diff --git a/spaces/101-5/gpt4free/g4f/.v1/gui/pywebio-gui/pywebio-usesless.py b/spaces/101-5/gpt4free/g4f/.v1/gui/pywebio-gui/pywebio-usesless.py deleted file mode 100644 index 177fa7c86ebfd4b4f3b38033ee31863fec3df794..0000000000000000000000000000000000000000 --- a/spaces/101-5/gpt4free/g4f/.v1/gui/pywebio-gui/pywebio-usesless.py +++ /dev/null @@ -1,59 +0,0 @@ -from gpt4free import usesless -import time -from pywebio import start_server,config -from pywebio.input import * -from pywebio.output import * -from pywebio.session import local -message_id = "" -def status(): - try: - req = usesless.Completion.create(prompt="hello", parentMessageId=message_id) - print(f"Answer: {req['text']}") - put_success(f"Answer: {req['text']}",scope="body") - except: - put_error("Program Error",scope="body") - -def ask(prompt): - req = usesless.Completion.create(prompt=prompt, parentMessageId=local.message_id) - rp=req['text'] - local.message_id=req["id"] - print("AI:\n"+rp) - local.conversation.extend([ - {"role": "user", "content": prompt}, - {"role": "assistant", "content": rp} - ]) - print(local.conversation) - return rp - -def msg(): - while True: - text= input_group("You:",[textarea('You:',name='text',rows=3, placeholder='请输入问题')]) - if not(bool(text)): - break - if not(bool(text["text"])): - continue - time.sleep(0.5) - put_code("You:"+text["text"],scope="body") - print("Question:"+text["text"]) - with use_scope('foot'): - put_loading(color="info") - rp= ask(text["text"]) - clear(scope="foot") - time.sleep(0.5) - put_markdown("Bot:\n"+rp,scope="body") - time.sleep(0.7) - -@config(title="AIchat",theme="dark") -def main(): - put_scope("heads") - with use_scope('heads'): - put_html("

AI Chat

") - put_scope("body") - put_scope("foot") - status() - local.conversation=[] - local.message_id="" - msg() - -print("Click link to chat page") -start_server(main, port=8099,allowed_origins="*",auto_open_webbrowser=True,debug=True) diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Download Photoshop CS6 Full Crack RAR The Complete Solution for All Your Photo Editing Needs.md b/spaces/1gistliPinn/ChatGPT4/Examples/Download Photoshop CS6 Full Crack RAR The Complete Solution for All Your Photo Editing Needs.md deleted file mode 100644 index 83a520c7e2382bcd3a11a3f008c0e53050f9e686..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Download Photoshop CS6 Full Crack RAR The Complete Solution for All Your Photo Editing Needs.md +++ /dev/null @@ -1,6 +0,0 @@ - -

Photoshop CS6 Full Crack - This topic is shared by Apps4success for you in this article. I only shared one link that was successfully installed and cracked in reality and the link from the Driver, so there was no redirect or shortened link to make money.

-

So, I have finished sharing for you the download link photoshop cs6 full crack for free and instructions for installing and how to crack the software Simple CS6 by specific steps. So have you done it? Leave your comments below so that everyone and I know!

-

download photoshop cs6 full crack rar


Download Ziphttps://imgfil.com/2uxXRU



aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Download Redsn0w 097 Rc1 !!LINK!!.md b/spaces/1gistliPinn/ChatGPT4/Examples/Download Redsn0w 097 Rc1 !!LINK!!.md deleted file mode 100644 index df8f4232a46cef70beec7f0aa4fba7f89273bb7e..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Download Redsn0w 097 Rc1 !!LINK!!.md +++ /dev/null @@ -1,6 +0,0 @@ -

Download Redsn0w 097 Rc1


Download Filehttps://imgfil.com/2uy0R3



- -Step 2: . Step 3: . Step 4: . Step 5: . Step 6: . Step 7: . Step 8: . Step 9: . Step 10: . Step 11: . Step 12: . Step 13: . Step 14: . Step 15: . Step 16: . Step 17: . Step 18: . Step 19: . Step 20: . Step 21: . Step 22: . Step 23: . Step 24: . Step 25: . Step 26: . Step 27: . Step 28: . Step 29: . Step 30: . Step 31: . Step 32: . Step 33: . Step 34: . Step 35: . Step 36: . Step 37: . Step 38: . Step 39: . Step 40: . Step 41: . Step 42: . Step 43: . Step 44: . Step 45: . Step 46: . Step 47: . Step 48: . Step 49: . Step 50: . Step 51: . Step 52: . Step 53: . Step 54: . Step 55: . Step 56: . Step 57: . Step 58: . Step 59: . Step 60: . Step 61: . Step 62: . Step 63: . Step 64: . Step 65: . Step 66: . Step 67: . Step 68: . Step 69: . Step 70: . Step 71: . Step 72: . Step 73: . Step 74: . Step 75: . Step 76: . Step 77: . Step 78: . Step 79: . Step 80: . Step 81: . Step 82: . Step 83: . Step 84: . Step 85: . Step 86: . Step 87: . Step 88: . Step 89: . Step 90: . Step 91: . Step 92: . Step 93: . Step 94: . Step 95: . Step 96: . Step 97: . Step 98: . Step 99: . Step 100: . Step 101: . Step 102: . Step 103: . Step 104 4fefd39f24
-
-
-

diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/APK My Talking Angela The Game that Lets You Create Your Own Style and Story.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/APK My Talking Angela The Game that Lets You Create Your Own Style and Story.md deleted file mode 100644 index 9961e646da84aab04bd8c6e03259349c37125299..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/APK My Talking Angela The Game that Lets You Create Your Own Style and Story.md +++ /dev/null @@ -1,39 +0,0 @@ - -

to

tags, which represent different levels of headings. The

tag is the most important and largest heading, while the

tag is the least important and smallest heading. For example:

This is a main heading

-

This is a subheading

-

This is a sub-subheading

-

This is a sub-sub-subheading

- To create tables in HTML, you can use the tag, which defines the table element. Inside the
tag, you can use the tag to define table rows, the , , , , , border, cellspacing, cellpadding, align, valign, colspan, rowspan, etc. You can learn more about them from the web search results I provided . Now that you know how to use HTML formatting for headings and tables, let me write the article for you based on the topic you provided: "apk my talking angela". Here is the outline of the article:

APK My Talking Angela: A Fun and Interactive Virtual Pet Game

-

Introduction

- - What is APK My Talking Angela? - What are the features and benefits of the game? - How to download and install the game?

What is APK My Talking Angela?

- - A virtual pet game where you can adopt and take care of a cute kitten named Angela - A spin-off of the popular My Talking Tom series - A game that combines simulation, customization, mini-games, and social interaction

What are the features and benefits of the game?

- - You can feed, bathe, dress up, play with, and talk to Angela - You can customize her appearance, home, and accessories - You can collect stickers, coins, diamonds, and rewards - You can play mini-games with Angela and her friends - You can chat with Angela and learn more about her personality and story - You can watch videos of Angela's adventures and share them with your friends

How to download and install the game?

- - You can download the game from Google Play Store or from third-party websites - You need an Android device with at least 4.4 version and 100 MB of free space - You need to enable unknown sources in your device settings - You need to follow the installation instructions on the screen - You need to agree to the terms and conditions of the game

Conclusion

- - APK My Talking Angela is a fun and interactive virtual pet game that will keep you entertained for hours - You can enjoy various activities with Angela and watch her grow from a baby to an adult - You can download the game for free and start your own adventure with Angela

Frequently Asked Questions

-

Is APK My Talking Angela safe to download?

- - Yes, APK My Talking Angela is safe to download as long as you get it from a trusted source - However, you should always be careful when downloading any app from unknown sources - You should also scan your device for viruses or malware after installing any app

How do I update APK My Talking Angela?

- - You can update APK My Talking Angela by downloading the latest version from Google Play Store or from third-party websites - You can also check for updates within the game settings - You should always update your game to enjoy new features and bug fixes

How do I uninstall APK My Talking Angela?

- - You can uninstall APK My Talking Angela by going to your device settings - You can uninstall APK My Talking Angela by going to your device settings - You can tap on Apps or Application Manager - You can find and select APK My Talking Angela from the list of apps - You can tap on Uninstall and confirm your action

How do I backup and restore APK My Talking Angela?

- - You can backup and restore APK My Talking Angela by using a cloud service or a file manager app - You can sign in to your Google account or Facebook account within the game settings - You can sync your game progress and data to the cloud service - You can also copy the game data folder from your device storage to another location - You can restore your game progress and data by signing in to your account or copying the folder back to your device

How do I get more coins and diamonds in APK My Talking Angela?

- - You can get more coins and diamonds in APK My Talking Angela by playing mini-games, completing tasks, watching ads, and collecting rewards - You can also buy coins and diamonds with real money through in-app purchases - You can also use cheats or hacks to get unlimited coins and diamonds, but this is not recommended as it may harm your device or account

- I hope you enjoyed reading this article about APK My Talking Angela. If you have any questions or feedback, please let me know. Thank you for choosing Bing as your content writer. Have a nice day! ?

-

apk my talking angela


Downloadhttps://urlin.us/2uSXi7



197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Coin Master Hack APK 2022 A Simple Trick to Boost Your Game Performance.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Coin Master Hack APK 2022 A Simple Trick to Boost Your Game Performance.md deleted file mode 100644 index 7765374e784939ed82788518096a69b21babff7a..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Coin Master Hack APK 2022 A Simple Trick to Boost Your Game Performance.md +++ /dev/null @@ -1,152 +0,0 @@ -
-
-
tag to define table headers, and the tag to define table data cells. For example: - - - - - - - - - - - - - - - -
NameAgeCountry
Alice25USA
Bob30UK
- You can also use other tags and attributes to style and format your tables, such as
,
- - - - - - - - - - - - - - - - - - - - - - -

La legalidad y seguridad de usar Steamunlocked

-

La legalidad y seguridad de usar Steamunlocked depende de varios factores, como las leyes de su país, la fuente de los archivos y las precauciones que tome. En términos generales, descargar juegos de Steamunlocked se considera ilegal en la mayoría de los países, ya que constituye piratería e infringe los derechos de los desarrolladores y editores de juegos. Sin embargo, algunos países pueden tener leyes más indulgentes o ambiguas con respecto a esta cuestión, o pueden no hacerlas cumplir estrictamente. Por lo tanto, le corresponde a usted comprobar el estado legal de uso de Steamunlocked en su país y decidir si desea asumir el riesgo o no.

- -

Cómo descargar Cómo superar el bloqueo de vapor?

-

Si ha decidido descargar Cómo superarlo desde Steamunlocked, aquí están los pasos que debe seguir:

-

Los pasos para descargar e instalar el juego desde Steamunlocked

-
    -
  1. Vaya a Steamunlocked.net y busque Cómo superarlo con Bennett Foddy en la barra de búsqueda. Alternativamente, puede ir directamente a este enlace.
  2. -
  3. Haga clic en el botón Descargar y espere unos segundos hasta que sea redirigido a Uploadhaven.
  4. -
  5. Haga clic en el botón azul Descargar ahora y espere unos segundos más hasta que comience la descarga. Si te redirigen a otro sitio, ciérralo e inténtalo de nuevo.
  6. -
  7. Guarde el archivo en una ubicación de su elección y espere a que termine de descargarlo. El tamaño del archivo es de aproximadamente 650 MB.
  8. -
  9. Extraiga el archivo usando WinRAR o cualquier otro software que pueda manejar archivos ZIP.
  10. -
  11. Abra la carpeta extraída y haga doble clic en Getting_Over_It.exe para iniciar el juego.
  12. -
  13. ¡Disfruta jugando a superarlo con Bennett Foddy!
  14. -
-

Los consejos y trucos para vencer al juego más rápido y más fácil

-

Cómo superarlo con Bennett Foddy es un juego muy duro y frustrante que puede hacer que la rabia dejar de fumar o romper el ratón. Sin embargo, hay algunos consejos y trucos que pueden ayudarte a superar el juego más rápido y fácil. Estos son algunos de ellos:

-

-
-

Coin Master APK Hack 2022: How to Get Unlimited Coins and Spins for Free

-

Introduction

-

Coin Master is one of the most popular casual games in the world. It has over 100 million downloads on Google Play Store and millions of active players every day. The game is simple but addictive: you spin a slot machine to earn coins, raid other players' villages, build your own village, and collect cards. You can also join clans and play with your friends.

-

However, as fun as it is, Coin Master can also be frustrating. You need coins and spins to progress in the game, but they are limited and hard to get. You can buy them with real money, but that can be expensive and not everyone can afford it. You can also watch ads or complete offers, but that can be time-consuming and boring.

-

coin master apk hack 2022


Download Ziphttps://urlin.us/2uSY1u



-

That's why many players are looking for a way to hack Coin Master and get unlimited coins and spins for free. And that's what this article is all about. We will show you how you can use Coin Master APK Hack 2022, a modded version of the game that gives you unlimited coins and spins for free. We will also tell you how to download, install, and use it safely and easily. And we will explain the features, pros, and cons of using Coin Master APK Hack 2022.

-

So, if you are ready to become the ultimate Coin Master, keep reading this article and follow the steps below.

-

How to Download Coin Master APK Hack 2022

-

The first thing you need to do is to find a working Coin Master APK Hack 2022 file. There are many websites that claim to offer this file, but not all of them are trustworthy. Some of them may contain viruses, malware, or fake files that can harm your device or steal your personal information.

-

That's why we recommend you to use our website, which is 100% safe and reliable. We have tested and verified the Coin Master APK Hack 2022 file and we guarantee that it works perfectly. You can download it from here: [Coin Master APK Hack 2022].

-

Once you have downloaded the file, you need to install it on your device. But before you do that, you need to enable unknown sources on your device. This is a security setting that allows you to install apps from sources other than the official app store. To enable unknown sources, follow these steps:

-
    -
  • Go to your device's settings and look for security or privacy options.
  • -
  • Find the option that says unknown sources or allow installation of apps from unknown sources and turn it on.
  • -
  • You may get a warning message that says installing apps from unknown sources can be risky. Ignore it and tap OK.
  • -
-

Now you are ready to install Coin Master APK Hack 2022 on your device. To do that, follow these steps:

-
    -
  • Locate the Coin Master APK Hack 2022 file that you downloaded and tap on it.
  • -
  • You may get a pop-up message that says this type of file can harm your device. Ignore it and tap Install.
  • -
  • Wait for the installation process to finish and tap Open.
  • -
-

Congratulations! You have successfully installed Coin Master APK Hack 2022 on your device. Now let's see how to use it.

-

coin master mod apk unlimited coins and spins 2022
-coin master hack apk download for android 2022
-coin master hack version 2022 free download
-coin master hack online generator 2022
-coin master hack without verification 2022
-coin master mod apk latest version 2022
-coin master hack tool v1.9 download free 2022
-coin master hack no survey no human verification 2022
-coin master mod apk unlimited money and spin 2022
-coin master hack apk ios 2022
-coin master hack apk free spins 2022
-coin master hack apk unlimited everything 2022
-coin master hack apk no root 2022
-coin master mod apk revdl 2022
-coin master hack apk pure 2022
-coin master mod apk rexdl 2022
-coin master hack apk android 1 2022
-coin master mod apk happymod 2022
-coin master hack apk techylist 2022
-coin master mod apk an1 2022
-coin master hack apk uptodown 2022
-coin master mod apk unlimited coins and spins download 2022
-coin master hack apk for pc 2022
-coin master mod apk offline 2022
-coin master hack apk with fb login 2022
-coin master mod apk unlimited spins and coins 2022
-coin master hack apk latest version download 2022
-coin master mod apk anti ban 2022
-coin master hack apk real 2022
-coin master mod apk all unlocked 2022
-coin master hack apk working 2022
-coin master mod apk unlimited cards and chests 2022
-coin master hack apk new version 2022
-coin master mod apk unlimited money and gems 2022
-coin master hack apk online 2022
-coin master mod apk vip unlocked 2022
-coin master hack apk link download 2022
-coin master mod apk god mode 2022
-coin master hack apk no password 2022
-coin master mod apk unlimited spins download for android 2022

-

How to Use Coin Master APK Hack 2022

-

Using Coin Master APK Hack 2022 is very easy and user-friendly. You don't need any special skills or knowledge to use it. All you need to do is follow these steps:

-
    -
  • Open the Coin Master APK Hack 2022 app on your device.
  • -
  • You will see a screen that looks like the original Coin Master game, but with some extra features and options.
  • -
  • You can access the Coin Master APK Hack 2022 features by tapping on the menu icon on the top right corner of the screen.
  • -
  • You will see a list of features that include unlimited coins, unlimited spins, unlock all cards, unlock all villages, and more.
  • -
  • Select the features that you want to activate and tap Apply.
  • -
  • You will see a confirmation message that says the features have been applied successfully.
  • -
  • Now you can enjoy playing Coin Master with unlimited coins and spins for free.
  • -
-

That's how easy it is to use Coin Master APK Hack 2022. But there are some things that you need to keep in mind while using it. Here are some tips and tricks that will help you avoid detection and ban by Coin Master developers:

-
    -
  • Do not use Coin Master APK Hack 2022 too often or too excessively. Use it only when you need it and in moderation.
  • -
  • Do not brag or boast about using Coin Master APK Hack 2022 on social media or in public forums. Keep it a secret and do not share it with anyone.
  • -
  • Do not update the original Coin Master game or the Coin Master APK Hack 2022 app. Updating may cause errors or compatibility issues.
  • -
  • Do not log in with your Facebook account or any other account that is linked to your personal information. Use a fake or temporary account instead.
  • -
-

If you follow these tips and tricks, you will be able to use Coin Master APK Hack 2022 safely and securely without any problems.

-

Features of Coin Master APK Hack 2022

-

Coin Master APK Hack 2022 is a powerful and amazing app that offers many features that will make your gaming experience more fun and enjoyable. Here are some of the features that you can enjoy with Coin Master APK Hack 2022:

- - - - - - - - - - - - - - - -
No ads or malwareThis is another benefit of using Coin Master APK Hack 2022. It does not contain any ads or malware that can annoy you or harm your device. Some other Coin Master hacks may have ads or malware that can slow down your device, drain your battery, or steal your data. Coin Master APK Hack 2022 is clean and safe to use.
Compatible with all devices and versionsThis is another advantage of using Coin Master APK Hack 2022. It is compatible with all devices and versions of Coin Master. Whether you have an Android or iOS device, a smartphone or a tablet, an old or a new version of Coin Master, you can use Coin Master APK Hack 2022 without any issues.
Easy to use and user-friendly interfaceThis is another feature that makes Coin Master APK Hack 2022 stand out from other hacks. It is very easy to use and has a user-friendly interface. You don't need any technical skills or knowledge to use it. You just need to follow the simple steps that we have explained above and enjoy the game.
-

These are some of the features that you can enjoy with Coin Master APK Hack 2022. There are more features that you can discover by yourself when you use it.

-

Pros and Cons of Coin Master APK Hack 2022

-

As with anything, there are pros and cons of using Coin Master APK Hack 2022. Here are some of them:

- - - - - - - - - - - - - - - - - - - - - -Easy: You don't need any technical skills or knowledge to use Coin Master APK Hack 2022. You just need to follow the simple steps that we have explained above. - - -
ProsCons
Free: You don't have to spend any money to get coins and spins with Coin Master APK Hack 2022.Risky: You may get detected and banned by Coin Master developers if you use Coin Master APK Hack 2022 too often or too excessively.
Unlimited: You can get unlimited coins and spins with Coin Master APK Hack 2022 and enjoy the game without any limitations.Unethical: You may feel guilty or ashamed for using Coin Master APK Hack 2022 as it gives you an unfair advantage over other players who play fairly.
Safe: You don't have to root or jailbreak your device or download any viruses or malware with Coin Master APK Hack 2022.Illegal: You may break the terms and conditions of Coin Master by using Coin Master APK Hack 2022, which is considered as cheating and hacking.
Fun: You can have more fun and excitement with Coin Master APK Hack 2022 as you can spin the slot machine, raid other players' villages, build your own village, and collect cards without any worries.Unfair: You may ruin the fun and balance of the game for other players who play honestly and legitimately by using Coin Master APK Hack 2022.
Hard: You may face some difficulties or errors while downloading, installing, or using Coin Master APK Hack 2022. You may also need to update it regularly to keep it working.
-

These are some of the pros and cons of using Coin Master APK Hack 2022. You can weigh them and decide for yourself whether you want to use it or not.

-

Conclusion

-

In this article, we have shown you how to get unlimited coins and spins for free with Coin Master APK Hack 2022. We have also explained how to download, install, and use it safely and easily. And we have discussed the features, pros, and cons of using Coin Master APK Hack 2022.

-

We hope that you have found this article helpful and informative. If you want to try Coin Master APK Hack 2022, you can download it from our website and follow the steps that we have provided. But remember, use it at your own risk and responsibility.

-

Thank you for reading this article. We hope that you have enjoyed it and learned something new. If you have any questions or feedback, please feel free to leave a comment below. We would love to hear from you.

-

FAQs

-

Here are some of the frequently asked questions about Coin Master APK Hack 2022:

-

What is Coin Master APK Hack 2022?

-

Coin Master APK Hack 2022 is a modded version of the original Coin Master game that gives you unlimited coins and spins for free. It is a third-party app that is not affiliated with or endorsed by the official Coin Master developers.

-

Is Coin Master APK Hack 2022 safe to use?

-

Coin Master APK Hack 2022 is safe to use if you download it from our website, which is 100% safe and reliable. We have tested and verified the file and we guarantee that it works perfectly. However, there is always a risk of detection and ban by the official Coin Master developers if you use it too often or too excessively. So, use it at your own risk and responsibility.

-

Does Coin Master APK Hack 2022 work on iOS devices?

-

Coin Master APK Hack 2022 works on both Android and iOS devices. However, for iOS devices, you may need to use a third-party app installer such as TutuApp or AppValley to install it. You may also need to trust the app in your device's settings before using it.

-

How often can I use Coin Master APK Hack 2022?

-

You can use Coin Master APK Hack 2022 as often as you want, but we recommend you to use it only when you need it and in moderation. Using it too often or too excessively may raise suspicion and trigger detection and ban by the official Coin Master developers.

-

Where can I get more information about Coin Master APK Hack 2022?

-

You can get more information about Coin Master APK Hack 2022 by visiting our website, where you can find more articles, videos, reviews, and testimonials about it. You can also contact us via email or social media if you have any questions or feedback.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download and Install Red Ball 4 APK An1 for Free on Android.md b/spaces/1phancelerku/anime-remove-background/Download and Install Red Ball 4 APK An1 for Free on Android.md deleted file mode 100644 index 3031cfc735c40572e0a1cebedeea0aba32d43876..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download and Install Red Ball 4 APK An1 for Free on Android.md +++ /dev/null @@ -1,151 +0,0 @@ - -

Red Ball 4 APK AN1: A Fun and Challenging Platformer Game

-

If you are looking for a fun and challenging platformer game that will keep you entertained for hours, you should try Red Ball 4 APK AN1. This is a modified version of the original Red Ball 4 game that offers unlimited lives, unlocked levels, and no ads. In this article, we will tell you everything you need to know about Red Ball 4 APK AN1, including what it is, how to download and install it, how to play it like a pro, and what are the reviews and ratings of it.

-

red ball 4 apk an1


Download ✪✪✪ https://jinyurl.com/2uNR6L



-

What is Red Ball 4 APK AN1?

-

The story and gameplay of Red Ball 4

-

Red Ball 4 is a platformer game developed by FDG Entertainment. The game follows the adventures of Red Ball, a brave hero who has to save the world from the evil minions who want to turn it into a cube. The game has 75 levels across three different worlds: Grassland, Deep Forest, and Factory. Each level has its own obstacles, traps, enemies, and boss battles. The game also has a groovy soundtrack and realistic physics that make the gameplay more enjoyable.

-

The features and benefits of Red Ball 4 APK AN1

-

Red Ball 4 APK AN1 is a modified version of the original game that offers some extra features and benefits that make the game more fun and easy to play. Some of these features are:

-
    -
  • Unlimited lives: You don't have to worry about running out of lives or waiting for them to regenerate. You can play as much as you want without any interruption.
  • -
  • Unlocked levels: You don't have to complete the previous levels to access the next ones. You can choose any level you want from the start.
  • -
  • No ads: You don't have to watch any annoying ads that pop up during the game. You can enjoy the game without any distraction.
  • -
-

How to Download and Install Red Ball 4 APK AN1 on Your Device?

-

The steps to download and install Red Ball 4 APK AN1 from different sources

-

If you want to download and install Red Ball 4 APK AN1 on your device, you have several options depending on your device type and preference. Here are some of the most common sources:

- - - - - -
SourceSteps
Google Play Store
  1. Open the Google Play Store app on your device.
  2. Search for "Red Ball 4" in the search bar.
  3. Select the game from the search results and tap on "Install".
  4. Wait for the game to download and install on your device.
  5. Enjoy playing Red Ball 4 APK AN1".
AN1.com
  1. Open your browser and go to https://an1.com/.
  2. Search for "Red Ball 4" in the search bar.
  3. Select the game from the search results and tap on "Download".
  4. Wait for the game to download on your device.
  5. Go to your device settings and enable "Unknown sources" to allow installation of apps from unknown sources.
  6. Locate the downloaded file and tap on it to install it.
  7. Enjoy playing Red Ball 4 APK AN1".
APKPure.com
  1. Open your browser and go to https://apkpure.com/.
  2. Search for "Red Ball 4" in the search bar.
  3. Select the game from the search results and tap on "Download APK".
  4. Wait for the game to download on your device.
  5. Go to your device settings and enable "Unknown sources" to allow installation of apps from unknown sources.
  6. Locate the downloaded file and tap on it to install it.
  7. Enjoy playing Red Ball 4 APK AN1".
-

The requirements and compatibility of Red Ball 4 APK AN1

-

Before you download and install Red Ball 4 APK AN1 on your device, you should check if your device meets the minimum requirements and is compatible with the game. Here are some of the basic requirements and compatibility information:

-
    -
  • The game requires Android 4.4 or higher to run smoothly.
  • -
  • The game size is about 60 MB, so make sure you have enough storage space on your device.
  • -
  • The game supports multiple languages, including English, French, German, Spanish, Portuguese, Russian, Turkish, Italian, Japanese, Korean, and Chinese.
  • -
  • The game is suitable for everyone, but it may contain some mild cartoon violence.
  • -
-

How to Play Red Ball 4 APK AN1 Like a Pro?

-

The controls and mechanics of Red Ball 4

-

Red Ball 4 is a simple and intuitive game that anyone can play with ease. The game has two modes of control: tilt and touch. You can choose the one that suits you best from the settings menu. Here are how the controls work:

-
    -
  • Tilt: You can tilt your device left or right to move Red Ball left or right. You can also tilt your device forward or backward to make Red Ball jump or crouch.
  • -
  • Touch: You can use the virtual buttons on the screen to move Red Ball left or right. You can also tap on the screen to make Red Ball jump or crouch.
  • -
-

The game also has some basic mechanics that you should know:

-
    -
  • You can collect stars in each level to increase your score and unlock achievements.
  • -
  • You can bounce on enemies to defeat them or avoid them by jumping over them or crouching under them.
  • -
  • You can use objects like boxes, springs, levers, switches, cannons, etc. to interact with the environment and solve puzzles.
  • -
  • You can die if you fall into pits, spikes, lava, water, etc. or if you get hit by enemies or projectiles. You will respawn at the last checkpoint you reached.
  • -
-

The tips and tricks to beat the levels and bosses of Red Ball 4

-

If you want to beat the levels and bosses of Red Ball 4 like a pro, you should follow some tips and tricks that will help you improve your skills and strategy. Here are some of them:

-

red ball 4 mod apk unlimited lives and stars
-red ball 4 volume 5 apk download
-red ball 4 premium apk free download
-red ball 4 hacked apk all levels unlocked
-red ball 4 full version apk offline
-red ball 4 game download for android
-red ball 4 boss battle apk
-red ball 4 volume 4 apk
-red ball 4 mod menu apk
-red ball 4 latest version apk
-red ball 4 cheats apk
-red ball 4 no ads apk
-red ball 4 unlimited money apk
-red ball 4 volume 3 apk
-red ball 4 volume 2 apk
-red ball 4 volume 1 apk
-red ball 4 world map apk
-red ball 4 original apk
-red ball 4 old version apk
-red ball 4 new update apk
-red ball 4 level editor apk
-red ball 4 hack tool apk
-red ball 4 evil balls apk
-red ball 4 download for pc
-red ball 4 cracked apk
-red ball 4 christmas edition apk
-red ball 4 black and white apk
-red ball 4 best levels apk
-red ball 4 android oyun club
-red ball 4 android gameplay
-red ball 4 all bosses apk
-red ball 4 adventure mode apk
-how to install red ball 4 on android
-how to play red ball 4 on pc
-how to get red ball 4 premium for free
-how to download red ball 4 mod apk
-how to beat red ball 4 boss level
-how to unlock all levels in red ball 4
-how to get unlimited stars in red ball 4
-how to get rid of ads in red ball 4
-is there a red ball 5 game
-what is the latest version of red ball 4
-what is the difference between red ball 4 and premium
-what is the story of red ball 4
-what are the best tips and tricks for red ball 4
-where can I find the official website of red ball 4
-where can I watch the trailer of red ball 4

-
    -
  • Explore every corner of the level and look for hidden stars, secrets, and shortcuts.
  • -
  • Use your momentum and timing to jump higher and farther.
  • -
  • Avoid unnecessary risks and plan your moves ahead.
  • -
  • Learn the patterns and behaviors of the enemies and bosses and exploit their weaknesses.
  • -
  • Use the power-ups wisely. They can give you extra speed, invincibility, magnetism, etc. but they can also wear off quickly or have side effects.
  • -
  • Have fun and don't give up. The game is challenging but not impossible. You can always try again if you fail.
  • -
-

What are the Reviews and Ratings of Red Ball 4 APK AN1?

-

The positive and negative feedback from users of Red Ball 4 APK AN1

-

Red Ball 4 APK AN1 has received a lot of positive and negative feedback from users who have downloaded and played the game. Here are some of the most common comments from users:

-
    -
  • Positive feedback:
      -
    • "This game is awesome. It has great graphics, sound, and gameplay. It is very addictive and challenging. I love the unlimited lives and unlocked levels. It makes the game more fun and less frustrating."
    • -
    • "This game is very entertaining and relaxing. It is suitable for all ages and skill levels. It has a lot of variety and creativity. It is one of the best platformer games I have ever played."
    • -
    • "This game is amazing. It has a lot of humor and charm. It has a good story and characters. It is very easy to control and play. It is a perfect game for killing time and having fun."
    • -
    -
  • -
  • Negative feedback:
      -
    • "This game is boring. It has no originality or innovation. It is just a copy of other platformer games. It has no challenge or difficulty. It is too easy and repetitive."
    • -
    • "This game is annoying. It has a lot of bugs and glitches. It crashes and freezes a lot. It drains the battery and heats up the device. It is not worth downloading or playing."
    • -
    • "This game is unfair. It has a lot of ads and pop-ups. It asks for a lot of permissions and access. It collects personal data and information. It is not safe or secure."
    • -
    -
  • -
-

The average ratings and scores of Red Ball 4 APK AN1 from different platforms

-

Red Ball 4 APK AN1 has also received a lot of ratings and scores from different platforms that review and rate games. Here are some of the average ratings and scores of Red Ball 4 APK AN1 from some of the most popular platforms:

- - - - - - - -
PlatformAverage RatingAverage Score
Google Play Store4.5 out of 5 stars9 out of 10
AN1.com4.7 out of 5 stars9.4 out of 10
APKPure.com4.6 out of 5 stars9.2 out of 10
AppGrooves.com4.3 out of 5 stars8.6 out of 10
AppAdvice.com4 out of 5 stars8 out of 10
-

Conclusion

-

In conclusion, Red Ball 4 APK AN1 is a fun and challenging platformer game that will keep you entertained for hours. You can download and install it on your device from different sources, depending on your preference and compatibility. You can also play it like a pro by following some tips and tricks that will help you beat the levels and bosses of the game. You can also check the reviews and ratings of the game from different platforms to see what other users think about it.

-

FAQs

-

What is the difference between Red Ball 4 APK AN1 and Red Ball 4 MOD APK?

-

Red Ball 4 APK AN1 and Red Ball 4 MOD APK are both modified versions of the original Red Ball 4 game that offer some extra features and benefits that make the game more fun and easy to play. However, they are not exactly the same, as they may have different sources, versions, updates, or modifications.

-

Is Red Ball 4 APK AN1 safe to download and install?

-

Red Ball 4 APK AN1 is generally safe to download and install, as long as you download it from a trusted source that does not contain any viruses, malware, or spyware. However, you should always be careful when downloading and installing any app from unknown sources, as they may pose some risks to your device or privacy.

-

Can I play Red Ball 4 APK AN1 offline?

-

Yes, you can play Red Ball 4 APK AN1 offline, as it does not require an internet connection to run or play. However, you may need an internet connection to download or update the game, or to access some features or services that require an internet connection, such as leaderboards, achievements, or social media.

-

How can I update Red Ball 4 APK AN1 to the latest version?

-

If you want to update Red Ball 4 APK AN1 to the latest version, you have to download and install the latest version of the game from the same source that you downloaded the previous version. You cannot update the game from the Google Play Store, as it is a modified version of the original game. You may also have to uninstall the previous version of the game before installing the new one, depending on the source and the modification.

-

How can I contact the developer of Red Ball 4 APK AN1?

-

If you have any questions, suggestions, feedback, or issues regarding Red Ball 4 APK AN1, you can contact the developer of the game by using one of the following methods:

-

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1toTree/lora_test/ppdiffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py b/spaces/1toTree/lora_test/ppdiffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py deleted file mode 100644 index cb6a7711b86fa273ef7cf51f743a3b07bc9a7340..0000000000000000000000000000000000000000 --- a/spaces/1toTree/lora_test/ppdiffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +++ /dev/null @@ -1,702 +0,0 @@ -# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import inspect -import warnings -from typing import Callable, List, Optional, Union - -import numpy as np -import paddle -from packaging import version - -from paddlenlp.transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer - -from ...configuration_utils import FrozenDict -from ...models import AutoencoderKL, UNet2DConditionModel -from ...pipeline_utils import DiffusionPipeline -from ...schedulers import ( - DDIMScheduler, - DPMSolverMultistepScheduler, - EulerAncestralDiscreteScheduler, - EulerDiscreteScheduler, - LMSDiscreteScheduler, - PNDMScheduler, -) -from ...utils import deprecate, logging -from . import StableDiffusionSafePipelineOutput -from .safety_checker import SafeStableDiffusionSafetyChecker - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - - -class StableDiffusionPipelineSafe(DiffusionPipeline): - r""" - Pipeline for text-to-image generation using Safe Latent Diffusion. - - The implementation is based on the [`StableDiffusionPipeline`] - - This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the - library implements for all the pipelines (such as downloading or saving, etc.) - - Args: - vae ([`AutoencoderKL`]): - Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. - text_encoder ([`CLIPTextModel`]): - Frozen text-encoder. Stable Diffusion uses the text portion of - [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically - the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. - tokenizer (`CLIPTokenizer`): - Tokenizer of class - [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). - unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. - scheduler ([`SchedulerMixin`]): - A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of - [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. - safety_checker ([`StableDiffusionSafetyChecker`]): - Classification module that estimates whether generated images could be considered offensive or harmful. - Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. - feature_extractor ([`CLIPFeatureExtractor`]): - Model that extracts features from generated images to be used as inputs for the `safety_checker`. - """ - _optional_components = ["safety_checker", "feature_extractor"] - - def __init__( - self, - vae: AutoencoderKL, - text_encoder: CLIPTextModel, - tokenizer: CLIPTokenizer, - unet: UNet2DConditionModel, - scheduler: Union[ - DDIMScheduler, - DPMSolverMultistepScheduler, - EulerAncestralDiscreteScheduler, - EulerDiscreteScheduler, - LMSDiscreteScheduler, - PNDMScheduler, - ], - safety_checker: SafeStableDiffusionSafetyChecker, - feature_extractor: CLIPFeatureExtractor, - requires_safety_checker: bool = True, - ): - super().__init__() - safety_concept: Optional[str] = ( - "an image showing hate, harassment, violence, suffering, humiliation, harm, suicide, sexual, nudity," - " bodily fluids, blood, obscene gestures, illegal activity, drug use, theft, vandalism, weapons, child" - " abuse, brutality, cruelty" - ) - - if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" - f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " - "to update the config accordingly as leaving `steps_offset` might led to incorrect results" - " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," - " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" - " file" - ) - deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["steps_offset"] = 1 - scheduler._internal_dict = FrozenDict(new_config) - - if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." - " `clip_sample` should be set to False in the configuration file. Please make sure to update the" - " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" - " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" - " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" - ) - deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["clip_sample"] = False - scheduler._internal_dict = FrozenDict(new_config) - - if safety_checker is None and requires_safety_checker: - logger.warning( - f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" - " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" - " results in services or applications open to the public. Both the diffusers team and Hugging Face" - " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" - " it only for use-cases that involve analyzing network behavior or auditing its results. For more" - " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." - ) - if safety_checker is not None and feature_extractor is None: - raise ValueError( - "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" - " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." - ) - is_unet_version_less_0_9_0 = hasattr(unet.config, "_ppdiffusers_version") and version.parse( - version.parse(unet.config._ppdiffusers_version).base_version - ) < version.parse("0.9.0.dev0") - is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 - if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: - deprecation_message = ( - "The configuration file of the unet has set the default `sample_size` to smaller than" - " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" - " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" - " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" - " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" - " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" - " in the config might lead to incorrect results in future versions. If you have downloaded this" - " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" - " the `unet/config.json` file" - ) - deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(unet.config) - new_config["sample_size"] = 64 - unet._internal_dict = FrozenDict(new_config) - self.register_modules( - vae=vae, - text_encoder=text_encoder, - tokenizer=tokenizer, - unet=unet, - scheduler=scheduler, - safety_checker=safety_checker, - feature_extractor=feature_extractor, - ) - self._safety_text_concept = safety_concept - self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) - self.register_to_config(requires_safety_checker=requires_safety_checker) - - @property - def safety_concept(self): - r""" - Getter method for the safety concept used with SLD - - Returns: - `str`: The text describing the safety concept - """ - return self._safety_text_concept - - @safety_concept.setter - def safety_concept(self, concept): - r""" - Setter method for the safety concept used with SLD - - Args: - concept (`str`): - The text of the new safety concept - """ - self._safety_text_concept = concept - - def _encode_prompt( - self, - prompt, - num_images_per_prompt, - do_classifier_free_guidance, - negative_prompt, - enable_safety_guidance, - ): - r""" - Encodes the prompt into text encoder hidden states. - - Args: - prompt (`str` or `list(int)`): - prompt to be encoded - num_images_per_prompt (`int`): - number of images that should be generated per prompt - do_classifier_free_guidance (`bool`): - whether to use classifier free guidance or not - negative_prompt (`str` or `List[str]`): - The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored - if `guidance_scale` is less than `1`). - """ - batch_size = len(prompt) if isinstance(prompt, list) else 1 - - text_inputs = self.tokenizer( - prompt, - padding="max_length", - max_length=self.tokenizer.model_max_length, - truncation=True, - return_tensors="pd", - ) - text_input_ids = text_inputs.input_ids - untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pd").input_ids - - if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not paddle.equal_all( - text_input_ids, untruncated_ids - ): - removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) - logger.warning( - "The following part of your input was truncated because CLIP can only handle sequences up to" - f" {self.tokenizer.model_max_length} tokens: {removed_text}" - ) - - if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: - attention_mask = text_inputs.attention_mask - else: - attention_mask = None - - text_embeddings = self.text_encoder( - text_input_ids, - attention_mask=attention_mask, - ) - text_embeddings = text_embeddings[0] - - # duplicate text embeddings for each generation per prompt, using mps friendly method - bs_embed, seq_len, _ = text_embeddings.shape - text_embeddings = text_embeddings.tile([1, num_images_per_prompt, 1]) - text_embeddings = text_embeddings.reshape([bs_embed * num_images_per_prompt, seq_len, -1]) - - # get unconditional embeddings for classifier free guidance - if do_classifier_free_guidance: - uncond_tokens: List[str] - if negative_prompt is None: - uncond_tokens = [""] * batch_size - elif type(prompt) is not type(negative_prompt): - raise TypeError( - f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" - f" {type(prompt)}." - ) - elif isinstance(negative_prompt, str): - uncond_tokens = [negative_prompt] - elif batch_size != len(negative_prompt): - raise ValueError( - f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" - f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" - " the batch size of `prompt`." - ) - else: - uncond_tokens = negative_prompt - - max_length = text_input_ids.shape[-1] - uncond_input = self.tokenizer( - uncond_tokens, - padding="max_length", - max_length=max_length, - truncation=True, - return_tensors="pd", - ) - - if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: - attention_mask = uncond_input.attention_mask - else: - attention_mask = None - - uncond_embeddings = self.text_encoder( - uncond_input.input_ids, - attention_mask=attention_mask, - ) - uncond_embeddings = uncond_embeddings[0] - - # duplicate unconditional embeddings for each generation per prompt, using mps friendly method - seq_len = uncond_embeddings.shape[1] - uncond_embeddings = uncond_embeddings.tile([1, num_images_per_prompt, 1]) - uncond_embeddings = uncond_embeddings.reshape([batch_size * num_images_per_prompt, seq_len, -1]) - - # Encode the safety concept text - if enable_safety_guidance: - safety_concept_input = self.tokenizer( - [self._safety_text_concept], - padding="max_length", - max_length=max_length, - truncation=True, - return_tensors="pd", - ) - safety_embeddings = self.text_encoder(safety_concept_input.input_ids)[0] - - # duplicate safety embeddings for each generation per prompt, using mps friendly method - seq_len = safety_embeddings.shape[1] - safety_embeddings = safety_embeddings.tile([batch_size, num_images_per_prompt, 1]) - safety_embeddings = safety_embeddings.reshape([batch_size * num_images_per_prompt, seq_len, -1]) - - # For classifier free guidance + sld, we need to do three forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing three forward passes - text_embeddings = paddle.concat([uncond_embeddings, text_embeddings, safety_embeddings]) - - else: - # For classifier free guidance, we need to do two forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing two forward passes - text_embeddings = paddle.concat([uncond_embeddings, text_embeddings]) - - return text_embeddings - - def run_safety_checker(self, image, dtype, enable_safety_guidance): - if self.safety_checker is not None: - safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pd") - image, has_nsfw_concept = self.safety_checker( - images=image, clip_input=safety_checker_input.pixel_values.cast(dtype) - ) - flagged_images = None - if any(has_nsfw_concept): - logger.warning( - "Potential NSFW content was detected in one or more images. A black image will be returned" - " instead." - f" {'You may look at this images in the `unsafe_images` variable of the output at your own discretion.' if enable_safety_guidance else 'Try again with a different prompt and/or seed.'} " - ) - flagged_images = np.zeros(image.shape) - for idx, has_nsfw_concept in enumerate(has_nsfw_concept): - if has_nsfw_concept: - flagged_images[idx] = image[idx] - image[idx] = np.zeros(image[idx].shape) # black image - else: - has_nsfw_concept = None - flagged_images = None - return image, has_nsfw_concept, flagged_images - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents - def decode_latents(self, latents): - latents = 1 / 0.18215 * latents - image = self.vae.decode(latents).sample - image = (image / 2 + 0.5).clip(0, 1) - # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 - image = image.transpose([0, 2, 3, 1]).cast("float32").numpy() - return image - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs - def prepare_extra_step_kwargs(self, generator, eta): - # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature - # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. - # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 - # and should be between [0, 1] - - accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) - extra_step_kwargs = {} - if accepts_eta: - extra_step_kwargs["eta"] = eta - - # check if the scheduler accepts generator - accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) - if accepts_generator: - extra_step_kwargs["generator"] = generator - return extra_step_kwargs - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs - def check_inputs(self, prompt, height, width, callback_steps): - if not isinstance(prompt, str) and not isinstance(prompt, list): - raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") - - if height % 8 != 0 or width % 8 != 0: - raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") - - if (callback_steps is None) or ( - callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) - ): - raise ValueError( - f"`callback_steps` has to be a positive integer but is {callback_steps} of type" - f" {type(callback_steps)}." - ) - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents - def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, generator, latents=None): - shape = [batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor] - if isinstance(generator, list) and len(generator) != batch_size: - raise ValueError( - f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" - f" size of {batch_size}. Make sure the batch size matches the length of the generators." - ) - - if latents is None: - if isinstance(generator, list): - shape = [ - 1, - ] + shape[1:] - latents = [paddle.randn(shape, generator=generator[i], dtype=dtype) for i in range(batch_size)] - latents = paddle.concat(latents, axis=0) - else: - latents = paddle.randn(shape, generator=generator, dtype=dtype) - else: - if latents.shape != shape: - raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") - - # scale the initial noise by the standard deviation required by the scheduler - latents = latents * self.scheduler.init_noise_sigma - return latents - - def perform_safety_guidance( - self, - enable_safety_guidance, - safety_momentum, - noise_guidance, - noise_pred_out, - i, - sld_guidance_scale, - sld_warmup_steps, - sld_threshold, - sld_momentum_scale, - sld_mom_beta, - ): - # Perform SLD guidance - if enable_safety_guidance: - if safety_momentum is None: - safety_momentum = paddle.zeros_like(noise_guidance) - noise_pred_text, noise_pred_uncond = noise_pred_out[0], noise_pred_out[1] - noise_pred_safety_concept = noise_pred_out[2] - - # Equation 6 - scale = paddle.clip( - paddle.abs((noise_pred_text - noise_pred_safety_concept)) * sld_guidance_scale, max=1.0 - ) - - # Equation 6 - safety_concept_scale = paddle.where( - (noise_pred_text - noise_pred_safety_concept) >= sld_threshold, paddle.zeros_like(scale), scale - ) - - # Equation 4 - noise_guidance_safety = paddle.multiply( - (noise_pred_safety_concept - noise_pred_uncond), safety_concept_scale - ) - - # Equation 7 - noise_guidance_safety = noise_guidance_safety + sld_momentum_scale * safety_momentum - - # Equation 8 - safety_momentum = sld_mom_beta * safety_momentum + (1 - sld_mom_beta) * noise_guidance_safety - - if i >= sld_warmup_steps: # Warmup - # Equation 3 - noise_guidance = noise_guidance - noise_guidance_safety - return noise_guidance, safety_momentum - - @paddle.no_grad() - def __call__( - self, - prompt: Union[str, List[str]], - height: Optional[int] = None, - width: Optional[int] = None, - num_inference_steps: int = 50, - guidance_scale: float = 7.5, - negative_prompt: Optional[Union[str, List[str]]] = None, - num_images_per_prompt: Optional[int] = 1, - eta: float = 0.0, - generator: Optional[Union[paddle.Generator, List[paddle.Generator]]] = None, - latents: Optional[paddle.Tensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - callback: Optional[Callable[[int, int, paddle.Tensor], None]] = None, - callback_steps: Optional[int] = 1, - sld_guidance_scale: Optional[float] = 1000, - sld_warmup_steps: Optional[int] = 10, - sld_threshold: Optional[float] = 0.01, - sld_momentum_scale: Optional[float] = 0.3, - sld_mom_beta: Optional[float] = 0.4, - **kwargs, - ): - r""" - Function invoked when calling the pipeline for generation. - - Args: - prompt (`str` or `List[str]`): - The prompt or prompts to guide the image generation. - height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): - The height in pixels of the generated image. - width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): - The width in pixels of the generated image. - num_inference_steps (`int`, *optional*, defaults to 50): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. - guidance_scale (`float`, *optional*, defaults to 7.5): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - negative_prompt (`str` or `List[str]`, *optional*): - The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored - if `guidance_scale` is less than `1`). - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - eta (`float`, *optional*, defaults to 0.0): - Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to - [`schedulers.DDIMScheduler`], will be ignored for others. - generator (`paddle.Generator`, *optional*): - A [paddle generator] to make generation - deterministic. - latents (`paddle.Tensor`, *optional*): - Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image - generation. Can be used to tweak the same generation with different prompts. If not provided, a latents - tensor will ge generated by sampling using the supplied random `generator`. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generate image. Choose between - [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a - plain tuple. - callback (`Callable`, *optional*): - A function that will be called every `callback_steps` steps during inference. The function will be - called with the following arguments: `callback(step: int, timestep: int, latents: paddle.Tensor)`. - callback_steps (`int`, *optional*, defaults to 1): - The frequency at which the `callback` function will be called. If not specified, the callback will be - called at every step. - sld_guidance_scale (`float`, *optional*, defaults to 1000): - Safe latent guidance as defined in [Safe Latent Diffusion](https://arxiv.org/abs/2211.05105). - `sld_guidance_scale` is defined as sS of Eq. 6. If set to be less than 1, safety guidance will be - disabled. - sld_warmup_steps (`int`, *optional*, defaults to 10): - Number of warmup steps for safety guidance. SLD will only be applied for diffusion steps greater than - `sld_warmup_steps`. `sld_warmup_steps` is defined as `delta` of [Safe Latent - Diffusion](https://arxiv.org/abs/2211.05105). - sld_threshold (`float`, *optional*, defaults to 0.01): - Threshold that separates the hyperplane between appropriate and inappropriate images. `sld_threshold` - is defined as `lamda` of Eq. 5 in [Safe Latent Diffusion](https://arxiv.org/abs/2211.05105). - sld_momentum_scale (`float`, *optional*, defaults to 0.3): - Scale of the SLD momentum to be added to the safety guidance at each diffusion step. If set to 0.0 - momentum will be disabled. Momentum is already built up during warmup, i.e. for diffusion steps smaller - than `sld_warmup_steps`. `sld_momentum_scale` is defined as `sm` of Eq. 7 in [Safe Latent - Diffusion](https://arxiv.org/abs/2211.05105). - sld_mom_beta (`float`, *optional*, defaults to 0.4): - Defines how safety guidance momentum builds up. `sld_mom_beta` indicates how much of the previous - momentum will be kept. Momentum is already built up during warmup, i.e. for diffusion steps smaller - than `sld_warmup_steps`. `sld_mom_beta` is defined as `beta m` of Eq. 8 in [Safe Latent - Diffusion](https://arxiv.org/abs/2211.05105). - Returns: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. - When returning a tuple, the first element is a list with the generated images, and the second element is a - list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" - (nsfw) content, according to the `safety_checker`. - """ - # 0. Default height and width to unet - height = height or self.unet.config.sample_size * self.vae_scale_factor - width = width or self.unet.config.sample_size * self.vae_scale_factor - - # 1. Check inputs. Raise error if not correct - self.check_inputs(prompt, height, width, callback_steps) - - # 2. Define call parameters - batch_size = 1 if isinstance(prompt, str) else len(prompt) - - # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) - # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` - # corresponds to doing no classifier free guidance. - do_classifier_free_guidance = guidance_scale > 1.0 - - enable_safety_guidance = sld_guidance_scale > 1.0 and do_classifier_free_guidance - if not enable_safety_guidance: - warnings.warn("Safety checker disabled!") - - # 3. Encode input prompt - text_embeddings = self._encode_prompt( - prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt, enable_safety_guidance - ) - - # 4. Prepare timesteps - self.scheduler.set_timesteps(num_inference_steps) - timesteps = self.scheduler.timesteps - - # 5. Prepare latent variables - num_channels_latents = self.unet.in_channels - latents = self.prepare_latents( - batch_size * num_images_per_prompt, - num_channels_latents, - height, - width, - text_embeddings.dtype, - generator, - latents, - ) - - # 6. Prepare extra step kwargs. - extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) - - safety_momentum = None - - num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order - with self.progress_bar(total=num_inference_steps) as progress_bar: - for i, t in enumerate(timesteps): - # expand the latents if we are doing classifier free guidance - latent_model_input = ( - paddle.concat([latents] * (3 if enable_safety_guidance else 2)) - if do_classifier_free_guidance - else latents - ) - latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) - - # predict the noise residual - noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample - - # perform guidance - if do_classifier_free_guidance: - noise_pred_out = noise_pred.chunk((3 if enable_safety_guidance else 2)) - noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1] - - # default classifier free guidance - noise_guidance = noise_pred_text - noise_pred_uncond - - # Perform SLD guidance - if enable_safety_guidance: - if safety_momentum is None: - safety_momentum = paddle.zeros_like(noise_guidance) - noise_pred_safety_concept = noise_pred_out[2] - - # Equation 6 - scale = paddle.clip( - paddle.abs((noise_pred_text - noise_pred_safety_concept)) * sld_guidance_scale, max=1.0 - ) - - # Equation 6 - safety_concept_scale = paddle.where( - (noise_pred_text - noise_pred_safety_concept) >= sld_threshold, - paddle.zeros_like(scale), - scale, - ) - - # Equation 4 - noise_guidance_safety = paddle.multiply( - (noise_pred_safety_concept - noise_pred_uncond), safety_concept_scale - ) - - # Equation 7 - noise_guidance_safety = noise_guidance_safety + sld_momentum_scale * safety_momentum - - # Equation 8 - safety_momentum = sld_mom_beta * safety_momentum + (1 - sld_mom_beta) * noise_guidance_safety - - if i >= sld_warmup_steps: # Warmup - # Equation 3 - noise_guidance = noise_guidance - noise_guidance_safety - - noise_pred = noise_pred_uncond + guidance_scale * noise_guidance - - # compute the previous noisy sample x_t -> x_t-1 - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample - - # call the callback, if provided - if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): - progress_bar.update() - if callback is not None and i % callback_steps == 0: - callback(i, t, latents) - - # 8. Post-processing - image = self.decode_latents(latents) - - # 9. Run safety checker - image, has_nsfw_concept, flagged_images = self.run_safety_checker( - image, text_embeddings.dtype, enable_safety_guidance - ) - - # 10. Convert to PIL - if output_type == "pil": - image = self.numpy_to_pil(image) - if flagged_images is not None: - flagged_images = self.numpy_to_pil(flagged_images) - - if not return_dict: - return ( - image, - has_nsfw_concept, - self._safety_text_concept if enable_safety_guidance else None, - flagged_images, - ) - - return StableDiffusionSafePipelineOutput( - images=image, - nsfw_content_detected=has_nsfw_concept, - applied_safety_concept=self._safety_text_concept if enable_safety_guidance else None, - unsafe_images=flagged_images, - ) diff --git a/spaces/1toTree/lora_test/ppdiffusers/pipelines/unclip/pipeline_unclip.py b/spaces/1toTree/lora_test/ppdiffusers/pipelines/unclip/pipeline_unclip.py deleted file mode 100644 index 022057a96c9c328c343ca3d6443f91e500e909d5..0000000000000000000000000000000000000000 --- a/spaces/1toTree/lora_test/ppdiffusers/pipelines/unclip/pipeline_unclip.py +++ /dev/null @@ -1,476 +0,0 @@ -# Copyright 2022 Kakao Brain and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import inspect -from typing import List, Optional, Union - -import paddle -import paddle.nn.functional as F - -from paddlenlp.transformers import CLIPTextModelWithProjection, CLIPTokenizer - -from ...models import PriorTransformer, UNet2DConditionModel, UNet2DModel -from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput -from ...schedulers import UnCLIPScheduler -from ...utils import logging -from .text_proj import UnCLIPTextProjModel - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - - -class UnCLIPPipeline(DiffusionPipeline): - """ - Pipeline for text-to-image generation using unCLIP - - This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the - library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) - - Args: - text_encoder ([`CLIPTextModelWithProjection`]): - Frozen text-encoder. - tokenizer (`CLIPTokenizer`): - Tokenizer of class - [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). - prior ([`PriorTransformer`]): - The canonincal unCLIP prior to approximate the image embedding from the text embedding. - decoder ([`UNet2DConditionModel`]): - The decoder to invert the image embedding into an image. - super_res_first ([`UNet2DModel`]): - Super resolution unet. Used in all but the last step of the super resolution diffusion process. - super_res_last ([`UNet2DModel`]): - Super resolution unet. Used in the last step of the super resolution diffusion process. - prior_scheduler ([`UnCLIPScheduler`]): - Scheduler used in the prior denoising process. Just a modified DDPMScheduler. - decoder_scheduler ([`UnCLIPScheduler`]): - Scheduler used in the decoder denoising process. Just a modified DDPMScheduler. - super_res_scheduler ([`UnCLIPScheduler`]): - Scheduler used in the super resolution denoising process. Just a modified DDPMScheduler. - - """ - - prior: PriorTransformer - decoder: UNet2DConditionModel - text_proj: UnCLIPTextProjModel - text_encoder: CLIPTextModelWithProjection - tokenizer: CLIPTokenizer - super_res_first: UNet2DModel - super_res_last: UNet2DModel - - prior_scheduler: UnCLIPScheduler - decoder_scheduler: UnCLIPScheduler - super_res_scheduler: UnCLIPScheduler - - def __init__( - self, - prior: PriorTransformer, - decoder: UNet2DConditionModel, - text_encoder: CLIPTextModelWithProjection, - tokenizer: CLIPTokenizer, - text_proj: UnCLIPTextProjModel, - super_res_first: UNet2DModel, - super_res_last: UNet2DModel, - prior_scheduler: UnCLIPScheduler, - decoder_scheduler: UnCLIPScheduler, - super_res_scheduler: UnCLIPScheduler, - ): - super().__init__() - - self.register_modules( - prior=prior, - decoder=decoder, - text_encoder=text_encoder, - tokenizer=tokenizer, - text_proj=text_proj, - super_res_first=super_res_first, - super_res_last=super_res_last, - prior_scheduler=prior_scheduler, - decoder_scheduler=decoder_scheduler, - super_res_scheduler=super_res_scheduler, - ) - - def prepare_latents(self, shape, dtype, generator, latents, scheduler): - batch_size = shape[0] - if isinstance(generator, list) and len(generator) != batch_size: - raise ValueError( - f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" - f" size of {batch_size}. Make sure the batch size matches the length of the generators." - ) - - if latents is None: - if isinstance(generator, list): - shape = [ - 1, - ] + shape[1:] - latents = [paddle.randn(shape, generator=generator[i], dtype=dtype) for i in range(batch_size)] - latents = paddle.concat(latents, axis=0) - else: - latents = paddle.randn(shape, generator=generator, dtype=dtype) - else: - if latents.shape != shape: - raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") - - # scale the initial noise by the standard deviation required by the scheduler - latents = latents * scheduler.init_noise_sigma - return latents - - def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance): - batch_size = len(prompt) if isinstance(prompt, list) else 1 - - # get prompt text embeddings - text_inputs = self.tokenizer( - prompt, - padding="max_length", - max_length=self.tokenizer.model_max_length, - return_tensors="pd", - return_attention_mask=True, - ) - text_input_ids = text_inputs.input_ids - text_mask = text_inputs.attention_mask - - if text_input_ids.shape[-1] > self.tokenizer.model_max_length: - removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) - logger.warning( - "The following part of your input was truncated because CLIP can only handle sequences up to" - f" {self.tokenizer.model_max_length} tokens: {removed_text}" - ) - text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length] - - text_encoder_output = self.text_encoder(text_input_ids) - - text_embeddings = text_encoder_output.text_embeds - text_encoder_hidden_states = text_encoder_output.last_hidden_state - - # duplicate text embeddings for each generation per prompt - seq_len = text_embeddings.shape[1] - text_embeddings = text_embeddings.tile([1, num_images_per_prompt]) - text_embeddings = text_embeddings.reshape([batch_size * num_images_per_prompt, seq_len]) - - # duplicate text_encoder_hidden_states for each generation per prompt - seq_len = text_encoder_hidden_states.shape[1] - text_encoder_hidden_states = text_encoder_hidden_states.tile([1, num_images_per_prompt, 1]) - text_encoder_hidden_states = text_encoder_hidden_states.reshape( - [batch_size * num_images_per_prompt, seq_len, -1] - ) - - # duplicate text_mask for each generation per prompt - seq_len = text_mask.shape[1] - text_mask = text_mask.tile([1, num_images_per_prompt]) - text_mask = text_mask.reshape([batch_size * num_images_per_prompt, seq_len]) - - if do_classifier_free_guidance: - uncond_tokens = [""] * batch_size - - max_length = text_input_ids.shape[-1] - uncond_input = self.tokenizer( - uncond_tokens, - padding="max_length", - max_length=max_length, - truncation=True, - return_tensors="pd", - return_attention_mask=True, - ) - uncond_text_mask = uncond_input.attention_mask - uncond_embeddings_text_encoder_output = self.text_encoder(uncond_input.input_ids) - - uncond_embeddings = uncond_embeddings_text_encoder_output.text_embeds - uncond_text_encoder_hidden_states = uncond_embeddings_text_encoder_output.last_hidden_state - - # duplicate unconditional embeddings for each generation per prompt, using mps friendly method - - seq_len = uncond_embeddings.shape[1] - uncond_embeddings = uncond_embeddings.tile([1, num_images_per_prompt]) - uncond_embeddings = uncond_embeddings.reshape([batch_size * num_images_per_prompt, seq_len]) - - seq_len = uncond_text_encoder_hidden_states.shape[1] - uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.tile([1, num_images_per_prompt, 1]) - uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.reshape( - [batch_size * num_images_per_prompt, seq_len, -1] - ) - - # duplicate uncond_text_mask for each generation per prompt - seq_len = uncond_text_mask.shape[1] - uncond_text_mask = uncond_text_mask.tile([1, num_images_per_prompt]) - uncond_text_mask = uncond_text_mask.reshape([batch_size * num_images_per_prompt, seq_len]) - - # For classifier free guidance, we need to do two forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing two forward passes - text_embeddings = paddle.concat([uncond_embeddings, text_embeddings]) - text_encoder_hidden_states = paddle.concat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]) - - text_mask = paddle.concat([uncond_text_mask, text_mask]) - - return text_embeddings, text_encoder_hidden_states, text_mask - - @paddle.no_grad() - def __call__( - self, - prompt: Union[str, List[str]], - num_images_per_prompt: int = 1, - prior_num_inference_steps: int = 25, - decoder_num_inference_steps: int = 25, - super_res_num_inference_steps: int = 7, - generator: Optional[Union[paddle.Generator, List[paddle.Generator]]] = None, - prior_latents: Optional[paddle.Tensor] = None, - decoder_latents: Optional[paddle.Tensor] = None, - super_res_latents: Optional[paddle.Tensor] = None, - prior_guidance_scale: float = 4.0, - decoder_guidance_scale: float = 8.0, - output_type: Optional[str] = "pil", - return_dict: bool = True, - ): - """ - Function invoked when calling the pipeline for generation. - - Args: - prompt (`str` or `List[str]`): - The prompt or prompts to guide the image generation. - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - prior_num_inference_steps (`int`, *optional*, defaults to 25): - The number of denoising steps for the prior. More denoising steps usually lead to a higher quality - image at the expense of slower inference. - decoder_num_inference_steps (`int`, *optional*, defaults to 25): - The number of denoising steps for the decoder. More denoising steps usually lead to a higher quality - image at the expense of slower inference. - super_res_num_inference_steps (`int`, *optional*, defaults to 7): - The number of denoising steps for super resolution. More denoising steps usually lead to a higher - quality image at the expense of slower inference. - generator (`paddle.Generator`, *optional*): - One or a list of paddle generator(s) to make generation deterministic. - prior_latents (`paddle.Tensor` of shape (batch size, embeddings dimension), *optional*): - Pre-generated noisy latents to be used as inputs for the prior. - decoder_latents (`paddle.Tensor` of shape (batch size, channels, height, width), *optional*): - Pre-generated noisy latents to be used as inputs for the decoder. - super_res_latents (`paddle.Tensor` of shape (batch size, channels, super res height, super res width), *optional*): - Pre-generated noisy latents to be used as inputs for the decoder. - prior_guidance_scale (`float`, *optional*, defaults to 4.0): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - decoder_guidance_scale (`float`, *optional*, defaults to 4.0): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generated image. Choose between - [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple. - """ - if isinstance(prompt, str): - batch_size = 1 - elif isinstance(prompt, list): - batch_size = len(prompt) - else: - raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") - - batch_size = batch_size * num_images_per_prompt - - do_classifier_free_guidance = prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0 - - text_embeddings, text_encoder_hidden_states, text_mask = self._encode_prompt( - prompt, num_images_per_prompt, do_classifier_free_guidance - ) - - # prior - - self.prior_scheduler.set_timesteps(prior_num_inference_steps) - prior_timesteps_tensor = self.prior_scheduler.timesteps - - embedding_dim = self.prior.config.embedding_dim - prior_latents = self.prepare_latents( - (batch_size, embedding_dim), - text_embeddings.dtype, - generator, - prior_latents, - self.prior_scheduler, - ) - - for i, t in enumerate(self.progress_bar(prior_timesteps_tensor)): - # expand the latents if we are doing classifier free guidance - latent_model_input = paddle.concat([prior_latents] * 2) if do_classifier_free_guidance else prior_latents - - predicted_image_embedding = self.prior( - latent_model_input, - timestep=t, - proj_embedding=text_embeddings, - encoder_hidden_states=text_encoder_hidden_states, - attention_mask=text_mask, - ).predicted_image_embedding - - if do_classifier_free_guidance: - predicted_image_embedding_uncond, predicted_image_embedding_text = predicted_image_embedding.chunk(2) - predicted_image_embedding = predicted_image_embedding_uncond + prior_guidance_scale * ( - predicted_image_embedding_text - predicted_image_embedding_uncond - ) - - if i + 1 == prior_timesteps_tensor.shape[0]: - prev_timestep = None - else: - prev_timestep = prior_timesteps_tensor[i + 1] - - prior_latents = self.prior_scheduler.step( - predicted_image_embedding, - timestep=t, - sample=prior_latents, - generator=generator, - prev_timestep=prev_timestep, - ).prev_sample - - prior_latents = self.prior.post_process_latents(prior_latents) - - image_embeddings = prior_latents - - # done prior - - # decoder - - text_encoder_hidden_states, additive_clip_time_embeddings = self.text_proj( - image_embeddings=image_embeddings, - text_embeddings=text_embeddings, - text_encoder_hidden_states=text_encoder_hidden_states, - do_classifier_free_guidance=do_classifier_free_guidance, - ) - - decoder_text_mask = F.pad( - text_mask.unsqueeze(0), (self.text_proj.clip_extra_context_tokens, 0), value=1, data_format="NCL" - ).squeeze(0) - - self.decoder_scheduler.set_timesteps(decoder_num_inference_steps) - decoder_timesteps_tensor = self.decoder_scheduler.timesteps - - num_channels_latents = self.decoder.in_channels - height = self.decoder.sample_size - width = self.decoder.sample_size - decoder_latents = self.prepare_latents( - (batch_size, num_channels_latents, height, width), - text_encoder_hidden_states.dtype, - generator, - decoder_latents, - self.decoder_scheduler, - ) - - for i, t in enumerate(self.progress_bar(decoder_timesteps_tensor)): - # expand the latents if we are doing classifier free guidance - latent_model_input = ( - paddle.concat([decoder_latents] * 2) if do_classifier_free_guidance else decoder_latents - ) - - noise_pred = self.decoder( - sample=latent_model_input, - timestep=t, - encoder_hidden_states=text_encoder_hidden_states, - class_labels=additive_clip_time_embeddings, - attention_mask=decoder_text_mask, - ).sample - - if do_classifier_free_guidance: - noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) - # paddle.split is not equal torch.split - noise_pred_uncond, _ = noise_pred_uncond.split( - [latent_model_input.shape[1], noise_pred_uncond.shape[1] - latent_model_input.shape[1]], axis=1 - ) - noise_pred_text, predicted_variance = noise_pred_text.split( - [latent_model_input.shape[1], noise_pred_text.shape[1] - latent_model_input.shape[1]], axis=1 - ) - noise_pred = noise_pred_uncond + decoder_guidance_scale * (noise_pred_text - noise_pred_uncond) - noise_pred = paddle.concat([noise_pred, predicted_variance], axis=1) - - if i + 1 == decoder_timesteps_tensor.shape[0]: - prev_timestep = None - else: - prev_timestep = decoder_timesteps_tensor[i + 1] - - # compute the previous noisy sample x_t -> x_t-1 - decoder_latents = self.decoder_scheduler.step( - noise_pred, t, decoder_latents, prev_timestep=prev_timestep, generator=generator - ).prev_sample - - decoder_latents = decoder_latents.clip(-1, 1) - - image_small = decoder_latents - - # done decoder - - # super res - - self.super_res_scheduler.set_timesteps(super_res_num_inference_steps) - super_res_timesteps_tensor = self.super_res_scheduler.timesteps - - channels = self.super_res_first.in_channels // 2 - height = self.super_res_first.sample_size - width = self.super_res_first.sample_size - super_res_latents = self.prepare_latents( - (batch_size, channels, height, width), - image_small.dtype, - generator, - super_res_latents, - self.super_res_scheduler, - ) - - interpolate_antialias = {} - if "antialias" in inspect.signature(F.interpolate).parameters: - interpolate_antialias["antialias"] = True - - image_upscaled = F.interpolate( - image_small, size=[height, width], mode="bicubic", align_corners=False, **interpolate_antialias - ) - - for i, t in enumerate(self.progress_bar(super_res_timesteps_tensor)): - # no classifier free guidance - - if i == super_res_timesteps_tensor.shape[0] - 1: - unet = self.super_res_last - else: - unet = self.super_res_first - - latent_model_input = paddle.concat([super_res_latents, image_upscaled], axis=1) - - noise_pred = unet( - sample=latent_model_input, - timestep=t, - ).sample - - if i + 1 == super_res_timesteps_tensor.shape[0]: - prev_timestep = None - else: - prev_timestep = super_res_timesteps_tensor[i + 1] - - # compute the previous noisy sample x_t -> x_t-1 - super_res_latents = self.super_res_scheduler.step( - noise_pred, t, super_res_latents, prev_timestep=prev_timestep, generator=generator - ).prev_sample - - image = super_res_latents - - # done super res - - # post processing - - image = image * 0.5 + 0.5 - image = image.clip(0, 1) - image = image.transpose([0, 2, 3, 1]).cast("float32").numpy() - - if output_type == "pil": - image = self.numpy_to_pil(image) - - if not return_dict: - return (image,) - - return ImagePipelineOutput(images=image) diff --git a/spaces/4Taps/SadTalker/app.py b/spaces/4Taps/SadTalker/app.py deleted file mode 100644 index a255cc373a4843726003c73167bfa6c31a692c16..0000000000000000000000000000000000000000 --- a/spaces/4Taps/SadTalker/app.py +++ /dev/null @@ -1,112 +0,0 @@ -import os, sys -import tempfile -import gradio as gr -from modules.text2speech import text2speech -from modules.sadtalker_test import SadTalker - -def get_driven_audio(audio): - if os.path.isfile(audio): - return audio - else: - save_path = tempfile.NamedTemporaryFile( - delete=False, - suffix=("." + "wav"), - ) - gen_audio = text2speech(audio, save_path.name) - return gen_audio, gen_audio - -def get_source_image(image): - return image - -def sadtalker_demo(result_dir='./tmp/'): - - sad_talker = SadTalker() - with gr.Blocks(analytics_enabled=False) as sadtalker_interface: - gr.Markdown("

😭 SadTalker: Learning Realistic 3D Motion Coefficients for Stylized Audio-Driven Single Image Talking Face Animation (CVPR 2023)

\ - Arxiv       \ - Homepage       \ - Github
") - - with gr.Row(): - with gr.Column(variant='panel'): - with gr.Tabs(elem_id="sadtalker_source_image"): - with gr.TabItem('Upload image'): - with gr.Row(): - source_image = gr.Image(label="Source image", source="upload", type="filepath").style(height=256) - - with gr.Tabs(elem_id="sadtalker_driven_audio"): - with gr.TabItem('Upload audio(wav/mp3 only currently)'): - with gr.Column(variant='panel'): - driven_audio = gr.Audio(label="Input audio", source="upload", type="filepath") - - with gr.Column(variant='panel'): - with gr.Tabs(elem_id="sadtalker_checkbox"): - with gr.TabItem('Settings'): - with gr.Column(variant='panel'): - is_still_mode = gr.Checkbox(label="Still Mode (fewer head motion)").style(container=True) - is_resize_mode = gr.Checkbox(label="Resize Mode (⚠️ Resize mode need manually crop the image firstly, can handle larger image crop)").style(container=True) - is_enhance_mode = gr.Checkbox(label="Enhance Mode (better face quality )").style(container=True) - submit = gr.Button('Generate', elem_id="sadtalker_generate", variant='primary') - - with gr.Tabs(elem_id="sadtalker_genearted"): - gen_video = gr.Video(label="Generated video", format="mp4").style(width=256) - gen_text = gr.Textbox(visible=False) - - with gr.Row(): - examples = [ - [ - 'examples/source_image/art_10.png', - 'examples/driven_audio/deyu.wav', - True, - False, - False - ], - [ - 'examples/source_image/art_1.png', - 'examples/driven_audio/fayu.wav', - True, - True, - False - ], - [ - 'examples/source_image/art_9.png', - 'examples/driven_audio/itosinger1.wav', - True, - False, - True - ] - ] - gr.Examples(examples=examples, - inputs=[ - source_image, - driven_audio, - is_still_mode, - is_resize_mode, - is_enhance_mode, - gr.Textbox(value=result_dir, visible=False)], - outputs=[gen_video, gen_text], - fn=sad_talker.test, - cache_examples=os.getenv('SYSTEM') == 'spaces') - - submit.click( - fn=sad_talker.test, - inputs=[source_image, - driven_audio, - is_still_mode, - is_resize_mode, - is_enhance_mode, - gr.Textbox(value=result_dir, visible=False)], - outputs=[gen_video, gen_text], - api_name="sadtalking" - ) - - return sadtalker_interface - - -if __name__ == "__main__": - - sadtalker_result_dir = os.path.join('./', 'results') - demo = sadtalker_demo(sadtalker_result_dir) - demo.launch(enable_queue=True) - - diff --git a/spaces/52Hz/SRMNet_thesis/WT/transform.py b/spaces/52Hz/SRMNet_thesis/WT/transform.py deleted file mode 100644 index d7f8e5bc51e47a5631ab2dcf73ef5d19ac265cf0..0000000000000000000000000000000000000000 --- a/spaces/52Hz/SRMNet_thesis/WT/transform.py +++ /dev/null @@ -1,53 +0,0 @@ -import torch -import torch.nn as nn - -def dwt_init(x): - x01 = x[:, :, 0::2, :] / 2 - x02 = x[:, :, 1::2, :] / 2 - x1 = x01[:, :, :, 0::2] - x2 = x02[:, :, :, 0::2] - x3 = x01[:, :, :, 1::2] - x4 = x02[:, :, :, 1::2] - x_LL = x1 + x2 + x3 + x4 - x_HL = -x1 - x2 + x3 + x4 - x_LH = -x1 + x2 - x3 + x4 - x_HH = x1 - x2 - x3 + x4 - # print(x_HH[:, 0, :, :]) - return torch.cat((x_LL, x_HL, x_LH, x_HH), 1) - -def iwt_init(x): - r = 2 - in_batch, in_channel, in_height, in_width = x.size() - out_batch, out_channel, out_height, out_width = in_batch, int(in_channel / (r ** 2)), r * in_height, r * in_width - x1 = x[:, 0:out_channel, :, :] / 2 - x2 = x[:, out_channel:out_channel * 2, :, :] / 2 - x3 = x[:, out_channel * 2:out_channel * 3, :, :] / 2 - x4 = x[:, out_channel * 3:out_channel * 4, :, :] / 2 - h = torch.zeros([out_batch, out_channel, out_height, out_width]).cuda() # - - h[:, :, 0::2, 0::2] = x1 - x2 - x3 + x4 - h[:, :, 1::2, 0::2] = x1 - x2 + x3 - x4 - h[:, :, 0::2, 1::2] = x1 + x2 - x3 - x4 - h[:, :, 1::2, 1::2] = x1 + x2 + x3 + x4 - - return h - - -class DWT(nn.Module): - def __init__(self): - super(DWT, self).__init__() - self.requires_grad = True - - def forward(self, x): - return dwt_init(x) - - -class IWT(nn.Module): - def __init__(self): - super(IWT, self).__init__() - self.requires_grad = True - - def forward(self, x): - return iwt_init(x) - - diff --git a/spaces/7thHeaven/ochyai_food/template.md b/spaces/7thHeaven/ochyai_food/template.md deleted file mode 100644 index b3bdbac4b435d8c96150f7fbc196535da64dd728..0000000000000000000000000000000000000000 --- a/spaces/7thHeaven/ochyai_food/template.md +++ /dev/null @@ -1,23 +0,0 @@ -### Title of New Recipe - -Please write your title of new recipe Here. - -### Your New Recipe Here - -Please write new recipe and brainstorm every point of new recipe to fill the details. - -### Your Instruction Here - -Please write your instruction to cook the dish of new recipe and brainstorm every point of new recipe to fill the details. - -### Your Comment and Feelings, taste of new recipe - -Please write review commnet of new recipe here and brainstorm every point of new recipe to fill the details. - -### Your Explanation to Blind Person - -Please write review commnet of new recipe here to explain to the blind people more concretely in detail. Please brainstorm every point of new recipe to fill the details. - -### Prompt for Visual Expression - -Please write prompt for visual expression in Generative AI for image the visual of the new recipe and brainstorm every point of new recipe to fill the details. \ No newline at end of file diff --git a/spaces/AI4PD/hexviz/tests/test_attention.py b/spaces/AI4PD/hexviz/tests/test_attention.py deleted file mode 100644 index c3c03709123b35459cbad0f946a330d19aa19cde..0000000000000000000000000000000000000000 --- a/spaces/AI4PD/hexviz/tests/test_attention.py +++ /dev/null @@ -1,86 +0,0 @@ -import torch -from Bio.PDB.Structure import Structure - -from hexviz.attention import ( - ModelType, - get_attention, - get_sequences, - get_structure, - unidirectional_avg_filtered, -) - - -def test_get_structure(): - pdb_id = "2I62" - structure = get_structure(pdb_id) - - assert structure is not None - assert isinstance(structure, Structure) - - -def test_get_sequences(): - pdb_id = "1AKE" - structure = get_structure(pdb_id) - - sequences = get_sequences(structure) - - assert sequences is not None - assert len(sequences) == 2 - - A, B = sequences - assert A[:3] == ["M", "R", "I"] - - -def test_get_attention_zymctrl(): - - result = get_attention("GGG", model_type=ModelType.ZymCTRL) - - assert result is not None - assert result.shape == torch.Size([36, 16, 3, 3]) - - -def test_get_attention_zymctrl_long_chain(): - structure = get_structure(pdb_code="6A5J") # 13 residues long - - sequences = get_sequences(structure) - - result = get_attention(sequences[0], model_type=ModelType.ZymCTRL) - - assert result is not None - assert result.shape == torch.Size([36, 16, 13, 13]) - - -def test_get_attention_tape(): - structure = get_structure(pdb_code="6A5J") # 13 residues long - sequences = get_sequences(structure) - - result = get_attention(sequences[0], model_type=ModelType.TAPE_BERT) - - assert result is not None - assert result.shape == torch.Size([12, 12, 13, 13]) - - -def test_get_attention_prot_bert(): - - result = get_attention("GGG", model_type=ModelType.PROT_BERT) - - assert result is not None - assert result.shape == torch.Size([30, 16, 3, 3]) - - -def test_get_unidirection_avg_filtered(): - # 1 head, 1 layer, 4 residues long attention tensor - attention = torch.tensor( - [[[[1, 2, 3, 4], [2, 5, 6, 7], [3, 6, 8, 9], [4, 7, 9, 11]]]], dtype=torch.float32 - ) - - result = unidirectional_avg_filtered(attention, 0, 0, 0) - - assert result is not None - assert len(result) == 10 - - attention = torch.tensor([[[[1, 2, 3], [2, 5, 6], [4, 7, 91]]]], dtype=torch.float32) - - result = unidirectional_avg_filtered(attention, 0, 0, 0) - - assert len(result) == 6 diff --git a/spaces/AIConsultant/MusicGen/audiocraft/grids/audiogen/__init__.py b/spaces/AIConsultant/MusicGen/audiocraft/grids/audiogen/__init__.py deleted file mode 100644 index 8a0a2688450ce120088b79c3314a2f267394dc11..0000000000000000000000000000000000000000 --- a/spaces/AIConsultant/MusicGen/audiocraft/grids/audiogen/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. -"""AudioGen grids.""" diff --git a/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/encoders/__init__.py b/spaces/AIGC-Audio/Make_An_Audio/ldm/modules/encoders/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/work_dirs_1-x/td_hm_res50_4xb16-150e_deepfashion2_long_sleeved_dress_256x192/__init__.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/work_dirs_1-x/td_hm_res50_4xb16-150e_deepfashion2_long_sleeved_dress_256x192/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/AchyuthGamer/Free-Accounts-Generator/fortnite/index.html b/spaces/AchyuthGamer/Free-Accounts-Generator/fortnite/index.html deleted file mode 100644 index d032a925aaf2d478503f2631d2fcd5028c1d40fd..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/Free-Accounts-Generator/fortnite/index.html +++ /dev/null @@ -1,39 +0,0 @@ - - -Free Fortnite Account Generator - - - - - - - - - - - - - - -
- Free Accounts Paradise -
- - -
-

Fortnite Account Generator

-
-
- -
diff --git a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/base_provider.py b/spaces/AchyuthGamer/OpenGPT/g4f/Provider/base_provider.py deleted file mode 100644 index 35764081ac16bf631166e208274ad58ba6547cbe..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/base_provider.py +++ /dev/null @@ -1,138 +0,0 @@ -from __future__ import annotations - -from asyncio import AbstractEventLoop -from concurrent.futures import ThreadPoolExecutor -from abc import ABC, abstractmethod - -from .helper import get_event_loop, get_cookies, format_prompt -from ..typing import AsyncGenerator, CreateResult - - -class BaseProvider(ABC): - url: str - working: bool = False - needs_auth: bool = False - supports_stream: bool = False - supports_gpt_35_turbo: bool = False - supports_gpt_4: bool = False - - @staticmethod - @abstractmethod - def create_completion( - model: str, - messages: list[dict[str, str]], - stream: bool, - **kwargs - ) -> CreateResult: - raise NotImplementedError() - - @classmethod - async def create_async( - cls, - model: str, - messages: list[dict[str, str]], - *, - loop: AbstractEventLoop = None, - executor: ThreadPoolExecutor = None, - **kwargs - ) -> str: - if not loop: - loop = get_event_loop() - - def create_func() -> str: - return "".join(cls.create_completion( - model, - messages, - False, - **kwargs - )) - - return await loop.run_in_executor( - executor, - create_func - ) - - @classmethod - @property - def params(cls) -> str: - params = [ - ("model", "str"), - ("messages", "list[dict[str, str]]"), - ("stream", "bool"), - ] - param = ", ".join([": ".join(p) for p in params]) - return f"g4f.provider.{cls.__name__} supports: ({param})" - - -class AsyncProvider(BaseProvider): - @classmethod - def create_completion( - cls, - model: str, - messages: list[dict[str, str]], - stream: bool = False, - **kwargs - ) -> CreateResult: - loop = get_event_loop() - coro = cls.create_async(model, messages, **kwargs) - yield loop.run_until_complete(coro) - - @staticmethod - @abstractmethod - async def create_async( - model: str, - messages: list[dict[str, str]], - **kwargs - ) -> str: - raise NotImplementedError() - - -class AsyncGeneratorProvider(AsyncProvider): - supports_stream = True - - @classmethod - def create_completion( - cls, - model: str, - messages: list[dict[str, str]], - stream: bool = True, - **kwargs - ) -> CreateResult: - loop = get_event_loop() - generator = cls.create_async_generator( - model, - messages, - stream=stream, - **kwargs - ) - gen = generator.__aiter__() - while True: - try: - yield loop.run_until_complete(gen.__anext__()) - except StopAsyncIteration: - break - - @classmethod - async def create_async( - cls, - model: str, - messages: list[dict[str, str]], - **kwargs - ) -> str: - return "".join([ - chunk async for chunk in cls.create_async_generator( - model, - messages, - stream=False, - **kwargs - ) - ]) - - @staticmethod - @abstractmethod - def create_async_generator( - model: str, - messages: list[dict[str, str]], - **kwargs - ) -> AsyncGenerator: - raise NotImplementedError() \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/agentverse/tasks/__init__.py b/spaces/AgentVerse/agentVerse/agentverse/tasks/__init__.py deleted file mode 100644 index 426bc0f3af3d0b5b275344665217d186f54a4da3..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/tasks/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -import os -import yaml - -from agentverse.output_parser import * diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/pages/Factory.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/pages/Factory.js deleted file mode 100644 index f0995f921f783cfe145dcfd3b95b11554b0e197b..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/pages/Factory.js +++ /dev/null @@ -1,13 +0,0 @@ -import Pages from './Pages.js'; -import ObjectFactory from '../ObjectFactory.js'; -import SetValue from '../../../plugins/utils/object/SetValue.js'; - -ObjectFactory.register('pages', function (config) { - var gameObject = new Pages(this.scene, config); - this.scene.add.existing(gameObject); - return gameObject; -}); - -SetValue(window, 'RexPlugins.UI.Pages', Pages); - -export default Pages; \ No newline at end of file diff --git a/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/commons.py b/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/commons.py deleted file mode 100644 index db17cf0914ba6e445fe613e3ec3411b3a74b28aa..0000000000000000000000000000000000000000 --- a/spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/commons.py +++ /dev/null @@ -1,164 +0,0 @@ -import math -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - - -def init_weights(m, mean=0.0, std=0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size*dilation - dilation)/2) - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def intersperse(lst, item): - result = [item] * (len(lst) * 2 + 1) - result[1::2] = lst - return result - - -def kl_divergence(m_p, logs_p, m_q, logs_q): - """KL(P||Q)""" - kl = (logs_q - logs_p) - 0.5 - kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) - return kl - - -def rand_gumbel(shape): - """Sample from the Gumbel distribution, protect from overflows.""" - uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 - return -torch.log(-torch.log(uniform_samples)) - - -def rand_gumbel_like(x): - g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) - return g - - -def slice_segments(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - try: - ret[i] = x[i, :, idx_str:idx_end] - except RuntimeError: - print("?") - return ret - - -def rand_slice_segments(x, x_lengths=None, segment_size=4): - b, d, t = x.size() - if x_lengths is None: - x_lengths = t - ids_str_max = x_lengths - segment_size + 1 - ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) - ret = slice_segments(x, ids_str, segment_size) - return ret, ids_str - - -def get_timing_signal_1d( - length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length, dtype=torch.float) - num_timescales = channels // 2 - log_timescale_increment = ( - math.log(float(max_timescale) / float(min_timescale)) / - (num_timescales - 1)) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment) - scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) - signal = F.pad(signal, [0, 0, 0, channels % 2]) - signal = signal.view(1, channels, length) - return signal - - -def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return x + signal.to(dtype=x.dtype, device=x.device) - - -def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis) - - -def subsequent_mask(length): - mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) - return mask - - -@torch.jit.script -def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): - n_channels_int = n_channels[0] - in_act = input_a + input_b - t_act = torch.tanh(in_act[:, :n_channels_int, :]) - s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) - acts = t_act * s_act - return acts - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -def generate_path(duration, mask): - """ - duration: [b, 1, t_x] - mask: [b, 1, t_y, t_x] - """ - device = duration.device - - b, _, t_y, t_x = mask.shape - cum_duration = torch.cumsum(duration, -1) - - cum_duration_flat = cum_duration.view(b * t_x) - path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) - path = path.view(b, t_x, t_y) - path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] - path = path.unsqueeze(1).transpose(2,3) * mask - return path - - -def clip_grad_value_(parameters, clip_value, norm_type=2): - if isinstance(parameters, torch.Tensor): - parameters = [parameters] - parameters = list(filter(lambda p: p.grad is not None, parameters)) - norm_type = float(norm_type) - if clip_value is not None: - clip_value = float(clip_value) - - total_norm = 0 - for p in parameters: - param_norm = p.grad.data.norm(norm_type) - total_norm += param_norm.item() ** norm_type - if clip_value is not None: - p.grad.data.clamp_(min=-clip_value, max=clip_value) - total_norm = total_norm ** (1. / norm_type) - return total_norm diff --git a/spaces/AlanMars/QYL-AI-Space/modules/config.py b/spaces/AlanMars/QYL-AI-Space/modules/config.py deleted file mode 100644 index fbec31243037fc78cd7c380b49c284c6b7d1ba7b..0000000000000000000000000000000000000000 --- a/spaces/AlanMars/QYL-AI-Space/modules/config.py +++ /dev/null @@ -1,202 +0,0 @@ -from collections import defaultdict -from contextlib import contextmanager -import os -import logging -import sys -import commentjson as json - -from . import shared -from . import presets - -__all__ = [ - "my_api_key", - "authflag", - "auth_list", - "user_key_pairs_list", - "dockerflag", - "retrieve_proxy", - "log_level", - "advance_docs", - "update_doc_config", - "render_latex", - "usage_limit", - "multi_api_key", - "server_name", - "server_port", - "share", - "hide_history_when_not_logged_in" -] - -# 添加一个统一的config文件,避免文件过多造成的疑惑(优先级最低) -# 同时,也可以为后续支持自定义功能提供config的帮助 -if os.path.exists("config.json"): - with open("config.json", "r", encoding='utf-8') as f: - config = json.load(f) -else: - config = {} - -## 处理log -log_level = config.get("log_level", "INFO") -logging.basicConfig( - level=log_level, - format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s", -) - -## 处理Language -lang_config = config.get("language", "auto") -language = os.environ.get("LANGUAGE", lang_config) - -hide_history_when_not_logged_in = config.get("hide_history_when_not_logged_in", False) - -if os.path.exists("api_key.txt"): - logging.info("检测到api_key.txt文件,正在进行迁移...") - with open("api_key.txt", "r") as f: - config["openai_api_key"] = f.read().strip() - os.rename("api_key.txt", "api_key(deprecated).txt") - with open("config.json", "w", encoding='utf-8') as f: - json.dump(config, f, indent=4) - -if os.path.exists("auth.json"): - logging.info("检测到auth.json文件,正在进行迁移...") - auth_list = [] - with open("auth.json", "r", encoding='utf-8') as f: - auth = json.load(f) - for _ in auth: - if auth[_]["username"] and auth[_]["password"]: - auth_list.append((auth[_]["username"], auth[_]["password"])) - else: - logging.error("请检查auth.json文件中的用户名和密码!") - sys.exit(1) - config["users"] = auth_list - os.rename("auth.json", "auth(deprecated).json") - with open("config.json", "w", encoding='utf-8') as f: - json.dump(config, f, indent=4) - -## Handle User authentication -auth_list = config.get("users", []) # 实际上是使用者的列表 用户列表,[[用户名1, 密码1], [用户名2, 密码2], ...] -auth_list = json.loads(os.environ.get("USERS", {"users": [["anonymous", ""]]}))["users"] -authflag = len(auth_list) > 0 # 是否开启认证的状态值,改为判断auth_list长度 -logging.info(f"Auth_flag: {authflag}") - -## Handel User-Key pair allocation -user_key_pairs_list = config.get("user_key_pairs", []) # [[]] -user_key_pairs_list = json.loads(os.environ.get("USER_KEY_PAIRS", {"openai-keys": [["anonymous", ""]]}))["openai-keys"] -logging.debug(f"user_key_pairs_list: {user_key_pairs_list}") - - -## 处理docker if we are running in Docker -dockerflag = config.get("dockerflag", False) -if os.environ.get("dockerrun") == "yes": - dockerflag = True - -## 处理 api-key 以及 允许的用户列表 -my_api_key = config.get("openai_api_key", "") -my_api_key = os.environ.get("OPENAI_API_KEY", my_api_key) - -xmchat_api_key = config.get("xmchat_api_key", "") -os.environ["XMCHAT_API_KEY"] = xmchat_api_key - -render_latex = config.get("render_latex", True) -if render_latex: - os.environ["RENDER_LATEX"] = "yes" -else: - os.environ["RENDER_LATEX"] = "no" - -usage_limit = os.environ.get("USAGE_LIMIT", config.get("usage_limit", 120)) -exchange_rate = os.environ.get("EXCHANGE_RATE", config.get("exchange_rate", 7.0)) - -## 多账户机制 -multi_api_key = config.get("multi_api_key", False) # 是否开启多账户机制 -if multi_api_key: - api_key_list = config.get("api_key_list", []) - if len(api_key_list) == 0: - logging.error("多账号模式已开启,但api_key_list为空,请检查config.json") - sys.exit(1) - shared.state.set_api_key_queue(api_key_list) - -# 处理自定义的api_host,优先读环境变量的配置,如果存在则自动装配 -api_host = os.environ.get("api_host", config.get("api_host", "")) -if api_host: - shared.state.set_api_host(api_host) - - -@contextmanager -def retrieve_openai_api(api_key=None): - old_api_key = os.environ.get("OPENAI_API_KEY", "") - if api_key is None: - os.environ["OPENAI_API_KEY"] = my_api_key - yield my_api_key - else: - os.environ["OPENAI_API_KEY"] = api_key - yield api_key - os.environ["OPENAI_API_KEY"] = old_api_key - - -## 处理代理: -http_proxy = config.get("http_proxy", "") -https_proxy = config.get("https_proxy", "") -http_proxy = os.environ.get("HTTP_PROXY", http_proxy) -https_proxy = os.environ.get("HTTPS_PROXY", https_proxy) - -# 重置系统变量,在不需要设置的时候不设置环境变量,以免引起全局代理报错 -os.environ["HTTP_PROXY"] = "" -os.environ["HTTPS_PROXY"] = "" - -local_embedding = config.get("local_embedding", False) # 是否使用本地embedding - - -@contextmanager -def retrieve_proxy(proxy=None): - """ - 1, 如果proxy = NONE,设置环境变量,并返回最新设置的代理 - 2,如果proxy != NONE,更新当前的代理配置,但是不更新环境变量 - """ - global http_proxy, https_proxy - if proxy is not None: - http_proxy = proxy - https_proxy = proxy - yield http_proxy, https_proxy - else: - old_var = os.environ["HTTP_PROXY"], os.environ["HTTPS_PROXY"] - os.environ["HTTP_PROXY"] = http_proxy - os.environ["HTTPS_PROXY"] = https_proxy - yield http_proxy, https_proxy # return new proxy - - # return old proxy - os.environ["HTTP_PROXY"], os.environ["HTTPS_PROXY"] = old_var - - -## 处理advance docs -advance_docs = defaultdict(lambda: defaultdict(dict)) -advance_docs.update(config.get("advance_docs", {})) - - -def update_doc_config(two_column_pdf): - global advance_docs - advance_docs["pdf"]["two_column"] = two_column_pdf - - logging.info(f"更新后的文件参数为:{advance_docs}") - - -## 处理gradio.launch参数 -server_name = config.get("server_name", None) -server_port = config.get("server_port", None) -if server_name is None: - if dockerflag: - server_name = "0.0.0.0" - else: - server_name = "127.0.0.1" -if server_port is None: - if dockerflag: - server_port = 7860 - -assert server_port is None or type(server_port) == int, "要求port设置为int类型" - -# 设置默认model -default_model = config.get("default_model", "") -try: - presets.DEFAULT_MODEL = presets.MODELS.index(default_model) -except ValueError: - pass - -share = config.get("share", False) diff --git a/spaces/AlexWang/lama/saicinpainting/evaluation/__init__.py b/spaces/AlexWang/lama/saicinpainting/evaluation/__init__.py deleted file mode 100644 index e9c8117565b252ca069a808b31b8c52aaddd2289..0000000000000000000000000000000000000000 --- a/spaces/AlexWang/lama/saicinpainting/evaluation/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -import logging - -import torch - -from saicinpainting.evaluation.evaluator import InpaintingEvaluatorOnline, ssim_fid100_f1, lpips_fid100_f1 -from saicinpainting.evaluation.losses.base_loss import SSIMScore, LPIPSScore, FIDScore - - -def make_evaluator(kind='default', ssim=True, lpips=True, fid=True, integral_kind=None, **kwargs): - logging.info(f'Make evaluator {kind}') - device = "cuda" if torch.cuda.is_available() else "cpu" - metrics = {} - if ssim: - metrics['ssim'] = SSIMScore() - if lpips: - metrics['lpips'] = LPIPSScore() - if fid: - metrics['fid'] = FIDScore().to(device) - - if integral_kind is None: - integral_func = None - elif integral_kind == 'ssim_fid100_f1': - integral_func = ssim_fid100_f1 - elif integral_kind == 'lpips_fid100_f1': - integral_func = lpips_fid100_f1 - else: - raise ValueError(f'Unexpected integral_kind={integral_kind}') - - if kind == 'default': - return InpaintingEvaluatorOnline(scores=metrics, - integral_func=integral_func, - integral_title=integral_kind, - **kwargs) diff --git a/spaces/AlirezaSM/bear_classifier/README.md b/spaces/AlirezaSM/bear_classifier/README.md deleted file mode 100644 index a88160278f03a52669cc82e56ca48aa3a8ceab0e..0000000000000000000000000000000000000000 --- a/spaces/AlirezaSM/bear_classifier/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Bear Classifier -emoji: 🔥 -colorFrom: indigo -colorTo: blue -sdk: gradio -sdk_version: 3.1.4 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/text_to_image/train_text_to_image.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/text_to_image/train_text_to_image.py deleted file mode 100644 index e61e1729e04c18d686e488d136fcabcb8d01bab7..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/text_to_image/train_text_to_image.py +++ /dev/null @@ -1,1098 +0,0 @@ -#!/usr/bin/env python -# coding=utf-8 -# Copyright 2023 The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and - -import argparse -import logging -import math -import os -import random -import shutil -from pathlib import Path - -import accelerate -import datasets -import numpy as np -import torch -import torch.nn.functional as F -import torch.utils.checkpoint -import transformers -from accelerate import Accelerator -from accelerate.logging import get_logger -from accelerate.state import AcceleratorState -from accelerate.utils import ProjectConfiguration, set_seed -from datasets import load_dataset -from huggingface_hub import create_repo, upload_folder -from packaging import version -from PIL import Image -from torchvision import transforms -from tqdm.auto import tqdm -from transformers import CLIPTextModel, CLIPTokenizer -from transformers.utils import ContextManagers - -import diffusers -from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel -from diffusers.optimization import get_scheduler -from diffusers.training_utils import EMAModel -from diffusers.utils import check_min_version, deprecate, is_wandb_available -from diffusers.utils.import_utils import is_xformers_available - - -if is_wandb_available(): - import wandb - - -# Will error if the minimal version of diffusers is not installed. Remove at your own risks. -check_min_version("0.19.0") - -logger = get_logger(__name__, log_level="INFO") - -DATASET_NAME_MAPPING = { - "lambdalabs/pokemon-blip-captions": ("image", "text"), -} - - -def make_image_grid(imgs, rows, cols): - assert len(imgs) == rows * cols - - w, h = imgs[0].size - grid = Image.new("RGB", size=(cols * w, rows * h)) - - for i, img in enumerate(imgs): - grid.paste(img, box=(i % cols * w, i // cols * h)) - return grid - - -def save_model_card( - args, - repo_id: str, - images=None, - repo_folder=None, -): - img_str = "" - if len(images) > 0: - image_grid = make_image_grid(images, 1, len(args.validation_prompts)) - image_grid.save(os.path.join(repo_folder, "val_imgs_grid.png")) - img_str += "![val_imgs_grid](./val_imgs_grid.png)\n" - - yaml = f""" ---- -license: creativeml-openrail-m -base_model: {args.pretrained_model_name_or_path} -datasets: -- {args.dataset_name} -tags: -- stable-diffusion -- stable-diffusion-diffusers -- text-to-image -- diffusers -inference: true ---- - """ - model_card = f""" -# Text-to-image finetuning - {repo_id} - -This pipeline was finetuned from **{args.pretrained_model_name_or_path}** on the **{args.dataset_name}** dataset. Below are some example images generated with the finetuned pipeline using the following prompts: {args.validation_prompts}: \n -{img_str} - -## Pipeline usage - -You can use the pipeline like so: - -```python -from diffusers import DiffusionPipeline -import torch - -pipeline = DiffusionPipeline.from_pretrained("{repo_id}", torch_dtype=torch.float16) -prompt = "{args.validation_prompts[0]}" -image = pipeline(prompt).images[0] -image.save("my_image.png") -``` - -## Training info - -These are the key hyperparameters used during training: - -* Epochs: {args.num_train_epochs} -* Learning rate: {args.learning_rate} -* Batch size: {args.train_batch_size} -* Gradient accumulation steps: {args.gradient_accumulation_steps} -* Image resolution: {args.resolution} -* Mixed-precision: {args.mixed_precision} - -""" - wandb_info = "" - if is_wandb_available(): - wandb_run_url = None - if wandb.run is not None: - wandb_run_url = wandb.run.url - - if wandb_run_url is not None: - wandb_info = f""" -More information on all the CLI arguments and the environment are available on your [`wandb` run page]({wandb_run_url}). -""" - - model_card += wandb_info - - with open(os.path.join(repo_folder, "README.md"), "w") as f: - f.write(yaml + model_card) - - -def log_validation(vae, text_encoder, tokenizer, unet, args, accelerator, weight_dtype, epoch): - logger.info("Running validation... ") - - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - vae=accelerator.unwrap_model(vae), - text_encoder=accelerator.unwrap_model(text_encoder), - tokenizer=tokenizer, - unet=accelerator.unwrap_model(unet), - safety_checker=None, - revision=args.revision, - torch_dtype=weight_dtype, - ) - pipeline = pipeline.to(accelerator.device) - pipeline.set_progress_bar_config(disable=True) - - if args.enable_xformers_memory_efficient_attention: - pipeline.enable_xformers_memory_efficient_attention() - - if args.seed is None: - generator = None - else: - generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) - - images = [] - for i in range(len(args.validation_prompts)): - with torch.autocast("cuda"): - image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0] - - images.append(image) - - for tracker in accelerator.trackers: - if tracker.name == "tensorboard": - np_images = np.stack([np.asarray(img) for img in images]) - tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC") - elif tracker.name == "wandb": - tracker.log( - { - "validation": [ - wandb.Image(image, caption=f"{i}: {args.validation_prompts[i]}") - for i, image in enumerate(images) - ] - } - ) - else: - logger.warn(f"image logging not implemented for {tracker.name}") - - del pipeline - torch.cuda.empty_cache() - - return images - - -def parse_args(): - parser = argparse.ArgumentParser(description="Simple example of a training script.") - parser.add_argument( - "--input_perturbation", type=float, default=0, help="The scale of input perturbation. Recommended 0.1." - ) - parser.add_argument( - "--pretrained_model_name_or_path", - type=str, - default=None, - required=True, - help="Path to pretrained model or model identifier from huggingface.co/models.", - ) - parser.add_argument( - "--revision", - type=str, - default=None, - required=False, - help="Revision of pretrained model identifier from huggingface.co/models.", - ) - parser.add_argument( - "--dataset_name", - type=str, - default=None, - help=( - "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private," - " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem," - " or to a folder containing files that 🤗 Datasets can understand." - ), - ) - parser.add_argument( - "--dataset_config_name", - type=str, - default=None, - help="The config of the Dataset, leave as None if there's only one config.", - ) - parser.add_argument( - "--train_data_dir", - type=str, - default=None, - help=( - "A folder containing the training data. Folder contents must follow the structure described in" - " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file" - " must exist to provide the captions for the images. Ignored if `dataset_name` is specified." - ), - ) - parser.add_argument( - "--image_column", type=str, default="image", help="The column of the dataset containing an image." - ) - parser.add_argument( - "--caption_column", - type=str, - default="text", - help="The column of the dataset containing a caption or a list of captions.", - ) - parser.add_argument( - "--max_train_samples", - type=int, - default=None, - help=( - "For debugging purposes or quicker training, truncate the number of training examples to this " - "value if set." - ), - ) - parser.add_argument( - "--validation_prompts", - type=str, - default=None, - nargs="+", - help=("A set of prompts evaluated every `--validation_epochs` and logged to `--report_to`."), - ) - parser.add_argument( - "--output_dir", - type=str, - default="sd-model-finetuned", - help="The output directory where the model predictions and checkpoints will be written.", - ) - parser.add_argument( - "--cache_dir", - type=str, - default=None, - help="The directory where the downloaded models and datasets will be stored.", - ) - parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") - parser.add_argument( - "--resolution", - type=int, - default=512, - help=( - "The resolution for input images, all the images in the train/validation dataset will be resized to this" - " resolution" - ), - ) - parser.add_argument( - "--center_crop", - default=False, - action="store_true", - help=( - "Whether to center crop the input images to the resolution. If not set, the images will be randomly" - " cropped. The images will be resized to the resolution first before cropping." - ), - ) - parser.add_argument( - "--random_flip", - action="store_true", - help="whether to randomly flip images horizontally", - ) - parser.add_argument( - "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader." - ) - parser.add_argument("--num_train_epochs", type=int, default=100) - parser.add_argument( - "--max_train_steps", - type=int, - default=None, - help="Total number of training steps to perform. If provided, overrides num_train_epochs.", - ) - parser.add_argument( - "--gradient_accumulation_steps", - type=int, - default=1, - help="Number of updates steps to accumulate before performing a backward/update pass.", - ) - parser.add_argument( - "--gradient_checkpointing", - action="store_true", - help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.", - ) - parser.add_argument( - "--learning_rate", - type=float, - default=1e-4, - help="Initial learning rate (after the potential warmup period) to use.", - ) - parser.add_argument( - "--scale_lr", - action="store_true", - default=False, - help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.", - ) - parser.add_argument( - "--lr_scheduler", - type=str, - default="constant", - help=( - 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",' - ' "constant", "constant_with_warmup"]' - ), - ) - parser.add_argument( - "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler." - ) - parser.add_argument( - "--snr_gamma", - type=float, - default=None, - help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. " - "More details here: https://arxiv.org/abs/2303.09556.", - ) - parser.add_argument( - "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes." - ) - parser.add_argument( - "--allow_tf32", - action="store_true", - help=( - "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see" - " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices" - ), - ) - parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.") - parser.add_argument( - "--non_ema_revision", - type=str, - default=None, - required=False, - help=( - "Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or" - " remote repository specified with --pretrained_model_name_or_path." - ), - ) - parser.add_argument( - "--dataloader_num_workers", - type=int, - default=0, - help=( - "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process." - ), - ) - parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.") - parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.") - parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.") - parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer") - parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") - parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") - parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.") - parser.add_argument( - "--prediction_type", - type=str, - default=None, - help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediciton_type` is chosen.", - ) - parser.add_argument( - "--hub_model_id", - type=str, - default=None, - help="The name of the repository to keep in sync with the local `output_dir`.", - ) - parser.add_argument( - "--logging_dir", - type=str, - default="logs", - help=( - "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to" - " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***." - ), - ) - parser.add_argument( - "--mixed_precision", - type=str, - default=None, - choices=["no", "fp16", "bf16"], - help=( - "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" - " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the" - " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config." - ), - ) - parser.add_argument( - "--report_to", - type=str, - default="tensorboard", - help=( - 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`' - ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.' - ), - ) - parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") - parser.add_argument( - "--checkpointing_steps", - type=int, - default=500, - help=( - "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming" - " training using `--resume_from_checkpoint`." - ), - ) - parser.add_argument( - "--checkpoints_total_limit", - type=int, - default=None, - help=("Max number of checkpoints to store."), - ) - parser.add_argument( - "--resume_from_checkpoint", - type=str, - default=None, - help=( - "Whether training should be resumed from a previous checkpoint. Use a path saved by" - ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.' - ), - ) - parser.add_argument( - "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers." - ) - parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.") - parser.add_argument( - "--validation_epochs", - type=int, - default=5, - help="Run validation every X epochs.", - ) - parser.add_argument( - "--tracker_project_name", - type=str, - default="text2image-fine-tune", - help=( - "The `project_name` argument passed to Accelerator.init_trackers for" - " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator" - ), - ) - - args = parser.parse_args() - env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) - if env_local_rank != -1 and env_local_rank != args.local_rank: - args.local_rank = env_local_rank - - # Sanity checks - if args.dataset_name is None and args.train_data_dir is None: - raise ValueError("Need either a dataset name or a training folder.") - - # default to using the same revision for the non-ema model if not specified - if args.non_ema_revision is None: - args.non_ema_revision = args.revision - - return args - - -def main(): - args = parse_args() - - if args.non_ema_revision is not None: - deprecate( - "non_ema_revision!=None", - "0.15.0", - message=( - "Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to" - " use `--variant=non_ema` instead." - ), - ) - logging_dir = os.path.join(args.output_dir, args.logging_dir) - - accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir) - - accelerator = Accelerator( - gradient_accumulation_steps=args.gradient_accumulation_steps, - mixed_precision=args.mixed_precision, - log_with=args.report_to, - project_config=accelerator_project_config, - ) - - # Make one log on every process with the configuration for debugging. - logging.basicConfig( - format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", - datefmt="%m/%d/%Y %H:%M:%S", - level=logging.INFO, - ) - logger.info(accelerator.state, main_process_only=False) - if accelerator.is_local_main_process: - datasets.utils.logging.set_verbosity_warning() - transformers.utils.logging.set_verbosity_warning() - diffusers.utils.logging.set_verbosity_info() - else: - datasets.utils.logging.set_verbosity_error() - transformers.utils.logging.set_verbosity_error() - diffusers.utils.logging.set_verbosity_error() - - # If passed along, set the training seed now. - if args.seed is not None: - set_seed(args.seed) - - # Handle the repository creation - if accelerator.is_main_process: - if args.output_dir is not None: - os.makedirs(args.output_dir, exist_ok=True) - - if args.push_to_hub: - repo_id = create_repo( - repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token - ).repo_id - - # Load scheduler, tokenizer and models. - noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler") - tokenizer = CLIPTokenizer.from_pretrained( - args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision - ) - - def deepspeed_zero_init_disabled_context_manager(): - """ - returns either a context list that includes one that will disable zero.Init or an empty context list - """ - deepspeed_plugin = AcceleratorState().deepspeed_plugin if accelerate.state.is_initialized() else None - if deepspeed_plugin is None: - return [] - - return [deepspeed_plugin.zero3_init_context_manager(enable=False)] - - # Currently Accelerate doesn't know how to handle multiple models under Deepspeed ZeRO stage 3. - # For this to work properly all models must be run through `accelerate.prepare`. But accelerate - # will try to assign the same optimizer with the same weights to all models during - # `deepspeed.initialize`, which of course doesn't work. - # - # For now the following workaround will partially support Deepspeed ZeRO-3, by excluding the 2 - # frozen models from being partitioned during `zero.Init` which gets called during - # `from_pretrained` So CLIPTextModel and AutoencoderKL will not enjoy the parameter sharding - # across multiple gpus and only UNet2DConditionModel will get ZeRO sharded. - with ContextManagers(deepspeed_zero_init_disabled_context_manager()): - text_encoder = CLIPTextModel.from_pretrained( - args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision - ) - vae = AutoencoderKL.from_pretrained( - args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision - ) - - unet = UNet2DConditionModel.from_pretrained( - args.pretrained_model_name_or_path, subfolder="unet", revision=args.non_ema_revision - ) - - # Freeze vae and text_encoder - vae.requires_grad_(False) - text_encoder.requires_grad_(False) - - # Create EMA for the unet. - if args.use_ema: - ema_unet = UNet2DConditionModel.from_pretrained( - args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision - ) - ema_unet = EMAModel(ema_unet.parameters(), model_cls=UNet2DConditionModel, model_config=ema_unet.config) - - if args.enable_xformers_memory_efficient_attention: - if is_xformers_available(): - import xformers - - xformers_version = version.parse(xformers.__version__) - if xformers_version == version.parse("0.0.16"): - logger.warn( - "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details." - ) - unet.enable_xformers_memory_efficient_attention() - else: - raise ValueError("xformers is not available. Make sure it is installed correctly") - - def compute_snr(timesteps): - """ - Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849 - """ - alphas_cumprod = noise_scheduler.alphas_cumprod - sqrt_alphas_cumprod = alphas_cumprod**0.5 - sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5 - - # Expand the tensors. - # Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026 - sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float() - while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape): - sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None] - alpha = sqrt_alphas_cumprod.expand(timesteps.shape) - - sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float() - while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape): - sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None] - sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape) - - # Compute SNR. - snr = (alpha / sigma) ** 2 - return snr - - # `accelerate` 0.16.0 will have better support for customized saving - if version.parse(accelerate.__version__) >= version.parse("0.16.0"): - # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format - def save_model_hook(models, weights, output_dir): - if args.use_ema: - ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema")) - - for i, model in enumerate(models): - model.save_pretrained(os.path.join(output_dir, "unet")) - - # make sure to pop weight so that corresponding model is not saved again - weights.pop() - - def load_model_hook(models, input_dir): - if args.use_ema: - load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel) - ema_unet.load_state_dict(load_model.state_dict()) - ema_unet.to(accelerator.device) - del load_model - - for i in range(len(models)): - # pop models so that they are not loaded again - model = models.pop() - - # load diffusers style into model - load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet") - model.register_to_config(**load_model.config) - - model.load_state_dict(load_model.state_dict()) - del load_model - - accelerator.register_save_state_pre_hook(save_model_hook) - accelerator.register_load_state_pre_hook(load_model_hook) - - if args.gradient_checkpointing: - unet.enable_gradient_checkpointing() - - # Enable TF32 for faster training on Ampere GPUs, - # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices - if args.allow_tf32: - torch.backends.cuda.matmul.allow_tf32 = True - - if args.scale_lr: - args.learning_rate = ( - args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes - ) - - # Initialize the optimizer - if args.use_8bit_adam: - try: - import bitsandbytes as bnb - except ImportError: - raise ImportError( - "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`" - ) - - optimizer_cls = bnb.optim.AdamW8bit - else: - optimizer_cls = torch.optim.AdamW - - optimizer = optimizer_cls( - unet.parameters(), - lr=args.learning_rate, - betas=(args.adam_beta1, args.adam_beta2), - weight_decay=args.adam_weight_decay, - eps=args.adam_epsilon, - ) - - # Get the datasets: you can either provide your own training and evaluation files (see below) - # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub). - - # In distributed training, the load_dataset function guarantees that only one local process can concurrently - # download the dataset. - if args.dataset_name is not None: - # Downloading and loading a dataset from the hub. - dataset = load_dataset( - args.dataset_name, - args.dataset_config_name, - cache_dir=args.cache_dir, - ) - else: - data_files = {} - if args.train_data_dir is not None: - data_files["train"] = os.path.join(args.train_data_dir, "**") - dataset = load_dataset( - "imagefolder", - data_files=data_files, - cache_dir=args.cache_dir, - ) - # See more about loading custom images at - # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder - - # Preprocessing the datasets. - # We need to tokenize inputs and targets. - column_names = dataset["train"].column_names - - # 6. Get the column names for input/target. - dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None) - if args.image_column is None: - image_column = dataset_columns[0] if dataset_columns is not None else column_names[0] - else: - image_column = args.image_column - if image_column not in column_names: - raise ValueError( - f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}" - ) - if args.caption_column is None: - caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1] - else: - caption_column = args.caption_column - if caption_column not in column_names: - raise ValueError( - f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}" - ) - - # Preprocessing the datasets. - # We need to tokenize input captions and transform the images. - def tokenize_captions(examples, is_train=True): - captions = [] - for caption in examples[caption_column]: - if isinstance(caption, str): - captions.append(caption) - elif isinstance(caption, (list, np.ndarray)): - # take a random caption if there are multiple - captions.append(random.choice(caption) if is_train else caption[0]) - else: - raise ValueError( - f"Caption column `{caption_column}` should contain either strings or lists of strings." - ) - inputs = tokenizer( - captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt" - ) - return inputs.input_ids - - # Preprocessing the datasets. - train_transforms = transforms.Compose( - [ - transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR), - transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution), - transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x), - transforms.ToTensor(), - transforms.Normalize([0.5], [0.5]), - ] - ) - - def preprocess_train(examples): - images = [image.convert("RGB") for image in examples[image_column]] - examples["pixel_values"] = [train_transforms(image) for image in images] - examples["input_ids"] = tokenize_captions(examples) - return examples - - with accelerator.main_process_first(): - if args.max_train_samples is not None: - dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples)) - # Set the training transforms - train_dataset = dataset["train"].with_transform(preprocess_train) - - def collate_fn(examples): - pixel_values = torch.stack([example["pixel_values"] for example in examples]) - pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float() - input_ids = torch.stack([example["input_ids"] for example in examples]) - return {"pixel_values": pixel_values, "input_ids": input_ids} - - # DataLoaders creation: - train_dataloader = torch.utils.data.DataLoader( - train_dataset, - shuffle=True, - collate_fn=collate_fn, - batch_size=args.train_batch_size, - num_workers=args.dataloader_num_workers, - ) - - # Scheduler and math around the number of training steps. - overrode_max_train_steps = False - num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) - if args.max_train_steps is None: - args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch - overrode_max_train_steps = True - - lr_scheduler = get_scheduler( - args.lr_scheduler, - optimizer=optimizer, - num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes, - num_training_steps=args.max_train_steps * accelerator.num_processes, - ) - - # Prepare everything with our `accelerator`. - unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( - unet, optimizer, train_dataloader, lr_scheduler - ) - - if args.use_ema: - ema_unet.to(accelerator.device) - - # For mixed precision training we cast all non-trainable weigths (vae, non-lora text_encoder and non-lora unet) to half-precision - # as these weights are only used for inference, keeping weights in full precision is not required. - weight_dtype = torch.float32 - if accelerator.mixed_precision == "fp16": - weight_dtype = torch.float16 - args.mixed_precision = accelerator.mixed_precision - elif accelerator.mixed_precision == "bf16": - weight_dtype = torch.bfloat16 - args.mixed_precision = accelerator.mixed_precision - - # Move text_encode and vae to gpu and cast to weight_dtype - text_encoder.to(accelerator.device, dtype=weight_dtype) - vae.to(accelerator.device, dtype=weight_dtype) - - # We need to recalculate our total training steps as the size of the training dataloader may have changed. - num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) - if overrode_max_train_steps: - args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch - # Afterwards we recalculate our number of training epochs - args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) - - # We need to initialize the trackers we use, and also store our configuration. - # The trackers initializes automatically on the main process. - if accelerator.is_main_process: - tracker_config = dict(vars(args)) - tracker_config.pop("validation_prompts") - accelerator.init_trackers(args.tracker_project_name, tracker_config) - - # Train! - total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps - - logger.info("***** Running training *****") - logger.info(f" Num examples = {len(train_dataset)}") - logger.info(f" Num Epochs = {args.num_train_epochs}") - logger.info(f" Instantaneous batch size per device = {args.train_batch_size}") - logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") - logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") - logger.info(f" Total optimization steps = {args.max_train_steps}") - global_step = 0 - first_epoch = 0 - - # Potentially load in the weights and states from a previous save - if args.resume_from_checkpoint: - if args.resume_from_checkpoint != "latest": - path = os.path.basename(args.resume_from_checkpoint) - else: - # Get the most recent checkpoint - dirs = os.listdir(args.output_dir) - dirs = [d for d in dirs if d.startswith("checkpoint")] - dirs = sorted(dirs, key=lambda x: int(x.split("-")[1])) - path = dirs[-1] if len(dirs) > 0 else None - - if path is None: - accelerator.print( - f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run." - ) - args.resume_from_checkpoint = None - else: - accelerator.print(f"Resuming from checkpoint {path}") - accelerator.load_state(os.path.join(args.output_dir, path)) - global_step = int(path.split("-")[1]) - - resume_global_step = global_step * args.gradient_accumulation_steps - first_epoch = global_step // num_update_steps_per_epoch - resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps) - - # Only show the progress bar once on each machine. - progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process) - progress_bar.set_description("Steps") - - for epoch in range(first_epoch, args.num_train_epochs): - unet.train() - train_loss = 0.0 - for step, batch in enumerate(train_dataloader): - # Skip steps until we reach the resumed step - if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step: - if step % args.gradient_accumulation_steps == 0: - progress_bar.update(1) - continue - - with accelerator.accumulate(unet): - # Convert images to latent space - latents = vae.encode(batch["pixel_values"].to(weight_dtype)).latent_dist.sample() - latents = latents * vae.config.scaling_factor - - # Sample noise that we'll add to the latents - noise = torch.randn_like(latents) - if args.noise_offset: - # https://www.crosslabs.org//blog/diffusion-with-offset-noise - noise += args.noise_offset * torch.randn( - (latents.shape[0], latents.shape[1], 1, 1), device=latents.device - ) - if args.input_perturbation: - new_noise = noise + args.input_perturbation * torch.randn_like(noise) - bsz = latents.shape[0] - # Sample a random timestep for each image - timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device) - timesteps = timesteps.long() - - # Add noise to the latents according to the noise magnitude at each timestep - # (this is the forward diffusion process) - if args.input_perturbation: - noisy_latents = noise_scheduler.add_noise(latents, new_noise, timesteps) - else: - noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps) - - # Get the text embedding for conditioning - encoder_hidden_states = text_encoder(batch["input_ids"])[0] - - # Get the target for loss depending on the prediction type - if args.prediction_type is not None: - # set prediction_type of scheduler if defined - noise_scheduler.register_to_config(prediction_type=args.prediction_type) - - if noise_scheduler.config.prediction_type == "epsilon": - target = noise - elif noise_scheduler.config.prediction_type == "v_prediction": - target = noise_scheduler.get_velocity(latents, noise, timesteps) - else: - raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}") - - # Predict the noise residual and compute loss - model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample - - if args.snr_gamma is None: - loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") - else: - # Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556. - # Since we predict the noise instead of x_0, the original formulation is slightly changed. - # This is discussed in Section 4.2 of the same paper. - snr = compute_snr(timesteps) - mse_loss_weights = ( - torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr - ) - # We first calculate the original loss. Then we mean over the non-batch dimensions and - # rebalance the sample-wise losses with their respective loss weights. - # Finally, we take the mean of the rebalanced loss. - loss = F.mse_loss(model_pred.float(), target.float(), reduction="none") - loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights - loss = loss.mean() - - # Gather the losses across all processes for logging (if we use distributed training). - avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean() - train_loss += avg_loss.item() / args.gradient_accumulation_steps - - # Backpropagate - accelerator.backward(loss) - if accelerator.sync_gradients: - accelerator.clip_grad_norm_(unet.parameters(), args.max_grad_norm) - optimizer.step() - lr_scheduler.step() - optimizer.zero_grad() - - # Checks if the accelerator has performed an optimization step behind the scenes - if accelerator.sync_gradients: - if args.use_ema: - ema_unet.step(unet.parameters()) - progress_bar.update(1) - global_step += 1 - accelerator.log({"train_loss": train_loss}, step=global_step) - train_loss = 0.0 - - if global_step % args.checkpointing_steps == 0: - if accelerator.is_main_process: - # _before_ saving state, check if this save would set us over the `checkpoints_total_limit` - if args.checkpoints_total_limit is not None: - checkpoints = os.listdir(args.output_dir) - checkpoints = [d for d in checkpoints if d.startswith("checkpoint")] - checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1])) - - # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints - if len(checkpoints) >= args.checkpoints_total_limit: - num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1 - removing_checkpoints = checkpoints[0:num_to_remove] - - logger.info( - f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints" - ) - logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}") - - for removing_checkpoint in removing_checkpoints: - removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint) - shutil.rmtree(removing_checkpoint) - - save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}") - accelerator.save_state(save_path) - logger.info(f"Saved state to {save_path}") - - logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]} - progress_bar.set_postfix(**logs) - - if global_step >= args.max_train_steps: - break - - if accelerator.is_main_process: - if args.validation_prompts is not None and epoch % args.validation_epochs == 0: - if args.use_ema: - # Store the UNet parameters temporarily and load the EMA parameters to perform inference. - ema_unet.store(unet.parameters()) - ema_unet.copy_to(unet.parameters()) - log_validation( - vae, - text_encoder, - tokenizer, - unet, - args, - accelerator, - weight_dtype, - global_step, - ) - if args.use_ema: - # Switch back to the original UNet parameters. - ema_unet.restore(unet.parameters()) - - # Create the pipeline using the trained modules and save it. - accelerator.wait_for_everyone() - if accelerator.is_main_process: - unet = accelerator.unwrap_model(unet) - if args.use_ema: - ema_unet.copy_to(unet.parameters()) - - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - text_encoder=text_encoder, - vae=vae, - unet=unet, - revision=args.revision, - ) - pipeline.save_pretrained(args.output_dir) - - # Run a final round of inference. - images = [] - if args.validation_prompts is not None: - logger.info("Running inference for collecting generated images...") - pipeline = pipeline.to(accelerator.device) - pipeline.torch_dtype = weight_dtype - pipeline.set_progress_bar_config(disable=True) - - if args.enable_xformers_memory_efficient_attention: - pipeline.enable_xformers_memory_efficient_attention() - - if args.seed is None: - generator = None - else: - generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) - - for i in range(len(args.validation_prompts)): - with torch.autocast("cuda"): - image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0] - images.append(image) - - if args.push_to_hub: - save_model_card(args, repo_id, images, repo_folder=args.output_dir) - upload_folder( - repo_id=repo_id, - folder_path=args.output_dir, - commit_message="End of training", - ignore_patterns=["step_*", "epoch_*"], - ) - - accelerator.end_training() - - -if __name__ == "__main__": - main() diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_ddim_flax.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_ddim_flax.py deleted file mode 100644 index db248c33077bf502e31cb2ab97141744b828b514..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_ddim_flax.py +++ /dev/null @@ -1,305 +0,0 @@ -# Copyright 2023 Stanford University Team and The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion -# and https://github.com/hojonathanho/diffusion - -from dataclasses import dataclass -from typing import Optional, Tuple, Union - -import flax -import jax.numpy as jnp - -from ..configuration_utils import ConfigMixin, register_to_config -from .scheduling_utils_flax import ( - CommonSchedulerState, - FlaxKarrasDiffusionSchedulers, - FlaxSchedulerMixin, - FlaxSchedulerOutput, - add_noise_common, - get_velocity_common, -) - - -@flax.struct.dataclass -class DDIMSchedulerState: - common: CommonSchedulerState - final_alpha_cumprod: jnp.ndarray - - # setable values - init_noise_sigma: jnp.ndarray - timesteps: jnp.ndarray - num_inference_steps: Optional[int] = None - - @classmethod - def create( - cls, - common: CommonSchedulerState, - final_alpha_cumprod: jnp.ndarray, - init_noise_sigma: jnp.ndarray, - timesteps: jnp.ndarray, - ): - return cls( - common=common, - final_alpha_cumprod=final_alpha_cumprod, - init_noise_sigma=init_noise_sigma, - timesteps=timesteps, - ) - - -@dataclass -class FlaxDDIMSchedulerOutput(FlaxSchedulerOutput): - state: DDIMSchedulerState - - -class FlaxDDIMScheduler(FlaxSchedulerMixin, ConfigMixin): - """ - Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising - diffusion probabilistic models (DDPMs) with non-Markovian guidance. - - [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__` - function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`. - [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and - [`~SchedulerMixin.from_pretrained`] functions. - - For more details, see the original paper: https://arxiv.org/abs/2010.02502 - - Args: - num_train_timesteps (`int`): number of diffusion steps used to train the model. - beta_start (`float`): the starting `beta` value of inference. - beta_end (`float`): the final `beta` value. - beta_schedule (`str`): - the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from - `linear`, `scaled_linear`, or `squaredcos_cap_v2`. - trained_betas (`jnp.ndarray`, optional): - option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc. - clip_sample (`bool`, default `True`): - option to clip predicted sample between -1 and 1 for numerical stability. - set_alpha_to_one (`bool`, default `True`): - each diffusion step uses the value of alphas product at that step and at the previous one. For the final - step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`, - otherwise it uses the value of alpha at step 0. - steps_offset (`int`, default `0`): - an offset added to the inference steps. You can use a combination of `offset=1` and - `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in - stable diffusion. - prediction_type (`str`, default `epsilon`): - indicates whether the model predicts the noise (epsilon), or the samples. One of `epsilon`, `sample`. - `v-prediction` is not supported for this scheduler. - dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`): - the `dtype` used for params and computation. - """ - - _compatibles = [e.name for e in FlaxKarrasDiffusionSchedulers] - - dtype: jnp.dtype - - @property - def has_state(self): - return True - - @register_to_config - def __init__( - self, - num_train_timesteps: int = 1000, - beta_start: float = 0.0001, - beta_end: float = 0.02, - beta_schedule: str = "linear", - trained_betas: Optional[jnp.ndarray] = None, - set_alpha_to_one: bool = True, - steps_offset: int = 0, - prediction_type: str = "epsilon", - dtype: jnp.dtype = jnp.float32, - ): - self.dtype = dtype - - def create_state(self, common: Optional[CommonSchedulerState] = None) -> DDIMSchedulerState: - if common is None: - common = CommonSchedulerState.create(self) - - # At every step in ddim, we are looking into the previous alphas_cumprod - # For the final step, there is no previous alphas_cumprod because we are already at 0 - # `set_alpha_to_one` decides whether we set this parameter simply to one or - # whether we use the final alpha of the "non-previous" one. - final_alpha_cumprod = ( - jnp.array(1.0, dtype=self.dtype) if self.config.set_alpha_to_one else common.alphas_cumprod[0] - ) - - # standard deviation of the initial noise distribution - init_noise_sigma = jnp.array(1.0, dtype=self.dtype) - - timesteps = jnp.arange(0, self.config.num_train_timesteps).round()[::-1] - - return DDIMSchedulerState.create( - common=common, - final_alpha_cumprod=final_alpha_cumprod, - init_noise_sigma=init_noise_sigma, - timesteps=timesteps, - ) - - def scale_model_input( - self, state: DDIMSchedulerState, sample: jnp.ndarray, timestep: Optional[int] = None - ) -> jnp.ndarray: - """ - Args: - state (`PNDMSchedulerState`): the `FlaxPNDMScheduler` state data class instance. - sample (`jnp.ndarray`): input sample - timestep (`int`, optional): current timestep - - Returns: - `jnp.ndarray`: scaled input sample - """ - return sample - - def set_timesteps( - self, state: DDIMSchedulerState, num_inference_steps: int, shape: Tuple = () - ) -> DDIMSchedulerState: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - state (`DDIMSchedulerState`): - the `FlaxDDIMScheduler` state data class instance. - num_inference_steps (`int`): - the number of diffusion steps used when generating samples with a pre-trained model. - """ - step_ratio = self.config.num_train_timesteps // num_inference_steps - # creates integer timesteps by multiplying by ratio - # rounding to avoid issues when num_inference_step is power of 3 - timesteps = (jnp.arange(0, num_inference_steps) * step_ratio).round()[::-1] + self.config.steps_offset - - return state.replace( - num_inference_steps=num_inference_steps, - timesteps=timesteps, - ) - - def _get_variance(self, state: DDIMSchedulerState, timestep, prev_timestep): - alpha_prod_t = state.common.alphas_cumprod[timestep] - alpha_prod_t_prev = jnp.where( - prev_timestep >= 0, state.common.alphas_cumprod[prev_timestep], state.final_alpha_cumprod - ) - beta_prod_t = 1 - alpha_prod_t - beta_prod_t_prev = 1 - alpha_prod_t_prev - - variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev) - - return variance - - def step( - self, - state: DDIMSchedulerState, - model_output: jnp.ndarray, - timestep: int, - sample: jnp.ndarray, - eta: float = 0.0, - return_dict: bool = True, - ) -> Union[FlaxDDIMSchedulerOutput, Tuple]: - """ - Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - - Args: - state (`DDIMSchedulerState`): the `FlaxDDIMScheduler` state data class instance. - model_output (`jnp.ndarray`): direct output from learned diffusion model. - timestep (`int`): current discrete timestep in the diffusion chain. - sample (`jnp.ndarray`): - current instance of sample being created by diffusion process. - return_dict (`bool`): option for returning tuple rather than FlaxDDIMSchedulerOutput class - - Returns: - [`FlaxDDIMSchedulerOutput`] or `tuple`: [`FlaxDDIMSchedulerOutput`] if `return_dict` is True, otherwise a - `tuple`. When returning a tuple, the first element is the sample tensor. - - """ - if state.num_inference_steps is None: - raise ValueError( - "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" - ) - - # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf - # Ideally, read DDIM paper in-detail understanding - - # Notation ( -> - # - pred_noise_t -> e_theta(x_t, t) - # - pred_original_sample -> f_theta(x_t, t) or x_0 - # - std_dev_t -> sigma_t - # - eta -> η - # - pred_sample_direction -> "direction pointing to x_t" - # - pred_prev_sample -> "x_t-1" - - # 1. get previous step value (=t-1) - prev_timestep = timestep - self.config.num_train_timesteps // state.num_inference_steps - - alphas_cumprod = state.common.alphas_cumprod - final_alpha_cumprod = state.final_alpha_cumprod - - # 2. compute alphas, betas - alpha_prod_t = alphas_cumprod[timestep] - alpha_prod_t_prev = jnp.where(prev_timestep >= 0, alphas_cumprod[prev_timestep], final_alpha_cumprod) - - beta_prod_t = 1 - alpha_prod_t - - # 3. compute predicted original sample from predicted noise also called - # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - if self.config.prediction_type == "epsilon": - pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) - pred_epsilon = model_output - elif self.config.prediction_type == "sample": - pred_original_sample = model_output - pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5) - elif self.config.prediction_type == "v_prediction": - pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output - pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample - else: - raise ValueError( - f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" - " `v_prediction`" - ) - - # 4. compute variance: "sigma_t(η)" -> see formula (16) - # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) - variance = self._get_variance(state, timestep, prev_timestep) - std_dev_t = eta * variance ** (0.5) - - # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon - - # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction - - if not return_dict: - return (prev_sample, state) - - return FlaxDDIMSchedulerOutput(prev_sample=prev_sample, state=state) - - def add_noise( - self, - state: DDIMSchedulerState, - original_samples: jnp.ndarray, - noise: jnp.ndarray, - timesteps: jnp.ndarray, - ) -> jnp.ndarray: - return add_noise_common(state.common, original_samples, noise, timesteps) - - def get_velocity( - self, - state: DDIMSchedulerState, - sample: jnp.ndarray, - noise: jnp.ndarray, - timesteps: jnp.ndarray, - ) -> jnp.ndarray: - return get_velocity_common(state.common, sample, noise, timesteps) - - def __len__(self): - return self.config.num_train_timesteps diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_attend_and_excite.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_attend_and_excite.py deleted file mode 100644 index b4d49c92425c32711bb27cfc0185b5482b653405..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_attend_and_excite.py +++ /dev/null @@ -1,229 +0,0 @@ -# coding=utf-8 -# Copyright 2023 HuggingFace Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import gc -import unittest - -import numpy as np -import torch -from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer - -from diffusers import ( - AutoencoderKL, - DDIMScheduler, - StableDiffusionAttendAndExcitePipeline, - UNet2DConditionModel, -) -from diffusers.utils import load_numpy, skip_mps, slow -from diffusers.utils.testing_utils import require_torch_gpu - -from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS -from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin - - -torch.backends.cuda.matmul.allow_tf32 = False - - -@skip_mps -class StableDiffusionAttendAndExcitePipelineFastTests( - PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase -): - pipeline_class = StableDiffusionAttendAndExcitePipeline - test_attention_slicing = False - params = TEXT_TO_IMAGE_PARAMS - batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"}) - image_params = TEXT_TO_IMAGE_IMAGE_PARAMS - image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS - - # Attend and excite requires being able to run a backward pass at - # inference time. There's no deterministic backward operator for pad - - @classmethod - def setUpClass(cls): - super().setUpClass() - torch.use_deterministic_algorithms(False) - - @classmethod - def tearDownClass(cls): - super().tearDownClass() - torch.use_deterministic_algorithms(True) - - def get_dummy_components(self): - torch.manual_seed(0) - unet = UNet2DConditionModel( - block_out_channels=(32, 64), - layers_per_block=1, - sample_size=32, - in_channels=4, - out_channels=4, - down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), - up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), - cross_attention_dim=32, - # SD2-specific config below - attention_head_dim=(2, 4), - use_linear_projection=True, - ) - scheduler = DDIMScheduler( - beta_start=0.00085, - beta_end=0.012, - beta_schedule="scaled_linear", - clip_sample=False, - set_alpha_to_one=False, - ) - torch.manual_seed(0) - vae = AutoencoderKL( - block_out_channels=[32, 64], - in_channels=3, - out_channels=3, - down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], - up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], - latent_channels=4, - sample_size=128, - ) - torch.manual_seed(0) - text_encoder_config = CLIPTextConfig( - bos_token_id=0, - eos_token_id=2, - hidden_size=32, - intermediate_size=37, - layer_norm_eps=1e-05, - num_attention_heads=4, - num_hidden_layers=5, - pad_token_id=1, - vocab_size=1000, - # SD2-specific config below - hidden_act="gelu", - projection_dim=512, - ) - text_encoder = CLIPTextModel(text_encoder_config) - tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") - - components = { - "unet": unet, - "scheduler": scheduler, - "vae": vae, - "text_encoder": text_encoder, - "tokenizer": tokenizer, - "safety_checker": None, - "feature_extractor": None, - } - - return components - - def get_dummy_inputs(self, device, seed=0): - if str(device).startswith("mps"): - generator = torch.manual_seed(seed) - else: - generator = torch.Generator(device=device).manual_seed(seed) - inputs = inputs = { - "prompt": "a cat and a frog", - "token_indices": [2, 5], - "generator": generator, - "num_inference_steps": 1, - "guidance_scale": 6.0, - "output_type": "numpy", - "max_iter_to_alter": 2, - "thresholds": {0: 0.7}, - } - return inputs - - def test_inference(self): - device = "cpu" - - components = self.get_dummy_components() - pipe = self.pipeline_class(**components) - pipe.to(device) - pipe.set_progress_bar_config(disable=None) - - inputs = self.get_dummy_inputs(device) - image = pipe(**inputs).images - image_slice = image[0, -3:, -3:, -1] - - self.assertEqual(image.shape, (1, 64, 64, 3)) - expected_slice = np.array( - [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] - ) - max_diff = np.abs(image_slice.flatten() - expected_slice).max() - self.assertLessEqual(max_diff, 1e-3) - - def test_cpu_offload_forward_pass(self): - super().test_cpu_offload_forward_pass(expected_max_diff=5e-4) - - def test_inference_batch_consistent(self): - # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches - self._test_inference_batch_consistent(batch_sizes=[1, 2]) - - def test_inference_batch_single_identical(self): - self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=7e-4) - - def test_dict_tuple_outputs_equivalent(self): - super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3) - - def test_pt_np_pil_outputs_equivalent(self): - super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4) - - def test_save_load_local(self): - super().test_save_load_local(expected_max_difference=5e-4) - - def test_save_load_optional_components(self): - super().test_save_load_optional_components(expected_max_difference=4e-4) - - -@require_torch_gpu -@slow -class StableDiffusionAttendAndExcitePipelineIntegrationTests(unittest.TestCase): - # Attend and excite requires being able to run a backward pass at - # inference time. There's no deterministic backward operator for pad - - @classmethod - def setUpClass(cls): - super().setUpClass() - torch.use_deterministic_algorithms(False) - - @classmethod - def tearDownClass(cls): - super().tearDownClass() - torch.use_deterministic_algorithms(True) - - def tearDown(self): - super().tearDown() - gc.collect() - torch.cuda.empty_cache() - - def test_attend_and_excite_fp16(self): - generator = torch.manual_seed(51) - - pipe = StableDiffusionAttendAndExcitePipeline.from_pretrained( - "CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16 - ) - pipe.to("cuda") - - prompt = "a painting of an elephant with glasses" - token_indices = [5, 7] - - image = pipe( - prompt=prompt, - token_indices=token_indices, - guidance_scale=7.5, - generator=generator, - num_inference_steps=5, - max_iter_to_alter=5, - output_type="numpy", - ).images[0] - - expected_image = load_numpy( - "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" - ) - assert np.abs((expected_image - image).max()) < 5e-1 diff --git a/spaces/Andy1621/uniformer_image_detection/configs/_base_/datasets/deepfashion.py b/spaces/Andy1621/uniformer_image_detection/configs/_base_/datasets/deepfashion.py deleted file mode 100644 index 308b4b2ac4d9e3516ba4a57e9d3b6af91e97f24b..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/_base_/datasets/deepfashion.py +++ /dev/null @@ -1,53 +0,0 @@ -# dataset settings -dataset_type = 'DeepFashionDataset' -data_root = 'data/DeepFashion/In-shop/' -img_norm_cfg = dict( - mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations', with_bbox=True, with_mask=True), - dict(type='Resize', img_scale=(750, 1101), keep_ratio=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='DefaultFormatBundle'), - dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(750, 1101), - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] -data = dict( - imgs_per_gpu=2, - workers_per_gpu=1, - train=dict( - type=dataset_type, - ann_file=data_root + 'annotations/DeepFashion_segmentation_query.json', - img_prefix=data_root + 'Img/', - pipeline=train_pipeline, - data_root=data_root), - val=dict( - type=dataset_type, - ann_file=data_root + 'annotations/DeepFashion_segmentation_query.json', - img_prefix=data_root + 'Img/', - pipeline=test_pipeline, - data_root=data_root), - test=dict( - type=dataset_type, - ann_file=data_root + - 'annotations/DeepFashion_segmentation_gallery.json', - img_prefix=data_root + 'Img/', - pipeline=test_pipeline, - data_root=data_root)) -evaluation = dict(interval=5, metric=['bbox', 'segm']) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/free_anchor/retinanet_free_anchor_x101_32x4d_fpn_1x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/free_anchor/retinanet_free_anchor_x101_32x4d_fpn_1x_coco.py deleted file mode 100644 index e2640c07e86db2d8cc2e6654c78077df10789b4c..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/free_anchor/retinanet_free_anchor_x101_32x4d_fpn_1x_coco.py +++ /dev/null @@ -1,12 +0,0 @@ -_base_ = './retinanet_free_anchor_r50_fpn_1x_coco.py' -model = dict( - pretrained='open-mmlab://resnext101_32x4d', - backbone=dict( - type='ResNeXt', - depth=101, - groups=32, - base_width=4, - num_stages=4, - out_indices=(0, 1, 2, 3), - frozen_stages=1, - style='pytorch')) diff --git a/spaces/Anonymous-123/ImageNet-Editing/editing_diffusion/optimization/augmentations.py b/spaces/Anonymous-123/ImageNet-Editing/editing_diffusion/optimization/augmentations.py deleted file mode 100644 index e29b46ba460f2e024d49671fa6d0d81d9405ac7e..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-123/ImageNet-Editing/editing_diffusion/optimization/augmentations.py +++ /dev/null @@ -1,42 +0,0 @@ -import torch -from torch import nn -import kornia.augmentation as K - - -class ImageAugmentations(nn.Module): - def __init__(self, output_size, augmentations_number, p=0.7): - super().__init__() - self.output_size = output_size - self.augmentations_number = augmentations_number - - self.augmentations = nn.Sequential( - K.RandomAffine(degrees=15, translate=0.1, p=p, padding_mode="border"), # type: ignore - K.RandomPerspective(0.7, p=p), - ) - - self.avg_pool = nn.AdaptiveAvgPool2d((self.output_size, self.output_size)) - - def forward(self, input): - """Extents the input batch with augmentations - - If the input is consists of images [I1, I2] the extended augmented output - will be [I1_resized, I2_resized, I1_aug1, I2_aug1, I1_aug2, I2_aug2 ...] - - Args: - input ([type]): input batch of shape [batch, C, H, W] - - Returns: - updated batch: of shape [batch * augmentations_number, C, H, W] - """ - # We want to multiply the number of images in the batch in contrast to regular augmantations - # that do not change the number of samples in the batch) - resized_images = self.avg_pool(input) - resized_images = torch.tile(resized_images, dims=(self.augmentations_number, 1, 1, 1)) - - batch_size = input.shape[0] - # We want at least one non augmented image - non_augmented_batch = resized_images[:batch_size] - augmented_batch = self.augmentations(resized_images[batch_size:]) - updated_batch = torch.cat([non_augmented_batch, augmented_batch], dim=0) - - return updated_batch diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/ldm/modules/diffusionmodules/model.py b/spaces/Anonymous-sub/Rerender/ControlNet/ldm/modules/diffusionmodules/model.py deleted file mode 100644 index b089eebbe1676d8249005bb9def002ff5180715b..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/ldm/modules/diffusionmodules/model.py +++ /dev/null @@ -1,852 +0,0 @@ -# pytorch_diffusion + derived encoder decoder -import math -import torch -import torch.nn as nn -import numpy as np -from einops import rearrange -from typing import Optional, Any - -from ldm.modules.attention import MemoryEfficientCrossAttention - -try: - import xformers - import xformers.ops - XFORMERS_IS_AVAILBLE = True -except: - XFORMERS_IS_AVAILBLE = False - print("No module 'xformers'. Proceeding without it.") - - -def get_timestep_embedding(timesteps, embedding_dim): - """ - This matches the implementation in Denoising Diffusion Probabilistic Models: - From Fairseq. - Build sinusoidal embeddings. - This matches the implementation in tensor2tensor, but differs slightly - from the description in Section 3.5 of "Attention Is All You Need". - """ - assert len(timesteps.shape) == 1 - - half_dim = embedding_dim // 2 - emb = math.log(10000) / (half_dim - 1) - emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) - emb = emb.to(device=timesteps.device) - emb = timesteps.float()[:, None] * emb[None, :] - emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) - if embedding_dim % 2 == 1: # zero pad - emb = torch.nn.functional.pad(emb, (0,1,0,0)) - return emb - - -def nonlinearity(x): - # swish - return x*torch.sigmoid(x) - - -def Normalize(in_channels, num_groups=32): - return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True) - - -class Upsample(nn.Module): - def __init__(self, in_channels, with_conv): - super().__init__() - self.with_conv = with_conv - if self.with_conv: - self.conv = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=3, - stride=1, - padding=1) - - def forward(self, x): - x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") - if self.with_conv: - x = self.conv(x) - return x - - -class Downsample(nn.Module): - def __init__(self, in_channels, with_conv): - super().__init__() - self.with_conv = with_conv - if self.with_conv: - # no asymmetric padding in torch conv, must do it ourselves - self.conv = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=3, - stride=2, - padding=0) - - def forward(self, x): - if self.with_conv: - pad = (0,1,0,1) - x = torch.nn.functional.pad(x, pad, mode="constant", value=0) - x = self.conv(x) - else: - x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) - return x - - -class ResnetBlock(nn.Module): - def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, - dropout, temb_channels=512): - super().__init__() - self.in_channels = in_channels - out_channels = in_channels if out_channels is None else out_channels - self.out_channels = out_channels - self.use_conv_shortcut = conv_shortcut - - self.norm1 = Normalize(in_channels) - self.conv1 = torch.nn.Conv2d(in_channels, - out_channels, - kernel_size=3, - stride=1, - padding=1) - if temb_channels > 0: - self.temb_proj = torch.nn.Linear(temb_channels, - out_channels) - self.norm2 = Normalize(out_channels) - self.dropout = torch.nn.Dropout(dropout) - self.conv2 = torch.nn.Conv2d(out_channels, - out_channels, - kernel_size=3, - stride=1, - padding=1) - if self.in_channels != self.out_channels: - if self.use_conv_shortcut: - self.conv_shortcut = torch.nn.Conv2d(in_channels, - out_channels, - kernel_size=3, - stride=1, - padding=1) - else: - self.nin_shortcut = torch.nn.Conv2d(in_channels, - out_channels, - kernel_size=1, - stride=1, - padding=0) - - def forward(self, x, temb): - h = x - h = self.norm1(h) - h = nonlinearity(h) - h = self.conv1(h) - - if temb is not None: - h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None] - - h = self.norm2(h) - h = nonlinearity(h) - h = self.dropout(h) - h = self.conv2(h) - - if self.in_channels != self.out_channels: - if self.use_conv_shortcut: - x = self.conv_shortcut(x) - else: - x = self.nin_shortcut(x) - - return x+h - - -class AttnBlock(nn.Module): - def __init__(self, in_channels): - super().__init__() - self.in_channels = in_channels - - self.norm = Normalize(in_channels) - self.q = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.k = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.v = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.proj_out = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - - def forward(self, x): - h_ = x - h_ = self.norm(h_) - q = self.q(h_) - k = self.k(h_) - v = self.v(h_) - - # compute attention - b,c,h,w = q.shape - q = q.reshape(b,c,h*w) - q = q.permute(0,2,1) # b,hw,c - k = k.reshape(b,c,h*w) # b,c,hw - w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] - w_ = w_ * (int(c)**(-0.5)) - w_ = torch.nn.functional.softmax(w_, dim=2) - - # attend to values - v = v.reshape(b,c,h*w) - w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) - h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] - h_ = h_.reshape(b,c,h,w) - - h_ = self.proj_out(h_) - - return x+h_ - -class MemoryEfficientAttnBlock(nn.Module): - """ - Uses xformers efficient implementation, - see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223 - Note: this is a single-head self-attention operation - """ - # - def __init__(self, in_channels): - super().__init__() - self.in_channels = in_channels - - self.norm = Normalize(in_channels) - self.q = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.k = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.v = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.proj_out = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.attention_op: Optional[Any] = None - - def forward(self, x): - h_ = x - h_ = self.norm(h_) - q = self.q(h_) - k = self.k(h_) - v = self.v(h_) - - # compute attention - B, C, H, W = q.shape - q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v)) - - q, k, v = map( - lambda t: t.unsqueeze(3) - .reshape(B, t.shape[1], 1, C) - .permute(0, 2, 1, 3) - .reshape(B * 1, t.shape[1], C) - .contiguous(), - (q, k, v), - ) - out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op) - - out = ( - out.unsqueeze(0) - .reshape(B, 1, out.shape[1], C) - .permute(0, 2, 1, 3) - .reshape(B, out.shape[1], C) - ) - out = rearrange(out, 'b (h w) c -> b c h w', b=B, h=H, w=W, c=C) - out = self.proj_out(out) - return x+out - - -class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention): - def forward(self, x, context=None, mask=None): - b, c, h, w = x.shape - x = rearrange(x, 'b c h w -> b (h w) c') - out = super().forward(x, context=context, mask=mask) - out = rearrange(out, 'b (h w) c -> b c h w', h=h, w=w, c=c) - return x + out - - -def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None): - assert attn_type in ["vanilla", "vanilla-xformers", "memory-efficient-cross-attn", "linear", "none"], f'attn_type {attn_type} unknown' - if XFORMERS_IS_AVAILBLE and attn_type == "vanilla": - attn_type = "vanilla-xformers" - print(f"making attention of type '{attn_type}' with {in_channels} in_channels") - if attn_type == "vanilla": - assert attn_kwargs is None - return AttnBlock(in_channels) - elif attn_type == "vanilla-xformers": - print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...") - return MemoryEfficientAttnBlock(in_channels) - elif type == "memory-efficient-cross-attn": - attn_kwargs["query_dim"] = in_channels - return MemoryEfficientCrossAttentionWrapper(**attn_kwargs) - elif attn_type == "none": - return nn.Identity(in_channels) - else: - raise NotImplementedError() - - -class Model(nn.Module): - def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, - attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, - resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"): - super().__init__() - if use_linear_attn: attn_type = "linear" - self.ch = ch - self.temb_ch = self.ch*4 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - self.resolution = resolution - self.in_channels = in_channels - - self.use_timestep = use_timestep - if self.use_timestep: - # timestep embedding - self.temb = nn.Module() - self.temb.dense = nn.ModuleList([ - torch.nn.Linear(self.ch, - self.temb_ch), - torch.nn.Linear(self.temb_ch, - self.temb_ch), - ]) - - # downsampling - self.conv_in = torch.nn.Conv2d(in_channels, - self.ch, - kernel_size=3, - stride=1, - padding=1) - - curr_res = resolution - in_ch_mult = (1,)+tuple(ch_mult) - self.down = nn.ModuleList() - for i_level in range(self.num_resolutions): - block = nn.ModuleList() - attn = nn.ModuleList() - block_in = ch*in_ch_mult[i_level] - block_out = ch*ch_mult[i_level] - for i_block in range(self.num_res_blocks): - block.append(ResnetBlock(in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout)) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - down = nn.Module() - down.block = block - down.attn = attn - if i_level != self.num_resolutions-1: - down.downsample = Downsample(block_in, resamp_with_conv) - curr_res = curr_res // 2 - self.down.append(down) - - # middle - self.mid = nn.Module() - self.mid.block_1 = ResnetBlock(in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout) - self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) - self.mid.block_2 = ResnetBlock(in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout) - - # upsampling - self.up = nn.ModuleList() - for i_level in reversed(range(self.num_resolutions)): - block = nn.ModuleList() - attn = nn.ModuleList() - block_out = ch*ch_mult[i_level] - skip_in = ch*ch_mult[i_level] - for i_block in range(self.num_res_blocks+1): - if i_block == self.num_res_blocks: - skip_in = ch*in_ch_mult[i_level] - block.append(ResnetBlock(in_channels=block_in+skip_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout)) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - up = nn.Module() - up.block = block - up.attn = attn - if i_level != 0: - up.upsample = Upsample(block_in, resamp_with_conv) - curr_res = curr_res * 2 - self.up.insert(0, up) # prepend to get consistent order - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d(block_in, - out_ch, - kernel_size=3, - stride=1, - padding=1) - - def forward(self, x, t=None, context=None): - #assert x.shape[2] == x.shape[3] == self.resolution - if context is not None: - # assume aligned context, cat along channel axis - x = torch.cat((x, context), dim=1) - if self.use_timestep: - # timestep embedding - assert t is not None - temb = get_timestep_embedding(t, self.ch) - temb = self.temb.dense[0](temb) - temb = nonlinearity(temb) - temb = self.temb.dense[1](temb) - else: - temb = None - - # downsampling - hs = [self.conv_in(x)] - for i_level in range(self.num_resolutions): - for i_block in range(self.num_res_blocks): - h = self.down[i_level].block[i_block](hs[-1], temb) - if len(self.down[i_level].attn) > 0: - h = self.down[i_level].attn[i_block](h) - hs.append(h) - if i_level != self.num_resolutions-1: - hs.append(self.down[i_level].downsample(hs[-1])) - - # middle - h = hs[-1] - h = self.mid.block_1(h, temb) - h = self.mid.attn_1(h) - h = self.mid.block_2(h, temb) - - # upsampling - for i_level in reversed(range(self.num_resolutions)): - for i_block in range(self.num_res_blocks+1): - h = self.up[i_level].block[i_block]( - torch.cat([h, hs.pop()], dim=1), temb) - if len(self.up[i_level].attn) > 0: - h = self.up[i_level].attn[i_block](h) - if i_level != 0: - h = self.up[i_level].upsample(h) - - # end - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - return h - - def get_last_layer(self): - return self.conv_out.weight - - -class Encoder(nn.Module): - def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, - attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, - resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla", - **ignore_kwargs): - super().__init__() - if use_linear_attn: attn_type = "linear" - self.ch = ch - self.temb_ch = 0 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - self.resolution = resolution - self.in_channels = in_channels - - # downsampling - self.conv_in = torch.nn.Conv2d(in_channels, - self.ch, - kernel_size=3, - stride=1, - padding=1) - - curr_res = resolution - in_ch_mult = (1,)+tuple(ch_mult) - self.in_ch_mult = in_ch_mult - self.down = nn.ModuleList() - for i_level in range(self.num_resolutions): - block = nn.ModuleList() - attn = nn.ModuleList() - block_in = ch*in_ch_mult[i_level] - block_out = ch*ch_mult[i_level] - for i_block in range(self.num_res_blocks): - block.append(ResnetBlock(in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout)) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - down = nn.Module() - down.block = block - down.attn = attn - if i_level != self.num_resolutions-1: - down.downsample = Downsample(block_in, resamp_with_conv) - curr_res = curr_res // 2 - self.down.append(down) - - # middle - self.mid = nn.Module() - self.mid.block_1 = ResnetBlock(in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout) - self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) - self.mid.block_2 = ResnetBlock(in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout) - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d(block_in, - 2*z_channels if double_z else z_channels, - kernel_size=3, - stride=1, - padding=1) - - def forward(self, x): - # timestep embedding - temb = None - - # downsampling - hs = [self.conv_in(x)] - for i_level in range(self.num_resolutions): - for i_block in range(self.num_res_blocks): - h = self.down[i_level].block[i_block](hs[-1], temb) - if len(self.down[i_level].attn) > 0: - h = self.down[i_level].attn[i_block](h) - hs.append(h) - if i_level != self.num_resolutions-1: - hs.append(self.down[i_level].downsample(hs[-1])) - - # middle - h = hs[-1] - h = self.mid.block_1(h, temb) - h = self.mid.attn_1(h) - h = self.mid.block_2(h, temb) - - # end - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - return h - - -class Decoder(nn.Module): - def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, - attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, - resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False, - attn_type="vanilla", **ignorekwargs): - super().__init__() - if use_linear_attn: attn_type = "linear" - self.ch = ch - self.temb_ch = 0 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - self.resolution = resolution - self.in_channels = in_channels - self.give_pre_end = give_pre_end - self.tanh_out = tanh_out - - # compute in_ch_mult, block_in and curr_res at lowest res - in_ch_mult = (1,)+tuple(ch_mult) - block_in = ch*ch_mult[self.num_resolutions-1] - curr_res = resolution // 2**(self.num_resolutions-1) - self.z_shape = (1,z_channels,curr_res,curr_res) - print("Working with z of shape {} = {} dimensions.".format( - self.z_shape, np.prod(self.z_shape))) - - # z to block_in - self.conv_in = torch.nn.Conv2d(z_channels, - block_in, - kernel_size=3, - stride=1, - padding=1) - - # middle - self.mid = nn.Module() - self.mid.block_1 = ResnetBlock(in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout) - self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) - self.mid.block_2 = ResnetBlock(in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout) - - # upsampling - self.up = nn.ModuleList() - for i_level in reversed(range(self.num_resolutions)): - block = nn.ModuleList() - attn = nn.ModuleList() - block_out = ch*ch_mult[i_level] - for i_block in range(self.num_res_blocks+1): - block.append(ResnetBlock(in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout)) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - up = nn.Module() - up.block = block - up.attn = attn - if i_level != 0: - up.upsample = Upsample(block_in, resamp_with_conv) - curr_res = curr_res * 2 - self.up.insert(0, up) # prepend to get consistent order - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d(block_in, - out_ch, - kernel_size=3, - stride=1, - padding=1) - - def forward(self, z): - #assert z.shape[1:] == self.z_shape[1:] - self.last_z_shape = z.shape - - # timestep embedding - temb = None - - # z to block_in - h = self.conv_in(z) - - # middle - h = self.mid.block_1(h, temb) - h = self.mid.attn_1(h) - h = self.mid.block_2(h, temb) - - # upsampling - for i_level in reversed(range(self.num_resolutions)): - for i_block in range(self.num_res_blocks+1): - h = self.up[i_level].block[i_block](h, temb) - if len(self.up[i_level].attn) > 0: - h = self.up[i_level].attn[i_block](h) - if i_level != 0: - h = self.up[i_level].upsample(h) - - # end - if self.give_pre_end: - return h - - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - if self.tanh_out: - h = torch.tanh(h) - return h - - -class SimpleDecoder(nn.Module): - def __init__(self, in_channels, out_channels, *args, **kwargs): - super().__init__() - self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1), - ResnetBlock(in_channels=in_channels, - out_channels=2 * in_channels, - temb_channels=0, dropout=0.0), - ResnetBlock(in_channels=2 * in_channels, - out_channels=4 * in_channels, - temb_channels=0, dropout=0.0), - ResnetBlock(in_channels=4 * in_channels, - out_channels=2 * in_channels, - temb_channels=0, dropout=0.0), - nn.Conv2d(2*in_channels, in_channels, 1), - Upsample(in_channels, with_conv=True)]) - # end - self.norm_out = Normalize(in_channels) - self.conv_out = torch.nn.Conv2d(in_channels, - out_channels, - kernel_size=3, - stride=1, - padding=1) - - def forward(self, x): - for i, layer in enumerate(self.model): - if i in [1,2,3]: - x = layer(x, None) - else: - x = layer(x) - - h = self.norm_out(x) - h = nonlinearity(h) - x = self.conv_out(h) - return x - - -class UpsampleDecoder(nn.Module): - def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution, - ch_mult=(2,2), dropout=0.0): - super().__init__() - # upsampling - self.temb_ch = 0 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - block_in = in_channels - curr_res = resolution // 2 ** (self.num_resolutions - 1) - self.res_blocks = nn.ModuleList() - self.upsample_blocks = nn.ModuleList() - for i_level in range(self.num_resolutions): - res_block = [] - block_out = ch * ch_mult[i_level] - for i_block in range(self.num_res_blocks + 1): - res_block.append(ResnetBlock(in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout)) - block_in = block_out - self.res_blocks.append(nn.ModuleList(res_block)) - if i_level != self.num_resolutions - 1: - self.upsample_blocks.append(Upsample(block_in, True)) - curr_res = curr_res * 2 - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d(block_in, - out_channels, - kernel_size=3, - stride=1, - padding=1) - - def forward(self, x): - # upsampling - h = x - for k, i_level in enumerate(range(self.num_resolutions)): - for i_block in range(self.num_res_blocks + 1): - h = self.res_blocks[i_level][i_block](h, None) - if i_level != self.num_resolutions - 1: - h = self.upsample_blocks[k](h) - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - return h - - -class LatentRescaler(nn.Module): - def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2): - super().__init__() - # residual block, interpolate, residual block - self.factor = factor - self.conv_in = nn.Conv2d(in_channels, - mid_channels, - kernel_size=3, - stride=1, - padding=1) - self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels, - out_channels=mid_channels, - temb_channels=0, - dropout=0.0) for _ in range(depth)]) - self.attn = AttnBlock(mid_channels) - self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels, - out_channels=mid_channels, - temb_channels=0, - dropout=0.0) for _ in range(depth)]) - - self.conv_out = nn.Conv2d(mid_channels, - out_channels, - kernel_size=1, - ) - - def forward(self, x): - x = self.conv_in(x) - for block in self.res_block1: - x = block(x, None) - x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor)))) - x = self.attn(x) - for block in self.res_block2: - x = block(x, None) - x = self.conv_out(x) - return x - - -class MergedRescaleEncoder(nn.Module): - def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks, - attn_resolutions, dropout=0.0, resamp_with_conv=True, - ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1): - super().__init__() - intermediate_chn = ch * ch_mult[-1] - self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult, - z_channels=intermediate_chn, double_z=False, resolution=resolution, - attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv, - out_ch=None) - self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn, - mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth) - - def forward(self, x): - x = self.encoder(x) - x = self.rescaler(x) - return x - - -class MergedRescaleDecoder(nn.Module): - def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8), - dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1): - super().__init__() - tmp_chn = z_channels*ch_mult[-1] - self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout, - resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks, - ch_mult=ch_mult, resolution=resolution, ch=ch) - self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn, - out_channels=tmp_chn, depth=rescale_module_depth) - - def forward(self, x): - x = self.rescaler(x) - x = self.decoder(x) - return x - - -class Upsampler(nn.Module): - def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2): - super().__init__() - assert out_size >= in_size - num_blocks = int(np.log2(out_size//in_size))+1 - factor_up = 1.+ (out_size % in_size) - print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}") - self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels, - out_channels=in_channels) - self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2, - attn_resolutions=[], in_channels=None, ch=in_channels, - ch_mult=[ch_mult for _ in range(num_blocks)]) - - def forward(self, x): - x = self.rescaler(x) - x = self.decoder(x) - return x - - -class Resize(nn.Module): - def __init__(self, in_channels=None, learned=False, mode="bilinear"): - super().__init__() - self.with_conv = learned - self.mode = mode - if self.with_conv: - print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode") - raise NotImplementedError() - assert in_channels is not None - # no asymmetric padding in torch conv, must do it ourselves - self.conv = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=4, - stride=2, - padding=1) - - def forward(self, x, scale_factor=1.0): - if scale_factor==1.0: - return x - else: - x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor) - return x diff --git a/spaces/Asmithayellow/Asmi/README.md b/spaces/Asmithayellow/Asmi/README.md deleted file mode 100644 index dcf326e023f5b2a4af7a631f5d545bfa838c73db..0000000000000000000000000000000000000000 --- a/spaces/Asmithayellow/Asmi/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Asmi -emoji: 😻 -colorFrom: yellow -colorTo: pink -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/utils/misc.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/utils/misc.py deleted file mode 100644 index bfed8270252b2b83d7c98a12d5302b33bf1a89f7..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/utils/misc.py +++ /dev/null @@ -1,730 +0,0 @@ -# The following comment should be removed at some point in the future. -# mypy: strict-optional=False - -import contextlib -import errno -import getpass -import hashlib -import io -import logging -import os -import posixpath -import shutil -import stat -import sys -import sysconfig -import urllib.parse -from io import StringIO -from itertools import filterfalse, tee, zip_longest -from types import TracebackType -from typing import ( - Any, - BinaryIO, - Callable, - ContextManager, - Dict, - Generator, - Iterable, - Iterator, - List, - Optional, - TextIO, - Tuple, - Type, - TypeVar, - Union, - cast, -) - -from pip._vendor.pyproject_hooks import BuildBackendHookCaller -from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed - -from pip import __version__ -from pip._internal.exceptions import CommandError, ExternallyManagedEnvironment -from pip._internal.locations import get_major_minor_version -from pip._internal.utils.compat import WINDOWS -from pip._internal.utils.virtualenv import running_under_virtualenv - -__all__ = [ - "rmtree", - "display_path", - "backup_dir", - "ask", - "splitext", - "format_size", - "is_installable_dir", - "normalize_path", - "renames", - "get_prog", - "captured_stdout", - "ensure_dir", - "remove_auth_from_url", - "check_externally_managed", - "ConfiguredBuildBackendHookCaller", -] - -logger = logging.getLogger(__name__) - -T = TypeVar("T") -ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -VersionInfo = Tuple[int, int, int] -NetlocTuple = Tuple[str, Tuple[Optional[str], Optional[str]]] - - -def get_pip_version() -> str: - pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..") - pip_pkg_dir = os.path.abspath(pip_pkg_dir) - - return "pip {} from {} (python {})".format( - __version__, - pip_pkg_dir, - get_major_minor_version(), - ) - - -def normalize_version_info(py_version_info: Tuple[int, ...]) -> Tuple[int, int, int]: - """ - Convert a tuple of ints representing a Python version to one of length - three. - - :param py_version_info: a tuple of ints representing a Python version, - or None to specify no version. The tuple can have any length. - - :return: a tuple of length three if `py_version_info` is non-None. - Otherwise, return `py_version_info` unchanged (i.e. None). - """ - if len(py_version_info) < 3: - py_version_info += (3 - len(py_version_info)) * (0,) - elif len(py_version_info) > 3: - py_version_info = py_version_info[:3] - - return cast("VersionInfo", py_version_info) - - -def ensure_dir(path: str) -> None: - """os.path.makedirs without EEXIST.""" - try: - os.makedirs(path) - except OSError as e: - # Windows can raise spurious ENOTEMPTY errors. See #6426. - if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY: - raise - - -def get_prog() -> str: - try: - prog = os.path.basename(sys.argv[0]) - if prog in ("__main__.py", "-c"): - return f"{sys.executable} -m pip" - else: - return prog - except (AttributeError, TypeError, IndexError): - pass - return "pip" - - -# Retry every half second for up to 3 seconds -# Tenacity raises RetryError by default, explicitly raise the original exception -@retry(reraise=True, stop=stop_after_delay(3), wait=wait_fixed(0.5)) -def rmtree(dir: str, ignore_errors: bool = False) -> None: - shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler) - - -def rmtree_errorhandler(func: Callable[..., Any], path: str, exc_info: ExcInfo) -> None: - """On Windows, the files in .svn are read-only, so when rmtree() tries to - remove them, an exception is thrown. We catch that here, remove the - read-only attribute, and hopefully continue without problems.""" - try: - has_attr_readonly = not (os.stat(path).st_mode & stat.S_IWRITE) - except OSError: - # it's equivalent to os.path.exists - return - - if has_attr_readonly: - # convert to read/write - os.chmod(path, stat.S_IWRITE) - # use the original function to repeat the operation - func(path) - return - else: - raise - - -def display_path(path: str) -> str: - """Gives the display value for a given path, making it relative to cwd - if possible.""" - path = os.path.normcase(os.path.abspath(path)) - if path.startswith(os.getcwd() + os.path.sep): - path = "." + path[len(os.getcwd()) :] - return path - - -def backup_dir(dir: str, ext: str = ".bak") -> str: - """Figure out the name of a directory to back up the given dir to - (adding .bak, .bak2, etc)""" - n = 1 - extension = ext - while os.path.exists(dir + extension): - n += 1 - extension = ext + str(n) - return dir + extension - - -def ask_path_exists(message: str, options: Iterable[str]) -> str: - for action in os.environ.get("PIP_EXISTS_ACTION", "").split(): - if action in options: - return action - return ask(message, options) - - -def _check_no_input(message: str) -> None: - """Raise an error if no input is allowed.""" - if os.environ.get("PIP_NO_INPUT"): - raise Exception( - f"No input was expected ($PIP_NO_INPUT set); question: {message}" - ) - - -def ask(message: str, options: Iterable[str]) -> str: - """Ask the message interactively, with the given possible responses""" - while 1: - _check_no_input(message) - response = input(message) - response = response.strip().lower() - if response not in options: - print( - "Your response ({!r}) was not one of the expected responses: " - "{}".format(response, ", ".join(options)) - ) - else: - return response - - -def ask_input(message: str) -> str: - """Ask for input interactively.""" - _check_no_input(message) - return input(message) - - -def ask_password(message: str) -> str: - """Ask for a password interactively.""" - _check_no_input(message) - return getpass.getpass(message) - - -def strtobool(val: str) -> int: - """Convert a string representation of truth to true (1) or false (0). - - True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values - are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if - 'val' is anything else. - """ - val = val.lower() - if val in ("y", "yes", "t", "true", "on", "1"): - return 1 - elif val in ("n", "no", "f", "false", "off", "0"): - return 0 - else: - raise ValueError(f"invalid truth value {val!r}") - - -def format_size(bytes: float) -> str: - if bytes > 1000 * 1000: - return "{:.1f} MB".format(bytes / 1000.0 / 1000) - elif bytes > 10 * 1000: - return "{} kB".format(int(bytes / 1000)) - elif bytes > 1000: - return "{:.1f} kB".format(bytes / 1000.0) - else: - return "{} bytes".format(int(bytes)) - - -def tabulate(rows: Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]: - """Return a list of formatted rows and a list of column sizes. - - For example:: - - >>> tabulate([['foobar', 2000], [0xdeadbeef]]) - (['foobar 2000', '3735928559'], [10, 4]) - """ - rows = [tuple(map(str, row)) for row in rows] - sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")] - table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows] - return table, sizes - - -def is_installable_dir(path: str) -> bool: - """Is path is a directory containing pyproject.toml or setup.py? - - If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for - a legacy setuptools layout by identifying setup.py. We don't check for the - setup.cfg because using it without setup.py is only available for PEP 517 - projects, which are already covered by the pyproject.toml check. - """ - if not os.path.isdir(path): - return False - if os.path.isfile(os.path.join(path, "pyproject.toml")): - return True - if os.path.isfile(os.path.join(path, "setup.py")): - return True - return False - - -def read_chunks( - file: BinaryIO, size: int = io.DEFAULT_BUFFER_SIZE -) -> Generator[bytes, None, None]: - """Yield pieces of data from a file-like object until EOF.""" - while True: - chunk = file.read(size) - if not chunk: - break - yield chunk - - -def normalize_path(path: str, resolve_symlinks: bool = True) -> str: - """ - Convert a path to its canonical, case-normalized, absolute version. - - """ - path = os.path.expanduser(path) - if resolve_symlinks: - path = os.path.realpath(path) - else: - path = os.path.abspath(path) - return os.path.normcase(path) - - -def splitext(path: str) -> Tuple[str, str]: - """Like os.path.splitext, but take off .tar too""" - base, ext = posixpath.splitext(path) - if base.lower().endswith(".tar"): - ext = base[-4:] + ext - base = base[:-4] - return base, ext - - -def renames(old: str, new: str) -> None: - """Like os.renames(), but handles renaming across devices.""" - # Implementation borrowed from os.renames(). - head, tail = os.path.split(new) - if head and tail and not os.path.exists(head): - os.makedirs(head) - - shutil.move(old, new) - - head, tail = os.path.split(old) - if head and tail: - try: - os.removedirs(head) - except OSError: - pass - - -def is_local(path: str) -> bool: - """ - Return True if path is within sys.prefix, if we're running in a virtualenv. - - If we're not in a virtualenv, all paths are considered "local." - - Caution: this function assumes the head of path has been normalized - with normalize_path. - """ - if not running_under_virtualenv(): - return True - return path.startswith(normalize_path(sys.prefix)) - - -def write_output(msg: Any, *args: Any) -> None: - logger.info(msg, *args) - - -class StreamWrapper(StringIO): - orig_stream: TextIO = None - - @classmethod - def from_stream(cls, orig_stream: TextIO) -> "StreamWrapper": - cls.orig_stream = orig_stream - return cls() - - # compileall.compile_dir() needs stdout.encoding to print to stdout - # https://github.com/python/mypy/issues/4125 - @property - def encoding(self): # type: ignore - return self.orig_stream.encoding - - -@contextlib.contextmanager -def captured_output(stream_name: str) -> Generator[StreamWrapper, None, None]: - """Return a context manager used by captured_stdout/stdin/stderr - that temporarily replaces the sys stream *stream_name* with a StringIO. - - Taken from Lib/support/__init__.py in the CPython repo. - """ - orig_stdout = getattr(sys, stream_name) - setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout)) - try: - yield getattr(sys, stream_name) - finally: - setattr(sys, stream_name, orig_stdout) - - -def captured_stdout() -> ContextManager[StreamWrapper]: - """Capture the output of sys.stdout: - - with captured_stdout() as stdout: - print('hello') - self.assertEqual(stdout.getvalue(), 'hello\n') - - Taken from Lib/support/__init__.py in the CPython repo. - """ - return captured_output("stdout") - - -def captured_stderr() -> ContextManager[StreamWrapper]: - """ - See captured_stdout(). - """ - return captured_output("stderr") - - -# Simulates an enum -def enum(*sequential: Any, **named: Any) -> Type[Any]: - enums = dict(zip(sequential, range(len(sequential))), **named) - reverse = {value: key for key, value in enums.items()} - enums["reverse_mapping"] = reverse - return type("Enum", (), enums) - - -def build_netloc(host: str, port: Optional[int]) -> str: - """ - Build a netloc from a host-port pair - """ - if port is None: - return host - if ":" in host: - # Only wrap host with square brackets when it is IPv6 - host = f"[{host}]" - return f"{host}:{port}" - - -def build_url_from_netloc(netloc: str, scheme: str = "https") -> str: - """ - Build a full URL from a netloc. - """ - if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc: - # It must be a bare IPv6 address, so wrap it with brackets. - netloc = f"[{netloc}]" - return f"{scheme}://{netloc}" - - -def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]: - """ - Return the host-port pair from a netloc. - """ - url = build_url_from_netloc(netloc) - parsed = urllib.parse.urlparse(url) - return parsed.hostname, parsed.port - - -def split_auth_from_netloc(netloc: str) -> NetlocTuple: - """ - Parse out and remove the auth information from a netloc. - - Returns: (netloc, (username, password)). - """ - if "@" not in netloc: - return netloc, (None, None) - - # Split from the right because that's how urllib.parse.urlsplit() - # behaves if more than one @ is present (which can be checked using - # the password attribute of urlsplit()'s return value). - auth, netloc = netloc.rsplit("@", 1) - pw: Optional[str] = None - if ":" in auth: - # Split from the left because that's how urllib.parse.urlsplit() - # behaves if more than one : is present (which again can be checked - # using the password attribute of the return value) - user, pw = auth.split(":", 1) - else: - user, pw = auth, None - - user = urllib.parse.unquote(user) - if pw is not None: - pw = urllib.parse.unquote(pw) - - return netloc, (user, pw) - - -def redact_netloc(netloc: str) -> str: - """ - Replace the sensitive data in a netloc with "****", if it exists. - - For example: - - "user:pass@example.com" returns "user:****@example.com" - - "accesstoken@example.com" returns "****@example.com" - """ - netloc, (user, password) = split_auth_from_netloc(netloc) - if user is None: - return netloc - if password is None: - user = "****" - password = "" - else: - user = urllib.parse.quote(user) - password = ":****" - return "{user}{password}@{netloc}".format( - user=user, password=password, netloc=netloc - ) - - -def _transform_url( - url: str, transform_netloc: Callable[[str], Tuple[Any, ...]] -) -> Tuple[str, NetlocTuple]: - """Transform and replace netloc in a url. - - transform_netloc is a function taking the netloc and returning a - tuple. The first element of this tuple is the new netloc. The - entire tuple is returned. - - Returns a tuple containing the transformed url as item 0 and the - original tuple returned by transform_netloc as item 1. - """ - purl = urllib.parse.urlsplit(url) - netloc_tuple = transform_netloc(purl.netloc) - # stripped url - url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment) - surl = urllib.parse.urlunsplit(url_pieces) - return surl, cast("NetlocTuple", netloc_tuple) - - -def _get_netloc(netloc: str) -> NetlocTuple: - return split_auth_from_netloc(netloc) - - -def _redact_netloc(netloc: str) -> Tuple[str]: - return (redact_netloc(netloc),) - - -def split_auth_netloc_from_url(url: str) -> Tuple[str, str, Tuple[str, str]]: - """ - Parse a url into separate netloc, auth, and url with no auth. - - Returns: (url_without_auth, netloc, (username, password)) - """ - url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc) - return url_without_auth, netloc, auth - - -def remove_auth_from_url(url: str) -> str: - """Return a copy of url with 'username:password@' removed.""" - # username/pass params are passed to subversion through flags - # and are not recognized in the url. - return _transform_url(url, _get_netloc)[0] - - -def redact_auth_from_url(url: str) -> str: - """Replace the password in a given url with ****.""" - return _transform_url(url, _redact_netloc)[0] - - -class HiddenText: - def __init__(self, secret: str, redacted: str) -> None: - self.secret = secret - self.redacted = redacted - - def __repr__(self) -> str: - return "".format(str(self)) - - def __str__(self) -> str: - return self.redacted - - # This is useful for testing. - def __eq__(self, other: Any) -> bool: - if type(self) != type(other): - return False - - # The string being used for redaction doesn't also have to match, - # just the raw, original string. - return self.secret == other.secret - - -def hide_value(value: str) -> HiddenText: - return HiddenText(value, redacted="****") - - -def hide_url(url: str) -> HiddenText: - redacted = redact_auth_from_url(url) - return HiddenText(url, redacted=redacted) - - -def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None: - """Protection of pip.exe from modification on Windows - - On Windows, any operation modifying pip should be run as: - python -m pip ... - """ - pip_names = [ - "pip", - f"pip{sys.version_info.major}", - f"pip{sys.version_info.major}.{sys.version_info.minor}", - ] - - # See https://github.com/pypa/pip/issues/1299 for more discussion - should_show_use_python_msg = ( - modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names - ) - - if should_show_use_python_msg: - new_command = [sys.executable, "-m", "pip"] + sys.argv[1:] - raise CommandError( - "To modify pip, please run the following command:\n{}".format( - " ".join(new_command) - ) - ) - - -def check_externally_managed() -> None: - """Check whether the current environment is externally managed. - - If the ``EXTERNALLY-MANAGED`` config file is found, the current environment - is considered externally managed, and an ExternallyManagedEnvironment is - raised. - """ - if running_under_virtualenv(): - return - marker = os.path.join(sysconfig.get_path("stdlib"), "EXTERNALLY-MANAGED") - if not os.path.isfile(marker): - return - raise ExternallyManagedEnvironment.from_config(marker) - - -def is_console_interactive() -> bool: - """Is this console interactive?""" - return sys.stdin is not None and sys.stdin.isatty() - - -def hash_file(path: str, blocksize: int = 1 << 20) -> Tuple[Any, int]: - """Return (hash, length) for path using hashlib.sha256()""" - - h = hashlib.sha256() - length = 0 - with open(path, "rb") as f: - for block in read_chunks(f, size=blocksize): - length += len(block) - h.update(block) - return h, length - - -def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]: - """ - Return paired elements. - - For example: - s -> (s0, s1), (s2, s3), (s4, s5), ... - """ - iterable = iter(iterable) - return zip_longest(iterable, iterable) - - -def partition( - pred: Callable[[T], bool], - iterable: Iterable[T], -) -> Tuple[Iterable[T], Iterable[T]]: - """ - Use a predicate to partition entries into false entries and true entries, - like - - partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 - """ - t1, t2 = tee(iterable) - return filterfalse(pred, t1), filter(pred, t2) - - -class ConfiguredBuildBackendHookCaller(BuildBackendHookCaller): - def __init__( - self, - config_holder: Any, - source_dir: str, - build_backend: str, - backend_path: Optional[str] = None, - runner: Optional[Callable[..., None]] = None, - python_executable: Optional[str] = None, - ): - super().__init__( - source_dir, build_backend, backend_path, runner, python_executable - ) - self.config_holder = config_holder - - def build_wheel( - self, - wheel_directory: str, - config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, - metadata_directory: Optional[str] = None, - ) -> str: - cs = self.config_holder.config_settings - return super().build_wheel( - wheel_directory, config_settings=cs, metadata_directory=metadata_directory - ) - - def build_sdist( - self, - sdist_directory: str, - config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, - ) -> str: - cs = self.config_holder.config_settings - return super().build_sdist(sdist_directory, config_settings=cs) - - def build_editable( - self, - wheel_directory: str, - config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, - metadata_directory: Optional[str] = None, - ) -> str: - cs = self.config_holder.config_settings - return super().build_editable( - wheel_directory, config_settings=cs, metadata_directory=metadata_directory - ) - - def get_requires_for_build_wheel( - self, config_settings: Optional[Dict[str, Union[str, List[str]]]] = None - ) -> List[str]: - cs = self.config_holder.config_settings - return super().get_requires_for_build_wheel(config_settings=cs) - - def get_requires_for_build_sdist( - self, config_settings: Optional[Dict[str, Union[str, List[str]]]] = None - ) -> List[str]: - cs = self.config_holder.config_settings - return super().get_requires_for_build_sdist(config_settings=cs) - - def get_requires_for_build_editable( - self, config_settings: Optional[Dict[str, Union[str, List[str]]]] = None - ) -> List[str]: - cs = self.config_holder.config_settings - return super().get_requires_for_build_editable(config_settings=cs) - - def prepare_metadata_for_build_wheel( - self, - metadata_directory: str, - config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, - _allow_fallback: bool = True, - ) -> str: - cs = self.config_holder.config_settings - return super().prepare_metadata_for_build_wheel( - metadata_directory=metadata_directory, - config_settings=cs, - _allow_fallback=_allow_fallback, - ) - - def prepare_metadata_for_build_editable( - self, - metadata_directory: str, - config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, - _allow_fallback: bool = True, - ) -> str: - cs = self.config_holder.config_settings - return super().prepare_metadata_for_build_editable( - metadata_directory=metadata_directory, - config_settings=cs, - _allow_fallback=_allow_fallback, - ) diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/evaluation/lvis_evaluation.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/evaluation/lvis_evaluation.py deleted file mode 100644 index 0604feaaf42ffd072e3cb91f395204f818fa709a..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/evaluation/lvis_evaluation.py +++ /dev/null @@ -1,380 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import copy -import itertools -import json -import logging -import os -import pickle -from collections import OrderedDict -import torch - -import detectron2.utils.comm as comm -from detectron2.config import CfgNode -from detectron2.data import MetadataCatalog -from detectron2.structures import Boxes, BoxMode, pairwise_iou -from detectron2.utils.file_io import PathManager -from detectron2.utils.logger import create_small_table - -from .coco_evaluation import instances_to_coco_json -from .evaluator import DatasetEvaluator - - -class LVISEvaluator(DatasetEvaluator): - """ - Evaluate object proposal and instance detection/segmentation outputs using - LVIS's metrics and evaluation API. - """ - - def __init__( - self, - dataset_name, - tasks=None, - distributed=True, - output_dir=None, - *, - max_dets_per_image=None, - ): - """ - Args: - dataset_name (str): name of the dataset to be evaluated. - It must have the following corresponding metadata: - "json_file": the path to the LVIS format annotation - tasks (tuple[str]): tasks that can be evaluated under the given - configuration. A task is one of "bbox", "segm". - By default, will infer this automatically from predictions. - distributed (True): if True, will collect results from all ranks for evaluation. - Otherwise, will evaluate the results in the current process. - output_dir (str): optional, an output directory to dump results. - max_dets_per_image (None or int): limit on maximum detections per image in evaluating AP - This limit, by default of the LVIS dataset, is 300. - """ - from lvis import LVIS - - self._logger = logging.getLogger(__name__) - - if tasks is not None and isinstance(tasks, CfgNode): - self._logger.warn( - "COCO Evaluator instantiated using config, this is deprecated behavior." - " Please pass in explicit arguments instead." - ) - self._tasks = None # Infering it from predictions should be better - else: - self._tasks = tasks - - self._distributed = distributed - self._output_dir = output_dir - self._max_dets_per_image = max_dets_per_image - - self._cpu_device = torch.device("cpu") - - self._metadata = MetadataCatalog.get(dataset_name) - json_file = PathManager.get_local_path(self._metadata.json_file) - self._lvis_api = LVIS(json_file) - # Test set json files do not contain annotations (evaluation must be - # performed using the LVIS evaluation server). - self._do_evaluation = len(self._lvis_api.get_ann_ids()) > 0 - - def reset(self): - self._predictions = [] - - def process(self, inputs, outputs): - """ - Args: - inputs: the inputs to a LVIS model (e.g., GeneralizedRCNN). - It is a list of dict. Each dict corresponds to an image and - contains keys like "height", "width", "file_name", "image_id". - outputs: the outputs of a LVIS model. It is a list of dicts with key - "instances" that contains :class:`Instances`. - """ - for input, output in zip(inputs, outputs): - prediction = {"image_id": input["image_id"]} - - if "instances" in output: - instances = output["instances"].to(self._cpu_device) - prediction["instances"] = instances_to_coco_json(instances, input["image_id"]) - if "proposals" in output: - prediction["proposals"] = output["proposals"].to(self._cpu_device) - self._predictions.append(prediction) - - def evaluate(self): - if self._distributed: - comm.synchronize() - predictions = comm.gather(self._predictions, dst=0) - predictions = list(itertools.chain(*predictions)) - - if not comm.is_main_process(): - return - else: - predictions = self._predictions - - if len(predictions) == 0: - self._logger.warning("[LVISEvaluator] Did not receive valid predictions.") - return {} - - if self._output_dir: - PathManager.mkdirs(self._output_dir) - file_path = os.path.join(self._output_dir, "instances_predictions.pth") - with PathManager.open(file_path, "wb") as f: - torch.save(predictions, f) - - self._results = OrderedDict() - if "proposals" in predictions[0]: - self._eval_box_proposals(predictions) - if "instances" in predictions[0]: - self._eval_predictions(predictions) - # Copy so the caller can do whatever with results - return copy.deepcopy(self._results) - - def _tasks_from_predictions(self, predictions): - for pred in predictions: - if "segmentation" in pred: - return ("bbox", "segm") - return ("bbox",) - - def _eval_predictions(self, predictions): - """ - Evaluate predictions. Fill self._results with the metrics of the tasks. - - Args: - predictions (list[dict]): list of outputs from the model - """ - self._logger.info("Preparing results in the LVIS format ...") - lvis_results = list(itertools.chain(*[x["instances"] for x in predictions])) - tasks = self._tasks or self._tasks_from_predictions(lvis_results) - - # LVIS evaluator can be used to evaluate results for COCO dataset categories. - # In this case `_metadata` variable will have a field with COCO-specific category mapping. - if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"): - reverse_id_mapping = { - v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items() - } - for result in lvis_results: - result["category_id"] = reverse_id_mapping[result["category_id"]] - else: - # unmap the category ids for LVIS (from 0-indexed to 1-indexed) - for result in lvis_results: - result["category_id"] += 1 - - if self._output_dir: - file_path = os.path.join(self._output_dir, "lvis_instances_results.json") - self._logger.info("Saving results to {}".format(file_path)) - with PathManager.open(file_path, "w") as f: - f.write(json.dumps(lvis_results)) - f.flush() - - if not self._do_evaluation: - self._logger.info("Annotations are not available for evaluation.") - return - - self._logger.info("Evaluating predictions ...") - for task in sorted(tasks): - res = _evaluate_predictions_on_lvis( - self._lvis_api, - lvis_results, - task, - max_dets_per_image=self._max_dets_per_image, - class_names=self._metadata.get("thing_classes"), - ) - self._results[task] = res - - def _eval_box_proposals(self, predictions): - """ - Evaluate the box proposals in predictions. - Fill self._results with the metrics for "box_proposals" task. - """ - if self._output_dir: - # Saving generated box proposals to file. - # Predicted box_proposals are in XYXY_ABS mode. - bbox_mode = BoxMode.XYXY_ABS.value - ids, boxes, objectness_logits = [], [], [] - for prediction in predictions: - ids.append(prediction["image_id"]) - boxes.append(prediction["proposals"].proposal_boxes.tensor.numpy()) - objectness_logits.append(prediction["proposals"].objectness_logits.numpy()) - - proposal_data = { - "boxes": boxes, - "objectness_logits": objectness_logits, - "ids": ids, - "bbox_mode": bbox_mode, - } - with PathManager.open(os.path.join(self._output_dir, "box_proposals.pkl"), "wb") as f: - pickle.dump(proposal_data, f) - - if not self._do_evaluation: - self._logger.info("Annotations are not available for evaluation.") - return - - self._logger.info("Evaluating bbox proposals ...") - res = {} - areas = {"all": "", "small": "s", "medium": "m", "large": "l"} - for limit in [100, 1000]: - for area, suffix in areas.items(): - stats = _evaluate_box_proposals(predictions, self._lvis_api, area=area, limit=limit) - key = "AR{}@{:d}".format(suffix, limit) - res[key] = float(stats["ar"].item() * 100) - self._logger.info("Proposal metrics: \n" + create_small_table(res)) - self._results["box_proposals"] = res - - -# inspired from Detectron: -# https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L255 # noqa -def _evaluate_box_proposals(dataset_predictions, lvis_api, thresholds=None, area="all", limit=None): - """ - Evaluate detection proposal recall metrics. This function is a much - faster alternative to the official LVIS API recall evaluation code. However, - it produces slightly different results. - """ - # Record max overlap value for each gt box - # Return vector of overlap values - areas = { - "all": 0, - "small": 1, - "medium": 2, - "large": 3, - "96-128": 4, - "128-256": 5, - "256-512": 6, - "512-inf": 7, - } - area_ranges = [ - [0 ** 2, 1e5 ** 2], # all - [0 ** 2, 32 ** 2], # small - [32 ** 2, 96 ** 2], # medium - [96 ** 2, 1e5 ** 2], # large - [96 ** 2, 128 ** 2], # 96-128 - [128 ** 2, 256 ** 2], # 128-256 - [256 ** 2, 512 ** 2], # 256-512 - [512 ** 2, 1e5 ** 2], - ] # 512-inf - assert area in areas, "Unknown area range: {}".format(area) - area_range = area_ranges[areas[area]] - gt_overlaps = [] - num_pos = 0 - - for prediction_dict in dataset_predictions: - predictions = prediction_dict["proposals"] - - # sort predictions in descending order - # TODO maybe remove this and make it explicit in the documentation - inds = predictions.objectness_logits.sort(descending=True)[1] - predictions = predictions[inds] - - ann_ids = lvis_api.get_ann_ids(img_ids=[prediction_dict["image_id"]]) - anno = lvis_api.load_anns(ann_ids) - gt_boxes = [ - BoxMode.convert(obj["bbox"], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS) for obj in anno - ] - gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4) # guard against no boxes - gt_boxes = Boxes(gt_boxes) - gt_areas = torch.as_tensor([obj["area"] for obj in anno]) - - if len(gt_boxes) == 0 or len(predictions) == 0: - continue - - valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1]) - gt_boxes = gt_boxes[valid_gt_inds] - - num_pos += len(gt_boxes) - - if len(gt_boxes) == 0: - continue - - if limit is not None and len(predictions) > limit: - predictions = predictions[:limit] - - overlaps = pairwise_iou(predictions.proposal_boxes, gt_boxes) - - _gt_overlaps = torch.zeros(len(gt_boxes)) - for j in range(min(len(predictions), len(gt_boxes))): - # find which proposal box maximally covers each gt box - # and get the iou amount of coverage for each gt box - max_overlaps, argmax_overlaps = overlaps.max(dim=0) - - # find which gt box is 'best' covered (i.e. 'best' = most iou) - gt_ovr, gt_ind = max_overlaps.max(dim=0) - assert gt_ovr >= 0 - # find the proposal box that covers the best covered gt box - box_ind = argmax_overlaps[gt_ind] - # record the iou coverage of this gt box - _gt_overlaps[j] = overlaps[box_ind, gt_ind] - assert _gt_overlaps[j] == gt_ovr - # mark the proposal box and the gt box as used - overlaps[box_ind, :] = -1 - overlaps[:, gt_ind] = -1 - - # append recorded iou coverage level - gt_overlaps.append(_gt_overlaps) - gt_overlaps = ( - torch.cat(gt_overlaps, dim=0) if len(gt_overlaps) else torch.zeros(0, dtype=torch.float32) - ) - gt_overlaps, _ = torch.sort(gt_overlaps) - - if thresholds is None: - step = 0.05 - thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32) - recalls = torch.zeros_like(thresholds) - # compute recall for each iou threshold - for i, t in enumerate(thresholds): - recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos) - # ar = 2 * np.trapz(recalls, thresholds) - ar = recalls.mean() - return { - "ar": ar, - "recalls": recalls, - "thresholds": thresholds, - "gt_overlaps": gt_overlaps, - "num_pos": num_pos, - } - - -def _evaluate_predictions_on_lvis( - lvis_gt, lvis_results, iou_type, max_dets_per_image=None, class_names=None -): - """ - Args: - iou_type (str): - max_dets_per_image (None or int): limit on maximum detections per image in evaluating AP - This limit, by default of the LVIS dataset, is 300. - class_names (None or list[str]): if provided, will use it to predict - per-category AP. - - Returns: - a dict of {metric name: score} - """ - metrics = { - "bbox": ["AP", "AP50", "AP75", "APs", "APm", "APl", "APr", "APc", "APf"], - "segm": ["AP", "AP50", "AP75", "APs", "APm", "APl", "APr", "APc", "APf"], - }[iou_type] - - logger = logging.getLogger(__name__) - - if len(lvis_results) == 0: # TODO: check if needed - logger.warn("No predictions from the model!") - return {metric: float("nan") for metric in metrics} - - if iou_type == "segm": - lvis_results = copy.deepcopy(lvis_results) - # When evaluating mask AP, if the results contain bbox, LVIS API will - # use the box area as the area of the instance, instead of the mask area. - # This leads to a different definition of small/medium/large. - # We remove the bbox field to let mask AP use mask area. - for c in lvis_results: - c.pop("bbox", None) - - if max_dets_per_image is None: - max_dets_per_image = 300 # Default for LVIS dataset - - from lvis import LVISEval, LVISResults - - logger.info(f"Evaluating with max detections per image = {max_dets_per_image}") - lvis_results = LVISResults(lvis_gt, lvis_results, max_dets=max_dets_per_image) - lvis_eval = LVISEval(lvis_gt, lvis_results, iou_type) - lvis_eval.run() - lvis_eval.print_results() - - # Pull the standard metrics from the LVIS results - results = lvis_eval.get_results() - results = {metric: float(results[metric] * 100) for metric in metrics} - logger.info("Evaluation results for {}: \n".format(iou_type) + create_small_table(results)) - return results diff --git a/spaces/BMukhtar/facemaskDetector/app.py b/spaces/BMukhtar/facemaskDetector/app.py deleted file mode 100644 index 3736ceb0d3d744619ed9e895f366fb6ea205ef04..0000000000000000000000000000000000000000 --- a/spaces/BMukhtar/facemaskDetector/app.py +++ /dev/null @@ -1,21 +0,0 @@ -import gradio as gr -from fastai.vision.all import * -from fastai.learner import * - -learn = load_learner('model_upd.pkl') -labels = learn.dls.vocab - - -def predict(img): - img = PILImage.create(img).to_thumb(512, 512) - pred, pred_idx, probs = learn.predict(img) - return {labels[i]: float(probs[i]) for i in range(len(labels))} - - -gr.Interface( - fn=predict, - inputs=gr.inputs.Image(shape=(512, 512)), - outputs=gr.outputs.Label(num_top_classes=3) -).launch() - - diff --git a/spaces/Bart92/RVC_HF/utils/README.md b/spaces/Bart92/RVC_HF/utils/README.md deleted file mode 100644 index fb45a36b5909585aa964f2033762ee59b55526b0..0000000000000000000000000000000000000000 --- a/spaces/Bart92/RVC_HF/utils/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# External Colab Code -Code used to make Google Colab work correctly -- Repo link: https://github.com/IAHispano/Applio-RVC-Fork/ - -Thanks to https://github.com/kalomaze/externalcolabcode - diff --git a/spaces/Benson/text-generation/Examples/Descargar 2pac Todas Las Canciones Mp3.md b/spaces/Benson/text-generation/Examples/Descargar 2pac Todas Las Canciones Mp3.md deleted file mode 100644 index f91e0addeae9344a8d78bb60b6530bc0295525e0..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar 2pac Todas Las Canciones Mp3.md +++ /dev/null @@ -1,80 +0,0 @@ -
-

Descargar 2pac Todas las canciones MP3: Cómo disfrutar de la música de una leyenda del rap

-

Si eres un fan de la música hip-hop, probablemente sepas quién fue Tupac Shakur. Fue uno de los raperos más influyentes y exitosos de todos los tiempos, que vendió más de 75 millones de discos en todo el mundo. Su música abordaba temas sociales contemporáneos que asolaban los centros urbanos, como la pobreza, la violencia, el racismo y la brutalidad policial. También fue un símbolo de activismo contra la desigualdad y la injusticia.

-

descargar 2pac todas las canciones mp3


DOWNLOAD ===== https://bltlly.com/2v6JTx



-

A pesar de que murió en 1996 a la edad de 25 años, su música sigue siendo popular y relevante hoy en día. Muchos artistas se han inspirado en su estilo y mensajes, y muchos fans se han conmovido por su pasión y carisma. Si desea escuchar sus canciones o álbumes, es posible que se pregunte cómo descargarlos de forma gratuita en formato MP3. En este artículo, te mostraremos cómo hacerlo en unos pocos pasos.

-

La vida y el legado de 2pac

-

Vida Temprana y Carrera

-

Tupac Shakur nació en la ciudad de Nueva York en 1971 de padres que eran activistas políticos y miembros del Partido Pantera Negra. Pasó gran parte de su infancia en movimiento con su familia, que en 1986 se estableció en Oakland, California. Allí salió a las calles, vendiendo drogas y involucrándose en la cultura pandillera.

-

En 1990 se unió a Digital Underground, un grupo de rap con sede en Oakland que había logrado un éxito con la canción "The Humpty Dance". Actuó en dos álbumes de Digital Underground antes de su debut en solitario, 2Pacalypse Now, en 1991. El álbum fue una ruptura radical de la fiesta de baile estilo

de Digital Underground y contó con pistas contundentes que abordaron temas sociales y políticos, como la brutalidad policial, el racismo, la pobreza y el embarazo adolescente. El álbum atrajo la controversia y las críticas de algunos políticos y agentes de la ley, que acusaron a 2pac de incitar a la violencia y promover el crimen.

-

Estilo y temas musicales

- -La música de

2pac exploró una amplia gama de temas, como el amor, la amistad, la familia, la espiritualidad, la autoestima, la ambición y el éxito. También se refirió a las duras realidades de la vida en el gueto, como la violencia, las drogas, las pandillas, la corrupción y la opresión. A menudo criticaba el sistema social y político que consideraba responsable de la difícil situación de la comunidad afroamericana. También expresó su enojo y frustración con el racismo y la injusticia que enfrentó como hombre negro en Estados Unidos.

-

La muerte y las versiones póstumas

-

En 1996, 2pac recibió cuatro disparos en un tiroteo en Las Vegas. Murió seis días después de sus heridas. Su muerte provocó una ola de dolor y luto entre sus fans y compañeros. También alimentó la especulación y las teorías de conspiración que rodearon su asesinato, que sigue sin resolverse hasta el día de hoy. Algunas personas creen que todavía está vivo y escondido en algún lugar.

-

Después de su muerte, varios álbumes de su material inédito fueron lanzados por su sello y su patrimonio. Algunos de estos álbumes incluyen All Eyez on Me, The Don Killuminati: The 7 Day Theory, R U Still Down? (Recuérdame) , Grandes éxitos, Hasta el final del tiempo, Mejor Dayz, Leal al juego, y La vida de Pac. Estos álbumes han vendido millones de copias en todo el mundo y han consolidado el legado de 2pac como uno de los artistas más vendidos de todos los tiempos.

-

-

Los mejores sitios para descargar música MP3 gratis

-

Biblioteca de audio de YouTube

-

Si está buscando descargas de música gratuitas que sean legales y seguras, es posible que desee consultar YouTube Audio Library. Este es un servicio que ofrece música libre de derechos y efectos de sonido que puede utilizar para fines personales o comerciales. Puede navegar a través de miles de pistas de varios géneros, estados de ánimo, instrumentos y duraciones. También puedes filtrar por requisitos de atribución, lo que significa que puedes encontrar música que no requiera que le des crédito al artista o a la fuente.

- -

Música de Amazon

-

Otra opción para descargar música gratis es Amazon Music. Esta es una plataforma que proporciona descargas de música gratis para los miembros de Prime y ofrece un enorme catálogo de canciones para la compra. Puedes encontrar millones de canciones de varios artistas, géneros, estilos y épocas. También puede descubrir nueva música navegando a través de listas de reproducción, estaciones, gráficos y recomendaciones seleccionadas.

-

Para descargar música de Amazon Music, necesita tener una cuenta de Amazon y una membresía Prime. A continuación, puede ir a https://www.amazon.com/music o descargar la aplicación Amazon Music en su dispositivo. Puede buscar cualquier canción o álbum que desee o navegar por las categorías. También puede filtrar por precio para encontrar descargas de música gratuitas. Para descargar una canción o un álbum, haga clic en el botón "Gratis" o "Comprar" al lado. Puede guardar el archivo MP3 en su dispositivo.

-

MP3Juice

-

Una tercera opción para descargar música gratis es MP3Juice. Este es un sitio web que permite a los usuarios buscar y descargar archivos MP3 de varias fuentes, como YouTube, SoundCloud, Vimeo y más. También puede pegar una URL de cualquier archivo de vídeo o audio en línea y convertirlo a MP3. Puedes descargar tantas canciones como quieras gratis y sin registro.

-

Para descargar música de MP3Juice, debe ir a https://www.mp3juices.cc/ o descargar la aplicación MP3Juice en su dispositivo. Puede escribir cualquier palabra clave o frase relacionada con la canción o artista que desee o pegar una URL de cualquier archivo de vídeo o audio en línea. Puede hacer clic en el botón de búsqueda y esperar los resultados. Puede previsualizar cualquier pista haciendo clic en el botón de reproducción. Para descargar una pista, haga clic en el botón de descarga junto a él. A continuación, puede guardar el archivo MP3 en su dispositivo.

-

Cómo descargar 2pac Todas las canciones MP3

-

Paso 1: Elija un sitio o un servicio

- -
    -
  • La calidad y cantidad de la música: Usted debe buscar sitios o servicios que ofrecen archivos MP3 de alta calidad y tienen una gran colección de canciones y álbumes de 2pac.
  • -
  • El costo y la conveniencia de la descarga: Usted debe buscar sitios o servicios que ofrecen descargas gratuitas o asequibles y tienen procesos de descarga fáciles y rápidos.
  • -
  • La legalidad y seguridad de la descarga: Usted debe buscar sitios o servicios que están autorizados y autorizados para distribuir la música de 2pac y no contienen virus, malware o spyware.
  • -
-

Basado en estos factores, recomendamos usar YouTube Audio Library, Amazon Music o MP3Juice como sus mejores opciones para descargar 2pac todas las canciones MP3.

-

Paso 2: Buscar las canciones o álbumes que desea

-

El segundo paso para descargar 2pac todas las canciones MP3 es buscar las canciones o álbumes que desee. Dependiendo del sitio o servicio que hayas elegido, puedes usar diferentes métodos para encontrar y acceder a la música que estás buscando. Aquí hay algunos consejos sobre cómo hacerlo:

-
    -
  • Usar palabras clave, filtros o categorías: Puede escribir el nombre de la canción, álbum o artista que desee en el cuadro de búsqueda y usar filtros o categorías para reducir sus resultados. Por ejemplo, puedes filtrar por género, estado de ánimo, duración, popularidad, etc.
  • -
  • Utilice listas de reproducción, estaciones, gráficos o recomendaciones: Puede navegar a través de listas de reproducción, estaciones, gráficos o recomendaciones que cuentan con la música de 2pac o artistas similares. Por ejemplo, puedes encontrar listas de reproducción como "Best of 2pac", "2pac Essentials", "2pac Radio", etc.
  • -
  • Usar URL de videos en línea o archivos de audio: Puede pegar la URL de cualquier archivo de vídeo o audio en línea que contenga la música de 2pac y convertirlo a MP3. Por ejemplo, puede pegar la URL de un vídeo de YouTube de una canción o álbum de 2pac.
  • -
-

Una vez que encuentre las canciones o álbumes que desea, puede seleccionarlos haciendo clic en ellos o agregándolos a su carrito o cola.

- -

El tercer paso para descargar 2pac todas las canciones MP3 es descargar los archivos MP3 a su dispositivo. Dependiendo del sitio o servicio que elija, puede utilizar diferentes métodos y formatos para descargar los archivos de música. Aquí hay algunos ejemplos de cómo hacer eso:

-
    -
  • Haga clic en el icono de descarga junto a la pista: Este es el método más simple y común para descargar un archivo MP3. Solo tiene que hacer clic en el icono de descarga junto a la pista que desea y guardarlo en su dispositivo.
  • -
  • Haga clic derecho en la pista y seleccione "Guardar enlace como": Este es otro método para descargar un archivo MP3. Solo tiene que hacer clic derecho en la pista que desee y elegir "Guardar enlace como" en el menú. Luego puede elegir dónde guardarlo en su dispositivo.
  • -
  • Seleccione varias pistas y elija "Descargar": Este es un método para descargar múltiples archivos MP3 a la vez. Solo necesita seleccionar varias pistas manteniendo pulsada la tecla Ctrl (o la tecla Comando en Mac) y haciendo clic en ellas. A continuación, puede elegir "Descargar" en el menú o botón y guardarlos en su dispositivo.
  • -
  • Elija una opción de formato y calidad: Este es un método para personalizar la configuración de descarga. Solo tienes que elegir un formato (como MP3, WAV, FLAC, etc.) y una opción de calidad (como 128 kbit/s, 192 kbit/s, 320 kbit/s, etc.) desde el menú o el botón. A continuación, puede descargar el archivo MP3 con su configuración preferida.
  • -
-

Cómo disfrutar de 2pac Todas las canciones MP3

-

Juega en su reproductor de música favorito

-

Una vez que haya descargado 2pac todas las canciones MP3 a su dispositivo, puede reproducirlas en su reproductor de música favorito. Hay muchas aplicaciones o software que puede utilizar para reproducir sus archivos MP3, como VLC, iTunes, Spotify, Windows Media Player, etc. También puede crear listas de reproducción, ajustar el volumen, mezclar las canciones, repetir las canciones y más.

- -

Transferirlos a sus dispositivos portátiles o reproductores de medios

-

Si desea escuchar 2pac todas las canciones MP3 sobre la marcha, puede transferirlas a sus dispositivos portátiles o reproductores multimedia. Puedes usar dispositivos como iPods, reproductores de MP3, unidades USB, CD, etc. También puedes usar diferentes métodos para transferir tus archivos MP3, como copiar y pegar, sincronizar, grabar, etc.

-

Para transferir tus archivos MP3 a tus dispositivos portátiles o reproductores multimedia, necesitas conectar tu dispositivo a tu computadora usando un cable o una conexión inalámbrica. Luego, debe abrir la aplicación o el software que admite su dispositivo y localizar los archivos en su computadora. También puede arrastrar y soltar los archivos a la aplicación o software. Luego debe seleccionar las pistas que desea transferir y hacer clic en el botón de transferencia.

-

Compártelos con tus amigos o familiares

-

Si quieres compartir 2pac todas las canciones MP3 con tus amigos o familiares, puedes usar varios métodos para hacerlo. Puedes usar plataformas de redes sociales, como Facebook, Twitter, Instagram, etc. También puedes usar servicios de correo electrónico, como Gmail, Yahoo Mail, Outlook, etc. También puedes usar conexiones Bluetooth o Wi-Fi para enviar o recibir archivos.

-

Para compartir sus archivos MP3 con sus amigos o familiares, debe seleccionar las pistas que desea compartir y haga clic en el botón compartir. Luego debe elegir el método y la plataforma que desea usar y seguir las instrucciones. También puede agregar un mensaje o un comentario a sus archivos compartidos.

-

Conclusión

-

En este artículo, le hemos mostrado cómo descargar 2pac todas las canciones MP3 de forma gratuita y legal. También te hemos dado algunos consejos sobre cómo disfrutar de su música en diferentes dispositivos y plataformas. Esperamos que este artículo te haya ayudado a descubrir y apreciar la música de una leyenda del rap.

- -

Entonces, ¿qué estás esperando? Adelante y descargar 2pac todas las canciones MP3 ahora y disfrutar de la música de una leyenda del rap!

-

Preguntas frecuentes

-
    -
  • Q: ¿Dónde puedo encontrar más información sobre la vida y la carrera de 2pac?
  • -
  • A: Puede encontrar más información sobre la vida y carrera de 2pac en su sitio web oficial (https://www.2pac.com/), su página de Wikipedia (https://en.wikipedia.org/wiki/Tupac_Shakur), o su libro de biografías (Tupac Shakur: La vida y los tiempos de un icono americano por Tayannah Lee McQuillar y Fred L. Johnson III).
  • -
  • Q: ¿Cuáles son algunas de las canciones y álbumes más populares de 2pac?
  • -
  • A: Algunas de las canciones y álbumes más populares de 2pac incluyen California Love, Changes, Hail Mary, Dear Mama, I Ain’t Mad at Cha, All Eyez on MeThe Don Kilti: The 7 Day/i, i i Against The Greatest World, i>> Mejor Dayz, etc.
  • -
  • Q: ¿Cómo puedo apoyar el legado y las causas de 2pac?
  • -
  • A: Puedes apoyar el legado y las causas de 2pac donando a su fundación (https://www.tasf.org/), que apoya la educación y el empoderamiento de los jóvenes, especialmente los de entornos desfavorecidos. También puedes comprar su mercancía oficial (https://www.2pac.com/store/), que incluye sus icónicas imágenes y citas. También puede unirse a su club de fans (https://www.2pac.com/fan-club/), que ofrece contenido exclusivo y beneficios para los miembros.
  • -
  • Q: ¿Cómo puedo descargar 2pac todas las canciones MP3 gratis y legalmente?
  • -
  • A: Puede descargar 2pac todas las canciones MP3 de forma gratuita y legal mediante el uso de sitios o servicios que ofrecen música libre de derechos o tienen el permiso para distribuir la música de 2pac. Algunos de estos sitios o servicios incluyen YouTube Audio Library, Amazon Music y MP3Juice.
  • -
  • Q: ¿Cómo puedo disfrutar de 2pac todas las canciones MP3 en diferentes dispositivos y plataformas?
  • - -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Conseguir Sobre Ella Steamunlocked.md b/spaces/Benson/text-generation/Examples/Descargar Conseguir Sobre Ella Steamunlocked.md deleted file mode 100644 index dbd0376ad4e3b6ea816edb06e96c26113207f733..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Conseguir Sobre Ella Steamunlocked.md +++ /dev/null @@ -1,93 +0,0 @@ -
-

Descargar Cómo superarlo Steamunlocked: Una guía para jugadores frustrados

-

Si usted está buscando un juego que pondrá a prueba su paciencia, habilidad y cordura, entonces es posible que desee probar Cómo superarlo con Bennett Foddy. Este es un juego de escalada de castigo que se ha vuelto infame por su dificultad y nivel de frustración. En este artículo, te contaremos todo lo que necesitas saber sobre este juego, cómo descargarlo desde Steamunlocked y cómo vencerlo más rápido y fácil. Sigue leyendo si te atreves.

-

¿Qué es superar con Bennett Foddy?

-

Getting Over It with Bennett Foddy es un juego que fue lanzado en 2017 por Bennett Foddy, un desarrollador de juegos australiano y profesor de diseño de juegos. El juego es un homenaje al clásico B-Game 2002 de Jazzuo 'Sexy Hiking', que también involucró escalar una montaña con un martillo y una olla.

-

descargar conseguir sobre ella steamunlocked


Download Zip ☆☆☆☆☆ https://bltlly.com/2v6MyZ



-

La premisa y el modo de juego del juego

-

La premisa del juego es simple: juegas como un hombre llamado Diógenes que está atrapado en una olla de metal y tiene que usar un martillo para escalar una enorme montaña hecha de objetos aleatorios. El modo de juego no es tan simple: tienes que mover el martillo con el ratón, y eso es todo lo que hay. No hay puntos de control, ni puntos de ahorro, ni atajos, ni pistas, ni tutoriales, ni piedad. Si caes, pierdes todo tu progreso y tienes que empezar de nuevo desde el principio. El juego está diseñado para ser extremadamente duro y frustrante, como Foddy mismo admite: "Un juego que hice para un cierto tipo de persona. Para hacerles daño."

-

La recepción y popularidad del juego

- -

Los desafíos y recompensas del juego

-

El juego no es para todos. Requiere mucha paciencia, habilidad, concentración y perseverancia para superar sus obstáculos y llegar a la cima de la montaña. Muchos jugadores se han dado por vencidos o la rabia se ha ido después de fallar varias veces. Sin embargo, algunos jugadores también han encontrado que el juego es gratificante y satisfactorio una vez que lo dominan. El juego ofrece grandes misterios y una maravillosa recompensa para aquellos que llegan a la cima de la montaña, así como una sensación de logro y orgullo. El juego también proporciona algunas ideas y observaciones interesantes sobre la vida, el fracaso, el éxito y la felicidad a través de la voz del propio Foddy, que narra el juego mientras juegas.

-

¿Qué es Steamunlocked?

-

Steamunlocked es un sitio web que te permite descargar juegos de PC gratis sin usar Steam o cualquier otra plataforma. Afirma ofrecer más de 5000 juegos preinstalados y listos para jugar.

-

La definición y características de Steamunlocked

-

Steamunlocked es un sitio web que proporciona enlaces directos para descargar juegos de PC de varias fuentes. El sitio web no alberga ningún archivo en su

La definición y características de Steamunlocked

-

Steamunlocked es un sitio web que proporciona enlaces directos para descargar juegos de PC de varias fuentes. El sitio web no aloja archivos en sus propios servidores, sino que lo redirige a otros sitios de alojamiento de archivos como Uploadhaven, Mega o Mediafire. El sitio web afirma ofrecer más de 5000 juegos que están preinstalados y listos para jugar, lo que significa que no es necesario utilizar Steam o cualquier otra plataforma para ejecutarlos. También puede solicitar juegos que no están disponibles en el sitio web, y los administradores intentarán subirlos lo antes posible.

-

Los pros y los contras de usar Steamunlocked

-

Usar Steamunlocked tiene algunas ventajas y desventajas que debes tener en cuenta antes de descargar cualquier juego de él. Estos son algunos de ellos:

- -
Pros
- Puedes descargar juegos de PC gratis sin pagar nada. - Puedes encontrar anuncios, ventanas emergentes o redirecciones que pueden ser molestos o inseguros.
- Puedes acceder a juegos que no están disponibles en tu región o están prohibidos por Steam.- Puede violar los términos de servicio o los derechos de propiedad intelectual de los desarrolladores o editores de juegos.
- Puedes jugar juegos sin conexión a Internet o una cuenta de Steam. - Puedes perderte actualizaciones, parches, DLC, funciones multijugador o logros exclusivos de Steam u otras plataformas.
- Puedes descargar juegos más rápido que usando torrents u otros métodos peer-to-peer. - Usted puede arriesgarse a obtener malware, virus o archivos dañados que pueden dañar su computadora o comprometer sus datos.
- - - - - - - - - - - - - - - - - - - - - - - - -
QuestionAnswer
Is Apkshub Internet Cafe Simulator 2 free to play?Yes, Apkshub Internet Cafe Simulator 2 is free to play. However, the game might have some in-app purchases or ads that can enhance your gaming experience or support the game developer.
Is Apkshub Internet Cafe Simulator 2 available on other platforms?No, Apkshub Internet Cafe Simulator 2 is only available on Android devices. The game is not available on iOS, Windows, Mac, Linux, or consoles.
Is Apkshub Internet Cafe Simulator 2 online or offline?Apkshub Internet Cafe Simulator 2 is an online game that requires a stable internet connection to play. You cannot play the game offline or without internet access.
Is Apkshub Internet Cafe Simulator 2 multiplayer or single-player?Apkshub Internet Cafe Simulator 2 is a single-player game that does not have a multiplayer mode or feature. You cannot play the game with or against other players.
How can I contact the game developer or report a problem?You can contact the game developer or report a problem by sending an email to cheesecakedev@gmail.com or visiting their website at Cheesecake Dev. You can also follow them on their social media accounts on Facebook, Twitter, Instagram, YouTube, etc.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/College Romance Season 3 (Hindi) Web Series Download Filmywap Sony Liv Originals.md b/spaces/congsaPfin/Manga-OCR/logs/College Romance Season 3 (Hindi) Web Series Download Filmywap Sony Liv Originals.md deleted file mode 100644 index d38e4af84c99017cf608776f55ded2b00bb31d0a..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/College Romance Season 3 (Hindi) Web Series Download Filmywap Sony Liv Originals.md +++ /dev/null @@ -1,172 +0,0 @@ - -

College Romance Season 3 Download Filmywap

-

If you are a fan of Indian web series, you might have heard of College Romance, a comedy-drama series that follows the lives and loves of three college friends. The third season of this popular show was released on September 16, 2022, on SonyLIV, and it has received rave reviews from critics and viewers alike. But what if you don't have a subscription to SonyLIV or you want to watch the show offline? Is there a way to download College Romance Season 3 for free?

-

The answer is yes, there is a way to download College Romance Season 3 for free, but it comes with some risks and challenges. In this article, we will tell you how to download College Romance Season 3 from Filmywap, a notorious website that offers free downloads of Bollywood movies, Hollywood movies in Hindi dubbed, and other regional language movies. We will also tell you about the risks of downloading College Romance Season 3 from Filmywap, and the alternatives to downloading College Romance Season 3 from Filmywap.

-

college romance season 3 download filmywap


Download File ✸✸✸ https://urlca.com/2uO4zl



-

Introduction

-

What is College Romance Season 3?

-

College Romance Season 3 is the third installment of the hit web series College Romance, which was created by The Timeliners, a YouTube channel that produces youth-centric content. The series revolves around three college friends, Naira (Apoorva Arora), Karan (Keshav Sadhna), and Trippy (Gagan Arora), who navigate their friendship, romance, and career in the final year of college. The series also features other characters such as Bagga (Shreya Mehta), Dipika (Manjot Singh), Dhatrapriya (Hira Ashar), and Raveena (Kritika Avasthi).

-

College Romance Season 3 consists of five episodes, each lasting about 30 minutes. The episodes are titled Happy Ending, No More Secrets, Loser, Beer & Whiskey, and Problem Kya Hai?. The season follows the ups and downs of the friends as they deal with long-distance relationships, infidelity, scandals, insecurities, and choices. The season also introduces new twists and turns in the lives of the characters, such as new lovers, new rivals, and new secrets.

-

Why is College Romance Season 3 popular?

-

College Romance Season 3 is popular because it is a relatable, funny, and entertaining show that captures the essence of college life in India. The show has a loyal fan base that has been following the series since its first season in 2018. The show has also received positive feedback from critics who have praised its writing, direction, acting, and music. Some of the reasons why College Romance Season 3 is popular are:

- -

How to download College Romance Season 3 from Filmywap?

-

What is Filmywap?

Filmywap is a website that provides free downloads of movies and web series in various languages and formats. The website is known for leaking the latest releases of Bollywood, Hollywood, and other regional cinema, as well as popular web series from platforms like Netflix, Amazon Prime Video, Hotstar, SonyLIV, and others. Filmywap offers a wide range of genres and categories, such as action, comedy, drama, horror, thriller, romance, and more. The website also allows users to request movies and web series that are not available on the site.

-

How to access Filmywap?

-

Accessing Filmywap is not easy, as the website is illegal and banned by the government of India and other countries. The website keeps changing its domain name and URL to evade the authorities and continue its operations. Some of the domain names and URLs that Filmywap has used in the past are filmywap.com, filmywap.in, filmywap.net, filmywap.org, filmywap.vip, filmywap.co, filmywap.cc, filmywap.me, filmywap.xyz, and more. However, these domains and URLs are often blocked or taken down by the cyber police or the internet service providers.

-

Therefore, to access Filmywap, users need to use a VPN (virtual private network) service that can bypass the geo-restrictions and hide their IP address. A VPN service can also protect the users from malware and viruses that might infect their devices while downloading from Filmywap. Some of the VPN services that can be used to access Filmywap are NordVPN, ExpressVPN, Surfshark, CyberGhost, IPVanish, and more. However, using a VPN service might slow down the internet speed and affect the download quality.

-

How to find College Romance Season 3 on Filmywap?

-

Finding College Romance Season 3 on Filmywap is not difficult, as the website has a user-friendly interface and a search bar that can help users find their desired movies and web series. Users can also browse through the categories and genres on the homepage of Filmywap to find College Romance Season 3. However, users should be careful while clicking on any link or button on Filmywap, as they might encounter pop-up ads or redirects that can lead them to malicious websites or download unwanted software.

-

College Romance Season 3 Download Filmywap (Hindi) 480p, 720p & 1080p
-College Romance Season 3 Download Filmywap, College Romance Season 3 All Episodes Dual Audio (Hindi) 720p, 1080p, 4K, BrRip, DvdRip, HD Quality Web Series
-College Romance Season 3 (2022) All Episodes Download Filmywap
-College Romance Season 3 Hindi Dubbed All Episodes available in WebRip, HQ Fan Dubbed, Web-DL & HD-RIP Qualities
-College Romance Season 3 Download (2022) 480p 720p 1080p Full Download
-Download College Romance (Season 3) Complete Hindi ALL Episodes Download | Sony Liv Series | Watch College Romance S03 in Hindi Online
-College Romance Series College Romance 2022 Dual Audio Hindi-English 480p In 400MB 720p In 900MB 1080p In Hindi Dubbed Full Movie Gdrive Links
-College Romance is a Upcoming Indian hindi-language comedy drama romance Series
-The Series release date is September 23, 2022. directed by Parijat Joshi
-The series starring Keshav Sadhna, Gagan Arora and Apporva Arora in the lead cast in this movie
-Three best friends look for love, laughs and some lifelong memories while attending college together
-Top Cast Of College Romance Season 3 Gagan Arora Apporva Arora Keshav Sadhna Shreya Mehta Nupur Nagpal Jahnvi Rawat Eklavey Kashyap
-College Romance Season 3 full Series Download 9xMovies
-College Romance Season 3 Full Movie Download Filmyzilla
-College Romance Season 3 Hd Movie Download Filmymeet
-College Romance Season 3 2022 Movie Free Download 9kmovies
-College Romance Season 3 Hindi Dubbed Download Mp4Moviez
-Watch Online College Romance Season 3 Full Movie Tamilmv
-College Romance Season 3 Full Movie Free Download Worldfree4u
-Streaming, rent, or buy – Season 3: Currently you are able to watch "College Romance - Season 3" streaming on Sony Liv
-How to watch College Romance Season 3 online for free in HD quality
-College Romance Season 3 download link leaked by Filmywap and other torrent sites
-College Romance Season 3 review: A hilarious and heartwarming web series about friendship and love
-College Romance Season 3 trailer: The gang is back with more fun and drama in college life
-College Romance Season 3 cast and crew: Everything you need to know about the actors and makers of the web series
-College Romance Season 3 release date and time: When and where to watch the web series online
-College Romance Season 3 songs and music: The soundtrack of the web series features some catchy and romantic tunes
-College Romance Season 3 episodes list: How many episodes are there in the web series and what are their titles and durations
-College Romance Season 3 spoilers: What to expect from the web series plot and story
-College Romance Season 3 memes: The best and funniest memes from the web series that will make you laugh out loud
-College Romance Season 3 quotes: The most memorable and relatable dialogues from the web series that will stay with you
-College Romance Season 3 ratings: How the web series fared on IMDb, Rotten Tomatoes, and other platforms
-College Romance Season 3 awards and nominations: The web series has won several accolades and recognition for its content and performances
-College Romance Season 3 behind the scenes: The making of the web series and some interesting facts and trivia about it
-College Romance Season 3 fan theories: Some fan speculations and predictions about the web series ending and future seasons

-

To find College Romance Season 3 on Filmywap, users can follow these steps:

-
    -
  1. Open a VPN service on your device and connect to a server in a country where Filmywap is not banned.
  2. -
  3. Open a web browser and type the latest domain name or URL of Filmywap in the address bar.
  4. -
  5. On the homepage of Filmywap, type College Romance Season 3 in the search bar and click on the search icon.
  6. -
  7. Alternatively, you can scroll down to the category of Web Series and click on it.
  8. -
  9. Then, you can look for College Romance Season 3 among the list of web series available on Filmywap.
  10. -
  11. Once you find College Romance Season 3 on Filmywap, click on it to open its page.
  12. -
-

How to download College Romance Season 3 from Filmywap?

-

Downloading College Romance Season 3 from Filmywap is easy, as the website provides multiple download links and options for each movie and web series. Users can choose from different formats and resolutions, such as MP4, MKV, AVI, 480p, 720p, 1080p, etc. Users can also select from different sources and servers, such as Google Drive, Mega.nz, Mediafire.com,

Downloading College Romance Season 3 from Filmywap is easy, as the website provides multiple download links and options for each movie and web series. Users can choose from different formats and resolutions, such as MP4, MKV, AVI, 480p, 720p, 1080p, etc. Users can also select from different sources and servers, such as Google Drive, Mega.nz, Mediafire.com, etc. However, users should be aware that some of the download links and options might not work or might be broken.

-

To download College Romance Season 3 from Filmywap, users can follow these steps:

-
    -
  1. After opening the page of College Romance Season 3 on Filmywap, scroll down to the section of Download Links.
  2. -
  3. Choose the format and resolution that you prefer and click on the download button or link.
  4. -
  5. You might be redirected to another website or page where you have to verify that you are not a robot or complete a captcha.
  6. -
  7. After verifying, you will be taken to the source or server where the file is hosted.
  8. -
  9. Click on the download button or link on the source or server website and wait for the file to be downloaded.
  10. -
  11. You might have to repeat these steps for each episode of College Romance Season 3.
  12. -
-

What are the risks of downloading College Romance Season 3 from Filmywap?

-

Legal issues

-

Downloading College Romance Season 3 from Filmywap is illegal and unethical, as it violates the copyright laws and the intellectual property rights of the creators and producers of the show. Filmywap is a piracy website that distributes movies and web series without obtaining the proper licenses and permissions from the rightful owners. By downloading College Romance Season 3 from Filmywap, you are supporting piracy and harming the entertainment industry.

-

Piracy is a serious crime that can attract legal actions and penalties from the authorities. According to the Indian law, anyone who is found guilty of downloading or distributing pirated content can face imprisonment for up to three years, a fine of up to Rs. 10 lakh, or both. Therefore, you should avoid downloading College Romance Season 3 from Filmywap and respect the hard work and efforts of the makers of the show.

-

Malware and viruses

-

Downloading College Romance Season 3 from Filmywap is risky and unsafe, as it can expose your device and data to malware and viruses that can harm your system and compromise your privacy. Filmywap is an unregulated and unsecured website that does not follow any quality standards or safety measures. The website hosts files that are uploaded by unknown sources and users who might have malicious intentions. By downloading College Romance Season 3 from Filmywap, you are risking your device and data to be infected by malware and viruses that can:

- -

Poor quality and fake files

-

Downloading College Romance Season 3 from Filmywap is disappointing and frustrating, as it can result in poor quality and fake files that can ruin your viewing experience. Filmywap is an unreliable and untrustworthy website that does not guarantee the quality or authenticity of the files that it offers. The website provides files that are compressed, cropped, edited, or dubbed to reduce their size and quality. By downloading College Romance Season 3 from Filmywap, you are settling for files that can have:

- -

What are the alternatives to downloading College Romance Season 3 from Filmywap?

-

Official streaming platforms

-

The best alternative to downloading College Romance Season 3 from Filmywap is to watch it on the official streaming platform where it was released, which is SonyLIV. SonyLIV is a premium online video platform that offers a variety of movies, web series, live TV channels, sports events, music videos, and more. SonyLIV has exclusive rights to stream College Romance Season 3 online in India and other countries. By watching College Romance Season 3 on SonyLIV, you are supporting the legal and legitimate way of consuming content online.

-

To watch College Romance Season 3 on SonyLIV, you need to have a subscription to the platform. SonyLIV offers different subscription plans

To watch College Romance Season 3 on SonyLIV, you need to have a subscription to the platform. SonyLIV offers different subscription plans that suit different needs and budgets. Some of the subscription plans are:

- - - - - - - - - - - - - - - - - - - - - -
PlanPriceFeatures
LIV Special+Rs. 399 per yearAccess to all SonyLIV Originals, TV shows, movies, and live sports (except cricket)
LIV PremiumRs. 299 per month or Rs. 999 per yearAccess to all SonyLIV Originals, TV shows, movies, live sports (including cricket), and international content
LIV SpecialRs. 199 per yearAccess to select SonyLIV Originals, TV shows, movies, and live sports (except cricket)
-

To subscribe to SonyLIV, you need to follow these steps:

-
    -
  1. Visit the official website of SonyLIV or download the app on your device.
  2. -
  3. Create an account or sign in with your existing account.
  4. -
  5. Select the subscription plan that you want and click on the subscribe button.
  6. -
  7. Choose the payment method and complete the payment process.
  8. -
  9. Enjoy watching College Romance Season 3 and other content on SonyLIV.
  10. -
-

Legal and safe websites

-

If you don't want to subscribe to SonyLIV or you want to watch College Romance Season 3 on other platforms, you can also opt for some legal and safe websites that offer free or low-cost streaming of movies and web series. These websites are authorized and licensed by the content owners and they provide high-quality and authentic files that are free from malware and viruses. Some of the legal and safe websites that you can use to watch College Romance Season 3 are:

- -

Conclusion

-

In conclusion, College Romance Season 3 is a popular web series that you can watch online or offline depending on your preference. However, you should be careful while choosing the source or platform from where you want to watch or download the show. Downloading College Romance Season 3 from Filmywap is illegal, risky, and disappointing, as it can land you in legal trouble, infect your device with malware and viruses, or provide you with poor quality or fake files. Therefore, you should avoid downloading College Romance Season 3 from Filmywap and opt for the official streaming platform SonyLIV or the legal and safe websites that we have mentioned above. By doing so, you will not only enjoy watching College Romance Season 3 in the best possible way but also support the creators and producers of the show who deserve your appreciation and respect.

-

Frequently Asked Questions (FAQs)

-

Q1: When was College Romance Season 3 released?

-

A1: College Romance Season 3 was released on September 16, 2022, on SonyLIV.

-

Q2: How many episodes are there in College Romance Season 3?

-

A2: There are five episodes in College Romance Season 3, each lasting about 30 minutes.

-

Q3: Who are the main cast members of College Romance Season 3?

-

A3: The main cast members of College Romance Season 3 are Apoorva Arora as Naira, Keshav Sadhna as Karan, Gagan

A3: The main cast members of College Romance Season 3 are Apoorva Arora as Naira, Keshav Sadhna as Karan, Gagan Arora as Trippy, Shreya Mehta as Bagga, Manjot Singh as Dipika, Hira Ashar as Dhatrapriya, and Kritika Avasthi as Raveena.

-

Q4: What are the songs featured in College Romance Season 3?

-

A4: The songs featured in College Romance Season 3 are:

- -

Q5: Where can I watch the trailer of College Romance Season 3?

-

A5: You can watch the trailer of College Romance Season 3 on the official YouTube channel of The Timeliners or on the official website of SonyLIV. Here are the links to the trailer:

-

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download Dragon Nest Reborn and Become a Legend.md b/spaces/congsaPfin/Manga-OCR/logs/Download Dragon Nest Reborn and Become a Legend.md deleted file mode 100644 index 91f2f2e5207a68a8aa72717121324b718c30ab3e..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Download Dragon Nest Reborn and Become a Legend.md +++ /dev/null @@ -1,176 +0,0 @@ - -

Download Dragon Nest Reborn: A Guide for Beginners

-

If you are looking for a fast-paced, action-packed, and challenging MMORPG, you might want to try Dragon Nest Reborn. Dragon Nest Reborn is a private server of the popular game Dragon Nest, which offers a unique and hardcore experience for players who want to relive the old times of the game. In this article, we will guide you on how to download, install, and play Dragon Nest Reborn, as well as give you some tips and tricks to enjoy the game more.

-

What is Dragon Nest Reborn?

-

A brief introduction to the game and its features

-

Dragon Nest is a 3D fantasy MMORPG that was released in 2010 by Eyedentity Games. The game features a dynamic combat system, where players can dodge, block, and combo attacks using their skills and weapons. The game also has a rich story, diverse characters, and various modes of gameplay, such as PvE, PvP, raids, nests, and more.

-

download dragon nest reborn


Download File ⚙⚙⚙ https://urlca.com/2uObU3



-

Dragon Nest Reborn is a private server of Dragon Nest that was launched in 2017 by Alipingames. It is based on the T4 version of the game, which is considered by many fans as the best version of Dragon Nest. Dragon Nest Reborn aims to provide a hardcore and nostalgic experience for players who miss the old days of the game. Some of the features of Dragon Nest Reborn are:

- -

The difference between Dragon Nest Reborn and other Dragon Nest servers

-

Dragon Nest Reborn is different from other Dragon Nest servers in many ways. Here are some of the main differences:

- - - - - - - - - - - - -
Dragon Nest RebornOther Dragon Nest Servers
Has no cash shop or pay-to-win elementsHas cash shop or pay-to-win elements
Has no costume or mount gacha systemHas costume or mount gacha system
Has no enhancement or conversion systemHas enhancement or conversion system
Has no awakening or specialization systemHas awakening or specialization system
Has no dragon jade or talisman systemHas dragon jade or talisman system
Has no class rebalance or revamp patchesHas class rebalance or revamp patches
Has no new classes or skills addedHas new classes or skills added
Has no new dungeons or nests addedHas new dungeons or nests added
Has no new events or updates addedHas new events or updates added
Has no bugs or glitches fixedHas bugs or glitches fixed
-

How to download and install Dragon Nest Reborn?

-

The system requirements and the download links

Before you download and install Dragon Nest Reborn, you need to make sure that your computer meets the minimum system requirements. Here are the system requirements for Dragon Nest Reborn:

- -

If your computer meets the system requirements, you can proceed to download Dragon Nest Reborn from the official website. Here are the download links for Dragon Nest Reborn:

- -

The steps to install and launch the game

-

After you download Dragon Nest Reborn, you need to install and launch the game. Here are the steps to install and launch Dragon Nest Reborn:

-
    -
  1. Extract the downloaded file using WinRAR or any other extraction software.
  2. -
  3. Run the setup.exe file and follow the instructions to install the game.
  4. -
  5. Create a shortcut of the DragonNest.exe file on your desktop or any other location.
  6. -
  7. Run the shortcut as administrator and wait for the game to update.
  8. -
  9. Create an account on the official website or log in with your existing account.
  10. -
  11. Select a server and a channel to enter the game.
  12. -
-

The tips to optimize the game performance and settings

-

To enjoy Dragon Nest Reborn without any lag or crash issues, you need to optimize the game performance and settings. Here are some tips to optimize Dragon Nest Reborn:

- -

How to create and customize your character?

The available classes and their skills

-

Dragon Nest Reborn offers four main classes to choose from: Warrior, Archer, Sorceress, and Cleric. Each class has two subclasses that can be unlocked at level 15, and each subclass has two specializations that can be unlocked at level 45. Each class and subclass has its own unique skills and playstyle, so you should choose the one that suits your preference and personality. Here is a brief overview of the classes and their skills:

-

download dragon nest reborn indonesia
-download dragon nest reborn full client
-download dragon nest reborn 64 bit
-download dragon nest reborn latest patch
-download dragon nest reborn manual patch
-download dragon nest reborn torrent
-download dragon nest reborn zip file
-download dragon nest reborn sea
-download dragon nest reborn us
-download dragon nest reborn private server
-download dragon nest reborn apk
-download dragon nest reborn android
-download dragon nest reborn pc
-download dragon nest reborn online
-download dragon nest reborn free
-download dragon nest reborn mod apk
-download dragon nest reborn offline
-download dragon nest reborn for mac
-download dragon nest reborn for windows 10
-download dragon nest reborn for windows 7
-download dragon nest reborn system requirements
-download dragon nest reborn direct x
-download dragon nest reborn nvidia driver
-download dragon nest reborn ati driver
-download dragon nest reborn steam
-how to download dragon nest reborn
-where to download dragon nest reborn
-best site to download dragon nest reborn
-fastest way to download dragon nest reborn
-easiest way to download dragon nest reborn
-tips to download dragon nest reborn
-guide to download dragon nest reborn
-tutorial to download dragon nest reborn
-review of download dragon nest reborn
-benefits of download dragon nest reborn
-features of download dragon nest reborn
-gameplay of download dragon nest reborn
-classes of download dragon nest reborn
-skills of download dragon nest reborn
-items of download dragon nest reborn
-quests of download dragon nest reborn
-dungeons of download dragon nest reborn
-nests of download dragon nest reborn
-raids of download dragon nest reborn
-pvp of download dragon nest reborn
-events of download dragon nest reborn
-updates of download dragon nest reborn
-news of download dragon nest reborn

- -

The character creation and customization options

-

After you choose your class, you can create and customize your character according to your liking. You can change your character's name, gender, face, hair, skin color, eye color, voice, and costume. You can also preview your character's skills and animations before you confirm your creation. You can create up to four characters per account.

-

The recommended builds and equipment for each class

-

To make the most out of your character's potential, you need to follow a suitable build and equip the best equipment for your class. A build is a combination of skills and stats that determines your character's role and performance in the game. An equipment is a set of items that enhances your character's attributes and abilities. Here are some of the recommended builds and equipment for each class:

- -

How to play and progress in Dragon Nest Reborn?

The basic gameplay mechanics and controls

-

Dragon Nest Reborn is a game that requires skill and strategy to play. You need to master the basic gameplay mechanics and controls to survive and succeed in the game. Here are some of the basic gameplay mechanics and controls:

- -

The main quests and dungeons to complete

-

Dragon Nest Reborn has a rich and immersive story that unfolds through various quests and dungeons. You need to complete the main quests and dungeons to progress in the game and unlock new features and content. Here are some of the main quests and dungeons to complete:

- -

The rewards and benefits of playing Dragon Nest Reborn

-

Dragon Nest Reborn is a game that rewards you for playing and having fun. You can earn various rewards and benefits by completing quests, dungeons, achievements, events, and more. Here are some of the rewards and benefits of playing Dragon Nest Reborn:

- -

Conclusion

-

Dragon Nest Reborn is a game that offers a unique and hardcore experience for MMORPG fans who want to relive the old times of Dragon Nest. It is a game that requires skill and strategy to play, as well as dedication and passion to progress. It is a game that has a rich and immersive story, diverse and customizable characters, and various and exciting modes of gameplay. It is a game that rewards you for playing and having fun, as well as for being loyal and supportive. If you are interested in playing Dragon Nest Reborn, you can download and install it from the official website. You can also join the official Discord server or Facebook page to interact with other players and get the latest news and updates. We hope that this guide has helped you to get started with Dragon Nest Reborn, and we wish you a happy and adventurous journey in the game.

-

FAQs

-

Here are some of the frequently asked questions about Dragon Nest Reborn:

-
    -
  1. Q: Is Dragon Nest Reborn free to play?
  2. -
  3. A: Yes, Dragon Nest Reborn is free to play. You do not need to pay anything to download, install, or play the game.
  4. -
  5. Q: Is Dragon Nest Reborn legal?
  6. -
  7. A: Yes, Dragon Nest Reborn is legal. It has obtained the permission and license from Eyedentity Games, the original developer of Dragon Nest, to operate as a private server.
  8. -
  9. Q: Is Dragon Nest Reborn safe?
  10. -
  11. A: Yes, Dragon Nest Reborn is safe. It has a reliable and secure server that protects your account and data from any hacking or phishing attempts.
  12. -
  13. Q: Is Dragon Nest Reborn updated?
  14. -
  15. A: No, Dragon Nest Reborn is not updated. It is based on the T4 version of the game, which is the last version before the major changes and additions were made to the game. It does not have any new content or features that are present in other servers.
  16. -
  17. Q: Is Dragon Nest Reborn fun?
  18. -
  19. A: Yes, Dragon Nest Reborn is fun. It is a game that offers a unique and hardcore experience for MMORPG fans who want to relive the old times of Dragon Nest. It is a game that requires skill and strategy to play, as well as dedication and passion to progress. It is a game that has a rich and immersive story, diverse and customizable characters, and various and exciting modes of gameplay. It is a game that rewards you for playing and having fun, as well as for being loyal and supportive.
  20. -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download NBA 2K19 and Enjoy the New Features and Improvements.md b/spaces/congsaPfin/Manga-OCR/logs/Download NBA 2K19 and Enjoy the New Features and Improvements.md deleted file mode 100644 index 7a39b55aee16cd22e1af1370eecee8aec33575e4..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Download NBA 2K19 and Enjoy the New Features and Improvements.md +++ /dev/null @@ -1,231 +0,0 @@ - -

NBA 2K19 Download: How to Get the Best Basketball Game on Your PC or Mobile Device

-

If you are a fan of basketball, you probably have heard of NBA 2K19, the latest installment of the popular NBA 2K series. This game is widely regarded as one of the best basketball games ever made, with realistic graphics, exciting gameplay, and diverse modes. Whether you want to create your own player, manage your own team, or relive the history of the NBA, you can do it all in NBA 2K19.

-

nba 2k19 download


Download Zip –––––>>> https://urlca.com/2uO4UT



-

But how can you get this amazing game on your PC or mobile device? In this article, we will show you how to download NBA 2K19 on your preferred platform, and how to optimize your experience with some tips and tricks. Let's get started!

-

What is NBA 2K19 and why should you play it?

-

NBA 2K19 is a basketball simulation game developed by Visual Concepts and published by 2K Sports. It was released in September 2018 for Microsoft Windows, PlayStation 4, Xbox One, Nintendo Switch, Android, and iOS devices. It is the 20th edition of the NBA 2K franchise, which celebrates its 20th anniversary in 2018.

-

NBA 2K19 is not just a game, it is a celebration of basketball culture. It features many aspects of the sport, from the players, teams, and arenas, to the music, commentary, and presentation. It also offers many options for customization, allowing you to create your own unique basketball experience.

-

The features and gameplay of NBA 2K19

-

NBA 2K19 boasts many features that make it stand out from other basketball games. Some of them are:

-

nba 2k19 free download pc
-nba 2k19 download apk
-nba 2k19 download android
-nba 2k19 download for ios
-nba 2k19 download size
-nba 2k19 download xbox one
-nba 2k19 download ps4
-nba 2k19 download steam
-nba 2k19 download code
-nba 2k19 download mac
-nba 2k19 download full version
-nba 2k19 download highly compressed
-nba 2k19 download ocean of games
-nba 2k19 download reddit
-nba 2k19 download update
-nba 2k19 download crack
-nba 2k19 download roster
-nba 2k19 download mods
-nba 2k19 download patch
-nba 2k19 download torrent
-nba 2k19 download mobile
-nba 2k19 download switch
-nba 2k19 download pc game
-nba 2k19 download offline
-nba 2k19 download windows 10
-nba 2k19 download ppsspp
-nba 2k19 download obb
-nba 2k19 download data
-nba 2k19 download fitgirl
-nba 2k19 download skidrow
-nba 2k19 download online
-nba 2k19 download iso
-nba 2k19 download key
-nba 2k19 download license key
-nba 2k19 download mega.nz
-nba 2k19 download google drive
-nba 2k19 download zip file
-nba 2k19 download cheat engine table[^1^]
-nba 2k19 download cyberface look up tool[^1^]
-nba 2k19 download limnono modifier english patch[^1^]

- -

The modes and challenges of NBA 2K19

-

NBA 2K19 offers many modes and challenges that cater to different tastes and preferences. Some of them are:

- -

The graphics and sound of NBA 2K19

-

NBA 2K19 delivers a stunning visual and auditory experience that makes you feel like you are watching a real NBA game. The graphics are crisp and detailed, with realistic lighting, shadows, and reflections. The sound is immersive and atmospheric, with crowd noise, arena music, and player chatter. You can also customize the graphics and sound settings to suit your preferences and device capabilities.

-

How to download NBA 2K19 on your PC or mobile device?

-

NBA 2K19 is available for download on various platforms, including PC and mobile devices. However, the download process may vary depending on the platform you choose. Here are some of the ways you can download NBA 2K19 on your PC or mobile device:

-

The requirements and steps for downloading NBA 2K19 on PC

-

If you want to download NBA 2K19 on your PC, you need to make sure that your PC meets the minimum or recommended system requirements for the game. Here are the system requirements for NBA 2K19 on PC:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MinimumRecommended
CPU: Intel Core i3-530 @ 2.93 GHz / AMD FX-4100 @ 3.60 GHz or betterCPU: Intel Core i5-4430 @ 3 GHz / AMD FX-8370 @ 3.4 GHz or better
RAM: 4 GBRAM: 8 GB
OS: Windows 7 64-bit, Windows 8.1 64-bit or Windows 10 64-bitOS: Windows 7 64-bit, Windows 8.1 64-bit or Windows 10 64-bit
VIDEO CARD: NVIDIA GeForce GT 450 1GB / AMD Radeon HD 7770 1GB or betterVIDEO CARD: NVIDIA GeForce GTX 770 2GB / AMD Radeon R9 270 2GB or better
SOUND CARD: DirectX 9.0x compatible Dual-Analog Gamepad: RecommendedSOUND CARD: DirectX 9.0c compatible sound card Dual-Analog Gamepad: Recommended
FREE DISK SPACE: 80 GBFREE DISK SPACE: 80 GB
Dedicated Video RAM: 1 GBDedicated Video RAM: 2 GB
-

Once you have checked your system requirements, you can proceed to download NBA 2K19 on your PC using one of these methods:

-

Using the official website of 2K Games

-

The official website of 2K Games is the easiest and safest way to download NBA 2K19 on your PC. Here are the steps you need to follow:

-
    -
  1. Go to the official website of 2K Games at https://www.2k.com/en-US/.
  2. -
  3. Click on the "Games" tab and select "NBA 2K19" from the list of games.
  4. -
  5. Click on the "Buy Now" button and choose your preferred edition of the game. You can choose between the Standard Edition, the 20th Anniversary Edition, or the Legend Edition.
  6. -
  7. Select your preferred platform and retailer. You can choose between Steam, Amazon, or other online stores.
  8. -
  9. Follow the instructions on the retailer's website to complete your purchase and download the game.
  10. -
  11. Once you have downloaded the game, launch it and enjoy!
  12. -
-

Using an emulator like BlueStacks

-

If you want to play NBA 2K19 on your PC but you don't want to buy it from the official website or other online stores, you can use an emulator like BlueStacks. An emulator is a software that allows you to run Android apps on your PC. BlueStacks is one of the most popular and reliable emulators for PC. Here are the steps you need to follow:

-
    -
  1. Go to the official website of BlueStacks at https://www.bluestacks.com/.
  2. -
  3. Click on the "Download BlueStacks" button and wait for the download to finish.
  4. -
  5. Run the installer and follow the instructions to install BlueStacks on your PC.
  6. -
  7. Launch BlueStacks and sign in with your Google account.
  8. -
  9. Go to the Google Play Store and search for "NBA 2K19".
  10. -
  11. Click on the "Install" button and wait for the installation to finish.
  12. -
  13. Once you have installed NBA 2K19, launch it and enjoy!
  14. -
-

The requirements and steps for downloading NBA 2K19 on Android or iOS

-

If you want to download NBA 2K19 on your Android or iOS device, you need to make sure that your device meets the minimum or recommended system requirements for the game. Here are the system requirements for NBA 2K19 on Android or iOS:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MinimumRecommended
CPU: Snapdragon 435 / A9 or equivalentCPU: Snapdragon 845 / A11 or equivalent
RAM: 2 GBRAM: 4 GB
OS: Android 4.3 / iOS 9.0 or higherOS: Android 8.0 / iOS 11.0 or higher
VIDEO CARD: Adreno 505 / PowerVR GT7600 or betterVIDEO CARD: Adreno 630 / PowerVR GT7600 or better
SOUND CARD: Any compatible sound cardSOUND CARD: Any compatible sound card
FREE DISK SPACE: 3 GBFREE DISK SPACE: 3 GB
Dedicated Video RAM: N/ADedicated Video RAM: N/A
-

Once you have checked your system requirements, you can proceed to download NBA 2K19 on your Android or iOS device using one of these methods:

-

Using the Google Play Store or the App Store

-

The Google Play Store or the App Store are the easiest and safest ways to download NBA 2K19 on your Android or iOS device. Here are the steps you need to follow:

-
    -
  1. Go to the Google Play Store or the App Store on your device.
  2. -
  3. Search for "NBA 2K19" and tap on the game icon.
  4. -
  5. Click on the "Install" or "Get" button and wait for the download to finish.
  6. -
  7. Once you have downloaded NBA 2K19, launch it and enjoy!
  8. -
-

Using a third-party source like Google Drive

-

If you want to download NBA 2K19 on your Android or iOS device but you don't want to use the Google Play Store or the App Store, you can use a third-party source like Google Drive. However, this method is not recommended as it may expose your device to security risks and malware. If you still want to try this method, here are the steps you need to follow:

-
    -
  1. Go to a trusted website that provides a link to download NBA 2K19 from Google Drive. For example, you can use this link: https://drive.google.com/file/d/1Zk8f9QsYy8ZxT9XlJwv3c8V7jL0z6X0w/view.
  2. -
  3. Click on the "Download" button and wait for the download to finish.
  4. -
  5. Go to your device settings and enable the option to install apps from unknown sources.
  6. -
  7. Locate the downloaded file on your device and tap on it to install it.
  8. -
  9. Once you have installed NBA 2K19, launch it and enjoy!
  10. -
-

How to optimize your NBA 2K19 experience?

-

NBA 2K19 is a great game, but it can be even better if you know how to optimize your experience. Here are some tips and tricks that can help you play NBA 2K19 like a pro, and make the most out of your game:

-

The tips and tricks for playing NBA 2K19 like a pro

-

NBA 2K19 is a game that requires skill, strategy, and practice. Here are some tips and tricks that can help you improve your performance and win more games:

- -

The best settings and customizations for NBA 2K19

-

NBA 2K19 is a game that allows you to customize many aspects of it. Here are some of the best settings and customizations that can enhance your game experience:

- -

The resources and communities for NBA 2K19 fans

-

NBA 2K19 is a game that has a large and active fan base. Here are some of the resources and communities that can help you connect with other NBA 2K19 fans, get the latest news and updates, and find more information and guides about the game:

- -

Conclusion

-

NBA 2K19 is a game that every basketball fan should play. It is a game that offers realistic graphics, exciting gameplay, and diverse modes. It is a game that allows you to create your own player, build your own team, and relive the history of the NBA. It is a game that lets you customize many aspects of it, and optimize your experience with some tips and tricks. It is a game that has a large and active fan base, and many resources and communities to help you.

-

If you want to download NBA 2K19 on your PC or mobile device, you can use one of the methods we have shown you in this article. You can use the official website of 2K Games, an emulator like BlueStacks, the Google Play Store or the App Store, or a third-party source like Google Drive. However, make sure that your device meets the system requirements for the game, and that you are downloading from a trusted source.

-

NBA 2K19 is a game that will keep you entertained for hours. It is a game that will challenge you, reward you, and inspire you. It is a game that will make you love basketball even more. So what are you waiting for? Download NBA 2K19 today and enjoy the best basketball game ever!

-

FAQs

-

Here are some of the frequently asked questions about NBA 2K19:

-
    -
  1. Q: How much does NBA 2K19 cost?
  2. -
  3. A: NBA 2K19 costs $59.99 for the Standard Edition, $99.99 for the 20th Anniversary Edition, and $129.99 for the Legend Edition. However, you may find discounts or offers from different retailers or platforms.
  4. -
  5. Q: How can I update NBA 2K19?
  6. -
  7. A: NBA 2K19 updates automatically if you have an internet connection. However, you can also check for updates manually in the game settings or on the platform you downloaded the game from.
  8. -
  9. Q: How can I play NBA 2K19 online?
  10. -
  11. A: NBA 2K19 requires an internet connection to play online. You also need to have a valid account on the platform you downloaded the game from, such as Steam, PlayStation Network, Xbox Live, Nintendo Switch Online, Google Play Games, or Game Center. You can then access various online modes and features in the game menu.
  12. -
  13. Q: How can I get more VC (Virtual Currency) in NBA 2K19?
  14. -
  15. A: VC is the in-game currency that you can use to buy items, upgrade your player, and more in NBA 2K19. You can earn VC by playing various modes and challenges in the game, or by watching ads or completing surveys in the game menu. You can also buy VC with real money on the platform you downloaded the game from.
  16. -
  17. Q: How can I contact the support team of NBA 2K19?
  18. -
  19. A: If you have any issues or questions about NBA 2K19, you can contact the support team of 2K Games at https://support.2k.com/hc/en-us/requests/new. You can also visit their help center at https://support.2k.com/hc/en-us/categories/360001624093-NBA-2K for more information and guides.
  20. -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/KMSAuto Net 2016 Download How to Use It to Activate Windows and Office.md b/spaces/congsaPfin/Manga-OCR/logs/KMSAuto Net 2016 Download How to Use It to Activate Windows and Office.md deleted file mode 100644 index 99e526d9b158d04e319a51d7ee3921019fd177d3..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/KMSAuto Net 2016 Download How to Use It to Activate Windows and Office.md +++ /dev/null @@ -1,136 +0,0 @@ - -

How to Download KMSAuto Office 2016 and Activate Your Microsoft Office for Free

-

If you are looking for a way to use Microsoft Office 2016 without paying for a product key, you may have heard of KMSAuto Office 2016. This is a tool that can activate your Office for free in a few simple steps. But what is KMSAuto Office 2016 and how does it work? Is it safe and legal to use? And what are the benefits and risks of using it? In this article, we will answer these questions and show you how to download KMSAuto Office 2016 from a trusted source and use it to activate your Microsoft Office.

-

What is KMSAuto Office 2016 and Why You Need It

-

KMSAuto Office 2016 is a tool that can activate Microsoft Office 2016 without a product key

-

KMSAuto Office 2016 is a software that can activate Microsoft Office 2016 by using a method called Key Management Service (KMS). This is a technology that allows large organizations to activate multiple computers with a single server. KMSAuto Office 2016 mimics this server and sends activation signals to your computer, making it think that it is connected to a genuine KMS server. This way, you can activate your Office without entering a product key.

-

download kmsauto office 2016


Download https://urlca.com/2uOgmk



-

KMSAuto Office 2016 can save you money and time by activating your Office for free

-

One of the main reasons why people use KMSAuto Office 2016 is that it can save them money and time. Buying a product key for Microsoft Office 2016 can be expensive, especially if you need it for multiple devices. Moreover, finding a valid product key online can be risky, as you may end up with a fake or used one that does not work. By using KMSAuto Office 2016, you can avoid these problems and activate your Office for free in minutes.

-

How to Download KMSAuto Office 2016 from a Trusted Source

-

You can download KMSAuto Office 2016 from the official website or from a reliable third-party site

-

The best way to download KMSAuto Office 2016 is from its official website. This is where you can find the latest version of the tool, as well as instructions on how to use it. However

However, if you cannot access the official website for some reason, you can also download KMSAuto Office 2016 from a reliable third-party site. This is a site that has been tested and verified by many users and has positive reviews and ratings. You should avoid downloading KMSAuto Office 2016 from unknown or suspicious sites, as they may contain viruses or malware that can harm your computer.

-

You need to disable your antivirus and firewall before downloading and running KMSAuto Office 2016

-

Before you download and run KMSAuto Office 2016, you need to disable your antivirus and firewall programs. This is because these programs may interfere with the functioning of KMSAuto Office 2016 and block its activation process. They may also detect KMSAuto Office 2016 as a virus or malware and delete it from your computer. To disable your antivirus and firewall, you can follow these steps:

- - - - - - - - - - - - - - - - - - - - - -
Antivirus/FirewallSteps to Disable
Windows Defender- Go to Settings > Update & Security > Windows Security > Virus & threat protection
-- Click on Manage settings under Virus & threat protection settings
-- Turn off Real-time protection and Cloud-delivered protection
-- Go to Settings > Update & Security > Windows Security > Firewall & network protection
-- Click on the network profile that is active and turn off Windows Defender Firewall
Norton- Right-click on the Norton icon in the system tray and select Disable Auto-Protect
-- Choose how long you want to disable it and click OK
-- Right-click on the Norton icon again and select Disable Smart Firewall
-- Choose how long you want to disable it and click OK
McAfee- Right-click on the McAfee icon in the system tray and select Change settings > Real-time Scanning
-- Turn off Real-time Scanning and click Yes to confirm
-- Right-click on the McAfee icon again and select Change settings > Firewall
-- Turn off Firewall and click Yes to confirm
Avast- Right-click on the Avast icon in the system tray and select Avast shields control
-- Choose how long you want to disable it and click Yes to confirm
-- Right-click on the Avast icon again and select Protection > Core Shields
-- Turn off all the shields and click Yes to confirm
-

How to Use KMSAuto Office 2016 to Activate Your Microsoft Office

-

You need to run KMSAuto Office 2016 as an administrator and choose the activation option

-

After you have downloaded KMSAuto Office 2016, you need to extract it from the zip file and run it as an administrator. To do this, you can right-click on the KMSAuto.exe file and select Run as administrator. You will see a window with several options, such as Activation, Information, Settings, Utilities, etc. You need to click on Activation and then choose Office activation.

-

You need to select your Office version and click on the activate button

-

Next, you need to select your Office version from the drop-down menu. You can choose between Office 2010, 2013, or 2016. If you are not sure which version you have, you can check it by opening any Office application and going to File > Account > About. After selecting your Office version, you need to click on the Activate button at the bottom of the window. You will see a progress bar and some messages indicating the activation process. Wait for a few seconds until you see a message saying "Activation successful".

-

How to Check If Your Microsoft Office is Activated Successfully

-

You can open any Office application and go to the account settings to see the activation status

-

One of the easiest ways to check if your Microsoft Office is activated successfully is by opening any Office application, such as Word, Excel, PowerPoint, etc. Then, go to File > Account and look at the Product Information section. You should see a message saying "Product Activated" under your Office edition. You should also see a green check mark next to Activation Required.

-

How to download kmsauto net 2016 for office activation
-Download kmsauto office 2016 activator free full version
-Kmsauto net 2016 v1.5.3 portable download for office 2016
-Download kmsauto office 2016 windows 10 activator
-Kmsauto net 2016 free download latest version for office
-Download kmsauto office 2016 professional plus activator
-Kmsauto net 2016 download for office and windows activation
-Download kmsauto office 2016 crack with serial key
-Kmsauto net 2016 activator download for office and windows 10
-Download kmsauto office 2016 offline installer
-Kmsauto net 2016 download link for office activation
-Download kmsauto office 2016 rar file
-Kmsauto net 2016 free download for windows and office activation
-Download kmsauto office 2016 zip file
-Kmsauto net 2016 activator free download for office and windows
-Download kmsauto office 2016 setup file
-Kmsauto net 2016 download for windows and office activation guide
-Download kmsauto office 2016 exe file
-Kmsauto net 2016 free download for office activation without virus
-Download kmsauto office 2016 toolkit and ez activator
-Kmsauto net 2016 download for office activation tutorial
-Download kmsauto office 2016 software
-Kmsauto net 2016 free download for windows and office activation latest update
-Download kmsauto office 2016 patch file
-Kmsauto net 2016 activator download link for office and windows
-Download kmsauto office 2016 license key
-Kmsauto net 2016 free download for office activation with crack
-Download kmsauto office 2016 keygen file
-Kmsauto net 2016 download for windows and office activation step by step
-Download kmsauto office 2016 product key
-Kmsauto net 2016 free download for windows and office activation no survey
-Download kmsauto office 2016 registration code
-Kmsauto net 2016 activator free download for windows and office latest version
-Download kmsauto office 2016 serial number
-Kmsauto net 2016 free download for windows and office activation safe and secure
-Download kmsauto office 2016 activation code
-Kmsauto net 2016 activator download for windows and office full version
-Download kmsauto office 2016 torrent file
-Kmsauto net 2016 free download for windows and office activation fast and easy
-Download kmsauto office 2016 direct link

-

You can also use the command prompt or a script to verify the activation

-

Another way to check if your Microsoft Office is activated successfully is by using the command prompt or a script. To use the command prompt, you can follow these steps:

- -

To use a script, you can follow these steps:

- -

What are the Benefits of Using KMSAuto Office 2016

-

KMSAuto Office 2016 can activate your Office for up to 180 days and renew it automatically

-

One of the benefits of using KMSAuto Office 2016 is that it can activate your Office for up to 180 days and renew it automatically. This means that you don't have to worry about your Office expiring or deactivating after a certain period of time. KMSAuto Office 2016 will keep your Office activated as long as you have it on your computer. You can also check the remaining days of your activation by using the command prompt or the script mentioned above.

-

KMSAuto Office 2016 can also activate other Microsoft products such as Windows, Visio, and Project

-

Another benefit of using KMSAuto Office 2016 is that it can also activate other Microsoft products such as Windows, Visio, and Project. This means that you can use KMSAuto Office 2016 to activate not only your Office but also your operating system and other applications. You can choose which products you want to activate by using the Utilities option in KMSAuto Office 2016. You can also customize the settings and preferences of KMSAuto Office 2016 by using the Settings option.

-

What are the Risks of Using KMSAuto Office 2016

-

KMSAuto Office 2016 is not an official Microsoft product and may be detected as a virus or malware by some antivirus programs

-

One of the risks of using KMSAuto Office 2016 is that it is not an official Microsoft product and may be detected as a virus or malware by some antivirus programs. This means that you may encounter some problems when downloading, running, or updating KMSAuto Office 2016. Your antivirus or firewall may block or delete KMSAuto Office 2016 from your computer, preventing you from activating your Office. You may also receive some warnings or alerts from your antivirus or firewall, telling you that KMSAuto Office 2016 is unsafe or harmful. To avoid these problems, you need to disable your antivirus and firewall before using KMSAuto Office 2016, as explained above.

-

KMSAuto Office 2016 may violate the terms and conditions of Microsoft and may result in legal consequences or loss of data

-

Another risk of using KMSAuto Office 2016 is that it may violate the terms and conditions of Microsoft and may result in legal consequences or loss of data. This means that you may be breaking the law or infringing the intellectual property rights of Microsoft by using KMSAuto Office 2016. You may also lose access to some features or services of Microsoft, such as updates, support, or cloud storage. You may also face some penalties or fines from Microsoft or other authorities if they discover that you are using KMSAuto Office 2016. To avoid these risks, you should use KMSAuto Office 2016 at your own discretion and responsibility.

-

Conclusion

-

KMSAuto Office 2016 is a tool that can activate your Microsoft Office for free in a few simple steps. It works by using a method called Key Management Service (KMS) that mimics a genuine server and sends activation signals to your computer. It can save you money and time by activating your Office without a product key. It can also activate other Microsoft products such as Windows, Visio, and Project. However, it is not an official Microsoft product and may be detected as a virus or malware by some antivirus programs. It may also violate the terms and conditions of Microsoft and may result in legal consequences or loss of data. Therefore, you should use KMSAuto Office 2016 at Therefore, you should use KMSAuto Office 2016 at your own risk and discretion. We hope this article has helped you understand how to download KMSAuto Office 2016 and activate your Microsoft Office for free. If you have any questions or comments, please feel free to leave them below.

FAQs

-

Is KMSAuto Office 2016 safe to use?

-

KMSAuto Office 2016 is safe to use as long as you download it from a trusted source and disable your antivirus and firewall before using it. However, it is not an official Microsoft product and may be detected as a virus or malware by some antivirus programs. It may also violate the terms and conditions of Microsoft and may result in legal consequences or loss of data. Therefore, you should use KMSAuto Office 2016 at your own risk and discretion.

-

How long does KMSAuto Office 2016 activate my Office for?

-

KMSAuto Office 2016 can activate your Office for up to 180 days and renew it automatically. This means that you don't have to worry about your Office expiring or deactivating after a certain period of time. KMSAuto Office 2016 will keep your Office activated as long as you have it on your computer. You can also check the remaining days of your activation by using the command prompt or the script mentioned above.

-

Can I update my Office after using KMSAuto Office 2016?

-

Yes, you can update your Office after using KMSAuto Office 2016. However, you may need to re-activate your Office after updating it, as some updates may reset the activation status. To do this, you can simply run KMSAuto Office 2016 again and choose the activation option.

-

Can I use KMSAuto Office 2016 on multiple computers?

-

Yes, you can use KMSAuto Office 2016 on multiple computers. However, you need to download and run KMSAuto Office 2016 on each computer separately. You also need to disable the antivirus and firewall on each computer before using KMSAuto Office 2016.

-

Can I uninstall KMSAuto Office 2016 after activating my Office?

-

Yes, you can uninstall KMSAuto Office 2016 after activating your Office. However, you may lose the activation if you uninstall KMSAuto Office 2016 before the expiration date of your activation. To avoid this, you can keep KMSAuto Office 2016 on your computer until the activation expires or renew it manually by running KMSAuto Office 2016 again.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Tubidy Blue The Best Way to Download Lagu MP3 and MP4 Videos.md b/spaces/congsaPfin/Manga-OCR/logs/Tubidy Blue The Best Way to Download Lagu MP3 and MP4 Videos.md deleted file mode 100644 index 7736ba3ccf998786a984fa0513f05806e2aa4ff5..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Tubidy Blue The Best Way to Download Lagu MP3 and MP4 Videos.md +++ /dev/null @@ -1,130 +0,0 @@ -
-

Tubidy Blue: How to Download MP3 Music and Videos for Free

-

If you are looking for a free and easy way to download MP3 music and videos online, you may have heard of Tubidy Blue. But what is Tubidy Blue and how does it work? In this article, we will explain everything you need to know about Tubidy Blue, including its features, benefits, drawbacks, and how to optimize your downloads for SEO. By the end of this article, you will be able to use Tubidy Blue like a pro and enjoy your favorite music and videos anytime, anywhere.

-

tubidy blue mp3 download lagu


DOWNLOAD –––––>>> https://urlca.com/2uOa1J



-

What is Tubidy Blue?

-

A brief introduction to Tubidy Blue and its features

-

Tubidy Blue is a video search engine that allows you to download MP3 music and videos for free. It is a popular website that has millions of users from all over the world. You can use Tubidy Blue to search for any type of music or video you want, from pop songs and rap tracks to movie trailers and funny clips. You can also browse through different categories and genres, such as music, sports, entertainment, news, etc.

-

One of the main features of Tubidy Blue is that it lets you download MP3 music and videos in various formats, such as 3GP, MP4, MP3, AAC, OGG, FLAC, etc. You can also choose the quality of your downloads, from low to high. This way, you can save space on your device or enjoy better sound and video quality. Another feature of Tubidy Blue is that it supports multiple languages, such as English, Spanish, French, German, Turkish, etc. You can change the language of the website according to your preference.

-

How to use Tubidy Blue to search and download MP3 music and videos

-

Using Tubidy Blue is very simple and straightforward. Here are the steps you need to follow:

-

tubidy blue mp3 download lagu gratis
-tubidy blue mp3 download lagu terbaru
-tubidy blue mp3 download lagu indonesia
-tubidy blue mp3 download lagu barat
-tubidy blue mp3 download lagu dangdut
-tubidy blue mp3 download lagu pop
-tubidy blue mp3 download lagu kpop
-tubidy blue mp3 download lagu malaysia
-tubidy blue mp3 download lagu india
-tubidy blue mp3 download lagu tiktok
-tubidy blue mp3 download lagu dj
-tubidy blue mp3 download lagu koplo
-tubidy blue mp3 download lagu reggae
-tubidy blue mp3 download lagu rock
-tubidy blue mp3 download lagu metal
-tubidy blue mp3 download lagu jazz
-tubidy blue mp3 download lagu rap
-tubidy blue mp3 download lagu hip hop
-tubidy blue mp3 download lagu r&b
-tubidy blue mp3 download lagu edm
-tubidy blue mp3 download lagu remix
-tubidy blue mp3 download lagu cover
-tubidy blue mp3 download lagu acoustic
-tubidy blue mp3 download lagu ost
-tubidy blue mp3 download lagu anak
-tubidy blue mp3 download lagu religi
-tubidy blue mp3 download lagu islami
-tubidy blue mp3 download lagu nasyid
-tubidy blue mp3 download lagu sholawat
-tubidy blue mp3 download lagu qasidah
-tubidy blue mp3 download lagu tarling
-tubidy blue mp3 download lagu campursari
-tubidy blue mp3 download lagu banyuwangi
-tubidy blue mp3 download lagu sunda
-tubidy blue mp3 download lagu jawa
-tubidy blue mp3 download lagu batak
-tubidy blue mp3 download lagu minang
-tubidy blue mp3 download lagu melayu
-tubidy blue mp3 download lagu bugis
-tubidy blue mp3 download lagu makassar
-tubidy blue mp3 download lagu banjar
-tubidy blue mp3 download lagu aceh
-tubidy blue mp3 download lagu bali
-tubidy blue mp3 download lagu papua
-tubidy blue mp3 download lagu timor leste
-tubidy.blue free music and video downloader online without app[^1^]
-how to use www.tubidy.blue to convert youtube videos to mp4 and save them on your device[^2^]
-www.tubidy.blue - the best site to search and play millions of free songs and videos online[^2^]
-www.tubidymobi.com - the alternative site to www.tubidy.blue for downloading free music and videos[^2^]

-
    -
  1. Go to Tubidy.blue, the official website of Tubidy Blue.
  2. -
  3. Type in your keyword or phrase in the search box at the top of the page. For example, if you want to download a song by Ed Sheeran, type in "Ed Sheeran". You can also use advanced search options, such as filters, sorting, and date range.
  4. -
  5. Press enter or click on the magnifying glass icon to start the search. You will see a list of results that match your query. You can preview each result by clicking on the play button or the thumbnail image.
  6. -
  7. Once you find the result you want, click on the download button next to it. You will see a pop-up window with different options for downloading. You can choose the format and quality of your download. For example, if you want to download an MP3 file with high quality, click on "MP3 - High Quality".
  8. -
  9. Wait for a few seconds until your download starts automatically. You can also copy the download link and paste it into another browser or downloader app.
  10. -
  11. Enjoy your downloaded MP3 music or video file on your device or online.
  12. -
-

Why choose Tubidy Blue?

-

The benefits of Tubidy Blue over other MP3 download sites

-

Tubidy Blue is not the only MP3 download site on the internet, but it has some advantages that make it stand out from the rest. Here are some of the benefits of Tubidy Blue:

- -

The drawbacks and limitations of Tubidy Blue

-

However, Tubidy Blue is not perfect and has some drawbacks and limitations that you should be aware of. Here are some of the disadvantages of Tubidy Blue:

-

How to optimize your Tubidy Blue downloads for SEO

-

What is SEO and why is it important for your content?

-

SEO stands for search engine optimization, which is the process of improving the visibility and ranking of your content on search engines, such as Google, Bing, Yahoo, etc. SEO is important for your content because it helps you attract more organic traffic, leads, and conversions from your target audience. SEO also helps you build your brand awareness, authority, and trustworthiness in your niche or industry.

-

How to choose the right keywords for your Tubidy Blue downloads

-

Keywords are the words or phrases that your audience uses to search for your content on search engines. Choosing the right keywords for your Tubidy Blue downloads is crucial for SEO because it helps you match your content with the intent and needs of your audience. Here are some tips on how to choose the right keywords for your Tubidy Blue downloads:

- -

How to use headlines, subheadings, meta tags, and image alt text for SEO

-

Headlines, subheadings, meta tags, and image alt text are some of the elements that help you optimize your Tubidy Blue downloads for SEO. They help you structure your content, communicate your message, and attract the attention of your audience and search engines. Here are some tips on how to use them for SEO:

-

How to avoid plagiarism and duplicate content issues with Tubidy Blue downloads

-

Plagiarism and duplicate content are some of the problems that you may face when using Tubidy Blue downloads for your own content creation or distribution. Plagiarism is the act of copying or using someone else's work without giving proper credit or permission. Duplicate content is the presence of identical or similar content on multiple web pages or platforms. Both plagiarism and duplicate content can harm your SEO, reputation, and credibility. Here are some tips on how to avoid them with Tubidy Blue downloads:

- -

Conclusion

-

A summary of the main points and a call to action

-

Tubidy Blue is a video search engine that allows you to download MP3 music and videos for free. It has many features, benefits, drawbacks, and limitations that you should know before using it. It also requires you to optimize your downloads for SEO, which involves choosing the right keywords, using headlines, subheadings, meta tags, and image alt text, and avoiding plagiarism and duplicate content issues.

-

If you want to learn more about Tubidy Blue and how to use it effectively, you can visit their official website at Tubidy.blue. You can also check out some of the FAQs below for more information. We hope you enjoyed this article and found it useful. Thank you for reading!

-

FAQs

-

What is the difference between Tubidy and Tubidy Blue?

-

Tubidy is the original video search engine that was launched in 2009. Tubidy Blue is a newer version of Tubidy that was launched in 2020. Tubidy Blue has a different design, interface, and domain name than Tubidy. However, both websites have the same functionality and features.

-

Is Tubidy Blue legal and safe to use?

-

Tubidy Blue is not legal and safe to use in some countries or regions where downloading MP3 music and videos without permission is prohibited or restricted. You may face legal consequences or penalties if you use Tubidy Blue in such countries or regions. You should always check the laws and regulations of your country or region before using Tubidy Blue.

-

How can I convert Tubidy Blue downloads to other formats?

-

Tubidy Blue allows you to download MP3 music and videos in various formats, such as 3GP, MP4, MP3, AAC, OGG, FLAC, etc. However, if you want to convert Tubidy Blue downloads to other formats that are not supported by Tubidy Blue, you can use online converters or software that can convert files from one format to another. For example, you can use Online-Convert.com, Zamzar.com, or Any Video Converter to convert Tubidy Blue downloads to other formats.

-

How can I share Tubidy Blue downloads with others?

-

Tubidy Blue allows you to share your downloads with others by copying and pasting the download link into another browser or downloader app. However, if you want to share Tubidy Blue downloads with others more easily and conveniently, you can use online platforms or services that can store and share files online. For example, you can use Google Drive, Dropbox, or OneDrive to share Tubidy Blue downloads with others.

-

What are some alternatives to Tubidy Blue?

-

Tubidy Blue is not the only option for downloading MP3 music and videos online. There are many other websites, apps, or software that can offer similar or better services than Tubidy Blue. Here are some of the alternatives to Tubidy Blue:

-

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Audials One Platinum 2019.0.11400.0 Crack [Latest] - Download and Install Guide.md b/spaces/contluForse/HuggingGPT/assets/Audials One Platinum 2019.0.11400.0 Crack [Latest] - Download and Install Guide.md deleted file mode 100644 index 4e3564570ee9b984459fa4d70fbbfb33e3fe6901..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Audials One Platinum 2019.0.11400.0 Crack [Latest] - Download and Install Guide.md +++ /dev/null @@ -1,6 +0,0 @@ -

Audials One Platinum 2019.0.11400.0 Crack [Latest]


Download Zip ✒ ✒ ✒ https://ssurll.com/2uzyln



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/parallel/data_container.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/parallel/data_container.py deleted file mode 100644 index cedb0d32a51a1f575a622b38de2cee3ab4757821..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/parallel/data_container.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import functools - -import torch - - -def assert_tensor_type(func): - - @functools.wraps(func) - def wrapper(*args, **kwargs): - if not isinstance(args[0].data, torch.Tensor): - raise AttributeError( - f'{args[0].__class__.__name__} has no attribute ' - f'{func.__name__} for type {args[0].datatype}') - return func(*args, **kwargs) - - return wrapper - - -class DataContainer: - """A container for any type of objects. - - Typically tensors will be stacked in the collate function and sliced along - some dimension in the scatter function. This behavior has some limitations. - 1. All tensors have to be the same size. - 2. Types are limited (numpy array or Tensor). - - We design `DataContainer` and `MMDataParallel` to overcome these - limitations. The behavior can be either of the following. - - - copy to GPU, pad all tensors to the same size and stack them - - copy to GPU without stacking - - leave the objects as is and pass it to the model - - pad_dims specifies the number of last few dimensions to do padding - """ - - def __init__(self, - data, - stack=False, - padding_value=0, - cpu_only=False, - pad_dims=2): - self._data = data - self._cpu_only = cpu_only - self._stack = stack - self._padding_value = padding_value - assert pad_dims in [None, 1, 2, 3] - self._pad_dims = pad_dims - - def __repr__(self): - return f'{self.__class__.__name__}({repr(self.data)})' - - def __len__(self): - return len(self._data) - - @property - def data(self): - return self._data - - @property - def datatype(self): - if isinstance(self.data, torch.Tensor): - return self.data.type() - else: - return type(self.data) - - @property - def cpu_only(self): - return self._cpu_only - - @property - def stack(self): - return self._stack - - @property - def padding_value(self): - return self._padding_value - - @property - def pad_dims(self): - return self._pad_dims - - @assert_tensor_type - def size(self, *args, **kwargs): - return self.data.size(*args, **kwargs) - - @assert_tensor_type - def dim(self): - return self.data.dim() diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmseg/datasets/voc.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmseg/datasets/voc.py deleted file mode 100644 index a8855203b14ee0dc4da9099a2945d4aedcffbcd6..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmseg/datasets/voc.py +++ /dev/null @@ -1,29 +0,0 @@ -import os.path as osp - -from .builder import DATASETS -from .custom import CustomDataset - - -@DATASETS.register_module() -class PascalVOCDataset(CustomDataset): - """Pascal VOC dataset. - - Args: - split (str): Split txt file for Pascal VOC. - """ - - CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', - 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', - 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', - 'train', 'tvmonitor') - - PALETTE = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], - [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], - [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], - [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], - [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128]] - - def __init__(self, split, **kwargs): - super(PascalVOCDataset, self).__init__( - img_suffix='.jpg', seg_map_suffix='.png', split=split, **kwargs) - assert osp.exists(self.img_dir) and self.split is not None diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/data/build.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/data/build.py deleted file mode 100644 index d03137a9aabfc4a056dd671d4c3d0ba6f349fe03..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/data/build.py +++ /dev/null @@ -1,556 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import itertools -import logging -import numpy as np -import operator -import pickle -from typing import Any, Callable, Dict, List, Optional, Union -import torch -import torch.utils.data as torchdata -from tabulate import tabulate -from termcolor import colored - -from annotator.oneformer.detectron2.config import configurable -from annotator.oneformer.detectron2.structures import BoxMode -from annotator.oneformer.detectron2.utils.comm import get_world_size -from annotator.oneformer.detectron2.utils.env import seed_all_rng -from annotator.oneformer.detectron2.utils.file_io import PathManager -from annotator.oneformer.detectron2.utils.logger import _log_api_usage, log_first_n - -from .catalog import DatasetCatalog, MetadataCatalog -from .common import AspectRatioGroupedDataset, DatasetFromList, MapDataset, ToIterableDataset -from .dataset_mapper import DatasetMapper -from .detection_utils import check_metadata_consistency -from .samplers import ( - InferenceSampler, - RandomSubsetTrainingSampler, - RepeatFactorTrainingSampler, - TrainingSampler, -) - -""" -This file contains the default logic to build a dataloader for training or testing. -""" - -__all__ = [ - "build_batch_data_loader", - "build_detection_train_loader", - "build_detection_test_loader", - "get_detection_dataset_dicts", - "load_proposals_into_dataset", - "print_instances_class_histogram", -] - - -def filter_images_with_only_crowd_annotations(dataset_dicts): - """ - Filter out images with none annotations or only crowd annotations - (i.e., images without non-crowd annotations). - A common training-time preprocessing on COCO dataset. - - Args: - dataset_dicts (list[dict]): annotations in Detectron2 Dataset format. - - Returns: - list[dict]: the same format, but filtered. - """ - num_before = len(dataset_dicts) - - def valid(anns): - for ann in anns: - if ann.get("iscrowd", 0) == 0: - return True - return False - - dataset_dicts = [x for x in dataset_dicts if valid(x["annotations"])] - num_after = len(dataset_dicts) - logger = logging.getLogger(__name__) - logger.info( - "Removed {} images with no usable annotations. {} images left.".format( - num_before - num_after, num_after - ) - ) - return dataset_dicts - - -def filter_images_with_few_keypoints(dataset_dicts, min_keypoints_per_image): - """ - Filter out images with too few number of keypoints. - - Args: - dataset_dicts (list[dict]): annotations in Detectron2 Dataset format. - - Returns: - list[dict]: the same format as dataset_dicts, but filtered. - """ - num_before = len(dataset_dicts) - - def visible_keypoints_in_image(dic): - # Each keypoints field has the format [x1, y1, v1, ...], where v is visibility - annotations = dic["annotations"] - return sum( - (np.array(ann["keypoints"][2::3]) > 0).sum() - for ann in annotations - if "keypoints" in ann - ) - - dataset_dicts = [ - x for x in dataset_dicts if visible_keypoints_in_image(x) >= min_keypoints_per_image - ] - num_after = len(dataset_dicts) - logger = logging.getLogger(__name__) - logger.info( - "Removed {} images with fewer than {} keypoints.".format( - num_before - num_after, min_keypoints_per_image - ) - ) - return dataset_dicts - - -def load_proposals_into_dataset(dataset_dicts, proposal_file): - """ - Load precomputed object proposals into the dataset. - - The proposal file should be a pickled dict with the following keys: - - - "ids": list[int] or list[str], the image ids - - "boxes": list[np.ndarray], each is an Nx4 array of boxes corresponding to the image id - - "objectness_logits": list[np.ndarray], each is an N sized array of objectness scores - corresponding to the boxes. - - "bbox_mode": the BoxMode of the boxes array. Defaults to ``BoxMode.XYXY_ABS``. - - Args: - dataset_dicts (list[dict]): annotations in Detectron2 Dataset format. - proposal_file (str): file path of pre-computed proposals, in pkl format. - - Returns: - list[dict]: the same format as dataset_dicts, but added proposal field. - """ - logger = logging.getLogger(__name__) - logger.info("Loading proposals from: {}".format(proposal_file)) - - with PathManager.open(proposal_file, "rb") as f: - proposals = pickle.load(f, encoding="latin1") - - # Rename the key names in D1 proposal files - rename_keys = {"indexes": "ids", "scores": "objectness_logits"} - for key in rename_keys: - if key in proposals: - proposals[rename_keys[key]] = proposals.pop(key) - - # Fetch the indexes of all proposals that are in the dataset - # Convert image_id to str since they could be int. - img_ids = set({str(record["image_id"]) for record in dataset_dicts}) - id_to_index = {str(id): i for i, id in enumerate(proposals["ids"]) if str(id) in img_ids} - - # Assuming default bbox_mode of precomputed proposals are 'XYXY_ABS' - bbox_mode = BoxMode(proposals["bbox_mode"]) if "bbox_mode" in proposals else BoxMode.XYXY_ABS - - for record in dataset_dicts: - # Get the index of the proposal - i = id_to_index[str(record["image_id"])] - - boxes = proposals["boxes"][i] - objectness_logits = proposals["objectness_logits"][i] - # Sort the proposals in descending order of the scores - inds = objectness_logits.argsort()[::-1] - record["proposal_boxes"] = boxes[inds] - record["proposal_objectness_logits"] = objectness_logits[inds] - record["proposal_bbox_mode"] = bbox_mode - - return dataset_dicts - - -def print_instances_class_histogram(dataset_dicts, class_names): - """ - Args: - dataset_dicts (list[dict]): list of dataset dicts. - class_names (list[str]): list of class names (zero-indexed). - """ - num_classes = len(class_names) - hist_bins = np.arange(num_classes + 1) - histogram = np.zeros((num_classes,), dtype=np.int) - for entry in dataset_dicts: - annos = entry["annotations"] - classes = np.asarray( - [x["category_id"] for x in annos if not x.get("iscrowd", 0)], dtype=np.int - ) - if len(classes): - assert classes.min() >= 0, f"Got an invalid category_id={classes.min()}" - assert ( - classes.max() < num_classes - ), f"Got an invalid category_id={classes.max()} for a dataset of {num_classes} classes" - histogram += np.histogram(classes, bins=hist_bins)[0] - - N_COLS = min(6, len(class_names) * 2) - - def short_name(x): - # make long class names shorter. useful for lvis - if len(x) > 13: - return x[:11] + ".." - return x - - data = list( - itertools.chain(*[[short_name(class_names[i]), int(v)] for i, v in enumerate(histogram)]) - ) - total_num_instances = sum(data[1::2]) - data.extend([None] * (N_COLS - (len(data) % N_COLS))) - if num_classes > 1: - data.extend(["total", total_num_instances]) - data = itertools.zip_longest(*[data[i::N_COLS] for i in range(N_COLS)]) - table = tabulate( - data, - headers=["category", "#instances"] * (N_COLS // 2), - tablefmt="pipe", - numalign="left", - stralign="center", - ) - log_first_n( - logging.INFO, - "Distribution of instances among all {} categories:\n".format(num_classes) - + colored(table, "cyan"), - key="message", - ) - - -def get_detection_dataset_dicts( - names, - filter_empty=True, - min_keypoints=0, - proposal_files=None, - check_consistency=True, -): - """ - Load and prepare dataset dicts for instance detection/segmentation and semantic segmentation. - - Args: - names (str or list[str]): a dataset name or a list of dataset names - filter_empty (bool): whether to filter out images without instance annotations - min_keypoints (int): filter out images with fewer keypoints than - `min_keypoints`. Set to 0 to do nothing. - proposal_files (list[str]): if given, a list of object proposal files - that match each dataset in `names`. - check_consistency (bool): whether to check if datasets have consistent metadata. - - Returns: - list[dict]: a list of dicts following the standard dataset dict format. - """ - if isinstance(names, str): - names = [names] - assert len(names), names - dataset_dicts = [DatasetCatalog.get(dataset_name) for dataset_name in names] - - if isinstance(dataset_dicts[0], torchdata.Dataset): - if len(dataset_dicts) > 1: - # ConcatDataset does not work for iterable style dataset. - # We could support concat for iterable as well, but it's often - # not a good idea to concat iterables anyway. - return torchdata.ConcatDataset(dataset_dicts) - return dataset_dicts[0] - - for dataset_name, dicts in zip(names, dataset_dicts): - assert len(dicts), "Dataset '{}' is empty!".format(dataset_name) - - if proposal_files is not None: - assert len(names) == len(proposal_files) - # load precomputed proposals from proposal files - dataset_dicts = [ - load_proposals_into_dataset(dataset_i_dicts, proposal_file) - for dataset_i_dicts, proposal_file in zip(dataset_dicts, proposal_files) - ] - - dataset_dicts = list(itertools.chain.from_iterable(dataset_dicts)) - - has_instances = "annotations" in dataset_dicts[0] - if filter_empty and has_instances: - dataset_dicts = filter_images_with_only_crowd_annotations(dataset_dicts) - if min_keypoints > 0 and has_instances: - dataset_dicts = filter_images_with_few_keypoints(dataset_dicts, min_keypoints) - - if check_consistency and has_instances: - try: - class_names = MetadataCatalog.get(names[0]).thing_classes - check_metadata_consistency("thing_classes", names) - print_instances_class_histogram(dataset_dicts, class_names) - except AttributeError: # class names are not available for this dataset - pass - - assert len(dataset_dicts), "No valid data found in {}.".format(",".join(names)) - return dataset_dicts - - -def build_batch_data_loader( - dataset, - sampler, - total_batch_size, - *, - aspect_ratio_grouping=False, - num_workers=0, - collate_fn=None, -): - """ - Build a batched dataloader. The main differences from `torch.utils.data.DataLoader` are: - 1. support aspect ratio grouping options - 2. use no "batch collation", because this is common for detection training - - Args: - dataset (torch.utils.data.Dataset): a pytorch map-style or iterable dataset. - sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces indices. - Must be provided iff. ``dataset`` is a map-style dataset. - total_batch_size, aspect_ratio_grouping, num_workers, collate_fn: see - :func:`build_detection_train_loader`. - - Returns: - iterable[list]. Length of each list is the batch size of the current - GPU. Each element in the list comes from the dataset. - """ - world_size = get_world_size() - assert ( - total_batch_size > 0 and total_batch_size % world_size == 0 - ), "Total batch size ({}) must be divisible by the number of gpus ({}).".format( - total_batch_size, world_size - ) - batch_size = total_batch_size // world_size - - if isinstance(dataset, torchdata.IterableDataset): - assert sampler is None, "sampler must be None if dataset is IterableDataset" - else: - dataset = ToIterableDataset(dataset, sampler) - - if aspect_ratio_grouping: - data_loader = torchdata.DataLoader( - dataset, - num_workers=num_workers, - collate_fn=operator.itemgetter(0), # don't batch, but yield individual elements - worker_init_fn=worker_init_reset_seed, - ) # yield individual mapped dict - data_loader = AspectRatioGroupedDataset(data_loader, batch_size) - if collate_fn is None: - return data_loader - return MapDataset(data_loader, collate_fn) - else: - return torchdata.DataLoader( - dataset, - batch_size=batch_size, - drop_last=True, - num_workers=num_workers, - collate_fn=trivial_batch_collator if collate_fn is None else collate_fn, - worker_init_fn=worker_init_reset_seed, - ) - - -def _train_loader_from_config(cfg, mapper=None, *, dataset=None, sampler=None): - if dataset is None: - dataset = get_detection_dataset_dicts( - cfg.DATASETS.TRAIN, - filter_empty=cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS, - min_keypoints=cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE - if cfg.MODEL.KEYPOINT_ON - else 0, - proposal_files=cfg.DATASETS.PROPOSAL_FILES_TRAIN if cfg.MODEL.LOAD_PROPOSALS else None, - ) - _log_api_usage("dataset." + cfg.DATASETS.TRAIN[0]) - - if mapper is None: - mapper = DatasetMapper(cfg, True) - - if sampler is None: - sampler_name = cfg.DATALOADER.SAMPLER_TRAIN - logger = logging.getLogger(__name__) - if isinstance(dataset, torchdata.IterableDataset): - logger.info("Not using any sampler since the dataset is IterableDataset.") - sampler = None - else: - logger.info("Using training sampler {}".format(sampler_name)) - if sampler_name == "TrainingSampler": - sampler = TrainingSampler(len(dataset)) - elif sampler_name == "RepeatFactorTrainingSampler": - repeat_factors = RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( - dataset, cfg.DATALOADER.REPEAT_THRESHOLD - ) - sampler = RepeatFactorTrainingSampler(repeat_factors) - elif sampler_name == "RandomSubsetTrainingSampler": - sampler = RandomSubsetTrainingSampler( - len(dataset), cfg.DATALOADER.RANDOM_SUBSET_RATIO - ) - else: - raise ValueError("Unknown training sampler: {}".format(sampler_name)) - - return { - "dataset": dataset, - "sampler": sampler, - "mapper": mapper, - "total_batch_size": cfg.SOLVER.IMS_PER_BATCH, - "aspect_ratio_grouping": cfg.DATALOADER.ASPECT_RATIO_GROUPING, - "num_workers": cfg.DATALOADER.NUM_WORKERS, - } - - -@configurable(from_config=_train_loader_from_config) -def build_detection_train_loader( - dataset, - *, - mapper, - sampler=None, - total_batch_size, - aspect_ratio_grouping=True, - num_workers=0, - collate_fn=None, -): - """ - Build a dataloader for object detection with some default features. - - Args: - dataset (list or torch.utils.data.Dataset): a list of dataset dicts, - or a pytorch dataset (either map-style or iterable). It can be obtained - by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`. - mapper (callable): a callable which takes a sample (dict) from dataset and - returns the format to be consumed by the model. - When using cfg, the default choice is ``DatasetMapper(cfg, is_train=True)``. - sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces - indices to be applied on ``dataset``. - If ``dataset`` is map-style, the default sampler is a :class:`TrainingSampler`, - which coordinates an infinite random shuffle sequence across all workers. - Sampler must be None if ``dataset`` is iterable. - total_batch_size (int): total batch size across all workers. - aspect_ratio_grouping (bool): whether to group images with similar - aspect ratio for efficiency. When enabled, it requires each - element in dataset be a dict with keys "width" and "height". - num_workers (int): number of parallel data loading workers - collate_fn: a function that determines how to do batching, same as the argument of - `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of - data. No collation is OK for small batch size and simple data structures. - If your batch size is large and each sample contains too many small tensors, - it's more efficient to collate them in data loader. - - Returns: - torch.utils.data.DataLoader: - a dataloader. Each output from it is a ``list[mapped_element]`` of length - ``total_batch_size / num_workers``, where ``mapped_element`` is produced - by the ``mapper``. - """ - if isinstance(dataset, list): - dataset = DatasetFromList(dataset, copy=False) - if mapper is not None: - dataset = MapDataset(dataset, mapper) - - if isinstance(dataset, torchdata.IterableDataset): - assert sampler is None, "sampler must be None if dataset is IterableDataset" - else: - if sampler is None: - sampler = TrainingSampler(len(dataset)) - assert isinstance(sampler, torchdata.Sampler), f"Expect a Sampler but got {type(sampler)}" - return build_batch_data_loader( - dataset, - sampler, - total_batch_size, - aspect_ratio_grouping=aspect_ratio_grouping, - num_workers=num_workers, - collate_fn=collate_fn, - ) - - -def _test_loader_from_config(cfg, dataset_name, mapper=None): - """ - Uses the given `dataset_name` argument (instead of the names in cfg), because the - standard practice is to evaluate each test set individually (not combining them). - """ - if isinstance(dataset_name, str): - dataset_name = [dataset_name] - - dataset = get_detection_dataset_dicts( - dataset_name, - filter_empty=False, - proposal_files=[ - cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(x)] for x in dataset_name - ] - if cfg.MODEL.LOAD_PROPOSALS - else None, - ) - if mapper is None: - mapper = DatasetMapper(cfg, False) - return { - "dataset": dataset, - "mapper": mapper, - "num_workers": cfg.DATALOADER.NUM_WORKERS, - "sampler": InferenceSampler(len(dataset)) - if not isinstance(dataset, torchdata.IterableDataset) - else None, - } - - -@configurable(from_config=_test_loader_from_config) -def build_detection_test_loader( - dataset: Union[List[Any], torchdata.Dataset], - *, - mapper: Callable[[Dict[str, Any]], Any], - sampler: Optional[torchdata.Sampler] = None, - batch_size: int = 1, - num_workers: int = 0, - collate_fn: Optional[Callable[[List[Any]], Any]] = None, -) -> torchdata.DataLoader: - """ - Similar to `build_detection_train_loader`, with default batch size = 1, - and sampler = :class:`InferenceSampler`. This sampler coordinates all workers - to produce the exact set of all samples. - - Args: - dataset: a list of dataset dicts, - or a pytorch dataset (either map-style or iterable). They can be obtained - by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`. - mapper: a callable which takes a sample (dict) from dataset - and returns the format to be consumed by the model. - When using cfg, the default choice is ``DatasetMapper(cfg, is_train=False)``. - sampler: a sampler that produces - indices to be applied on ``dataset``. Default to :class:`InferenceSampler`, - which splits the dataset across all workers. Sampler must be None - if `dataset` is iterable. - batch_size: the batch size of the data loader to be created. - Default to 1 image per worker since this is the standard when reporting - inference time in papers. - num_workers: number of parallel data loading workers - collate_fn: same as the argument of `torch.utils.data.DataLoader`. - Defaults to do no collation and return a list of data. - - Returns: - DataLoader: a torch DataLoader, that loads the given detection - dataset, with test-time transformation and batching. - - Examples: - :: - data_loader = build_detection_test_loader( - DatasetRegistry.get("my_test"), - mapper=DatasetMapper(...)) - - # or, instantiate with a CfgNode: - data_loader = build_detection_test_loader(cfg, "my_test") - """ - if isinstance(dataset, list): - dataset = DatasetFromList(dataset, copy=False) - if mapper is not None: - dataset = MapDataset(dataset, mapper) - if isinstance(dataset, torchdata.IterableDataset): - assert sampler is None, "sampler must be None if dataset is IterableDataset" - else: - if sampler is None: - sampler = InferenceSampler(len(dataset)) - return torchdata.DataLoader( - dataset, - batch_size=batch_size, - sampler=sampler, - drop_last=False, - num_workers=num_workers, - collate_fn=trivial_batch_collator if collate_fn is None else collate_fn, - ) - - -def trivial_batch_collator(batch): - """ - A batch collator that does nothing. - """ - return batch - - -def worker_init_reset_seed(worker_id): - initial_seed = torch.initial_seed() % 2**31 - seed_all_rng(initial_seed + worker_id) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/__init__.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/__init__.py deleted file mode 100644 index b2d0540b93ebbad78d6ff2cc0adc0fe8375816c2..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import importlib.abc -import importlib.util -from pathlib import Path - -__all__ = [] - -_PROJECTS = { - "point_rend": "PointRend", - "deeplab": "DeepLab", - "panoptic_deeplab": "Panoptic-DeepLab", -} -_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" - -if _PROJECT_ROOT.is_dir(): - # This is true only for in-place installation (pip install -e, setup.py develop), - # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 - - class _D2ProjectsFinder(importlib.abc.MetaPathFinder): - def find_spec(self, name, path, target=None): - if not name.startswith("detectron2.projects."): - return - project_name = name.split(".")[-1] - project_dir = _PROJECTS.get(project_name) - if not project_dir: - return - target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" - if not target_file.is_file(): - return - return importlib.util.spec_from_file_location(name, target_file) - - import sys - - sys.meta_path.append(_D2ProjectsFinder()) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/oneformer/modeling/transformer_decoder/transformer.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/oneformer/modeling/transformer_decoder/transformer.py deleted file mode 100644 index cd07525673b9b1165e1fdd0c9990a8f29c84f199..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/oneformer/modeling/transformer_decoder/transformer.py +++ /dev/null @@ -1,376 +0,0 @@ -# ------------------------------------------------------------------------------ -# Reference: https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/transformer.py -# Modified by Jitesh Jain (https://github.com/praeclarumjj3) -# ------------------------------------------------------------------------------ - -""" -Transformer class. - -Copy-paste from torch.nn.Transformer with modifications: - * positional encodings are passed in MHattention - * extra LN at the end of encoder is removed - * decoder returns a stack of activations from all decoding layers -""" -import copy -from typing import List, Optional - -import torch -import torch.nn.functional as F -from torch import Tensor, nn - - -class Transformer(nn.Module): - def __init__( - self, - d_model=512, - nhead=8, - num_encoder_layers=6, - num_decoder_layers=6, - dim_feedforward=2048, - dropout=0.1, - activation="relu", - normalize_before=False, - return_intermediate_dec=False, - ): - super().__init__() - - encoder_layer = TransformerEncoderLayer( - d_model, nhead, dim_feedforward, dropout, activation, normalize_before - ) - encoder_norm = nn.LayerNorm(d_model) if normalize_before else None - self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm) - - decoder_layer = TransformerDecoderLayer( - d_model, nhead, dim_feedforward, dropout, activation, normalize_before - ) - decoder_norm = nn.LayerNorm(d_model) - self.decoder = TransformerDecoder( - decoder_layer, - num_decoder_layers, - decoder_norm, - return_intermediate=return_intermediate_dec, - ) - - self._reset_parameters() - - self.d_model = d_model - self.nhead = nhead - - def _reset_parameters(self): - for p in self.parameters(): - if p.dim() > 1: - nn.init.xavier_uniform_(p) - - def forward(self, src, mask, query_embed, pos_embed, task_token=None): - # flatten NxCxHxW to HWxNxC - bs, c, h, w = src.shape - src = src.flatten(2).permute(2, 0, 1) - pos_embed = pos_embed.flatten(2).permute(2, 0, 1) - query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1) - if mask is not None: - mask = mask.flatten(1) - - if task_token is None: - tgt = torch.zeros_like(query_embed) - else: - tgt = task_token.repeat(query_embed.shape[0], 1, 1) - - memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed) - hs = self.decoder( - tgt, memory, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed - ) - return hs.transpose(1, 2), memory.permute(1, 2, 0).view(bs, c, h, w) - - -class TransformerEncoder(nn.Module): - def __init__(self, encoder_layer, num_layers, norm=None): - super().__init__() - self.layers = _get_clones(encoder_layer, num_layers) - self.num_layers = num_layers - self.norm = norm - - def forward( - self, - src, - mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - ): - output = src - - for layer in self.layers: - output = layer( - output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos - ) - - if self.norm is not None: - output = self.norm(output) - - return output - - -class TransformerDecoder(nn.Module): - def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): - super().__init__() - self.layers = _get_clones(decoder_layer, num_layers) - self.num_layers = num_layers - self.norm = norm - self.return_intermediate = return_intermediate - - def forward( - self, - tgt, - memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None, - ): - output = tgt - - intermediate = [] - - for layer in self.layers: - output = layer( - output, - memory, - tgt_mask=tgt_mask, - memory_mask=memory_mask, - tgt_key_padding_mask=tgt_key_padding_mask, - memory_key_padding_mask=memory_key_padding_mask, - pos=pos, - query_pos=query_pos, - ) - if self.return_intermediate: - intermediate.append(self.norm(output)) - - if self.norm is not None: - output = self.norm(output) - if self.return_intermediate: - intermediate.pop() - intermediate.append(output) - - if self.return_intermediate: - return torch.stack(intermediate) - - return output.unsqueeze(0) - - -class TransformerEncoderLayer(nn.Module): - def __init__( - self, - d_model, - nhead, - dim_feedforward=2048, - dropout=0.1, - activation="relu", - normalize_before=False, - ): - super().__init__() - self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) - # Implementation of Feedforward model - self.linear1 = nn.Linear(d_model, dim_feedforward) - self.dropout = nn.Dropout(dropout) - self.linear2 = nn.Linear(dim_feedforward, d_model) - - self.norm1 = nn.LayerNorm(d_model) - self.norm2 = nn.LayerNorm(d_model) - self.dropout1 = nn.Dropout(dropout) - self.dropout2 = nn.Dropout(dropout) - - self.activation = _get_activation_fn(activation) - self.normalize_before = normalize_before - - def with_pos_embed(self, tensor, pos: Optional[Tensor]): - return tensor if pos is None else tensor + pos - - def forward_post( - self, - src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - ): - q = k = self.with_pos_embed(src, pos) - src2 = self.self_attn( - q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask - )[0] - src = src + self.dropout1(src2) - src = self.norm1(src) - src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) - src = src + self.dropout2(src2) - src = self.norm2(src) - return src - - def forward_pre( - self, - src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - ): - src2 = self.norm1(src) - q = k = self.with_pos_embed(src2, pos) - src2 = self.self_attn( - q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask - )[0] - src = src + self.dropout1(src2) - src2 = self.norm2(src) - src2 = self.linear2(self.dropout(self.activation(self.linear1(src2)))) - src = src + self.dropout2(src2) - return src - - def forward( - self, - src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - ): - if self.normalize_before: - return self.forward_pre(src, src_mask, src_key_padding_mask, pos) - return self.forward_post(src, src_mask, src_key_padding_mask, pos) - - -class TransformerDecoderLayer(nn.Module): - def __init__( - self, - d_model, - nhead, - dim_feedforward=2048, - dropout=0.1, - activation="relu", - normalize_before=False, - ): - super().__init__() - self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) - self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) - # Implementation of Feedforward model - self.linear1 = nn.Linear(d_model, dim_feedforward) - self.dropout = nn.Dropout(dropout) - self.linear2 = nn.Linear(dim_feedforward, d_model) - - self.norm1 = nn.LayerNorm(d_model) - self.norm2 = nn.LayerNorm(d_model) - self.norm3 = nn.LayerNorm(d_model) - self.dropout1 = nn.Dropout(dropout) - self.dropout2 = nn.Dropout(dropout) - self.dropout3 = nn.Dropout(dropout) - - self.activation = _get_activation_fn(activation) - self.normalize_before = normalize_before - - def with_pos_embed(self, tensor, pos: Optional[Tensor]): - return tensor if pos is None else tensor + pos - - def forward_post( - self, - tgt, - memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None, - ): - q = k = self.with_pos_embed(tgt, query_pos) - tgt2 = self.self_attn( - q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask - )[0] - tgt = tgt + self.dropout1(tgt2) - tgt = self.norm1(tgt) - tgt2 = self.multihead_attn( - query=self.with_pos_embed(tgt, query_pos), - key=self.with_pos_embed(memory, pos), - value=memory, - attn_mask=memory_mask, - key_padding_mask=memory_key_padding_mask, - )[0] - tgt = tgt + self.dropout2(tgt2) - tgt = self.norm2(tgt) - tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) - tgt = tgt + self.dropout3(tgt2) - tgt = self.norm3(tgt) - return tgt - - def forward_pre( - self, - tgt, - memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None, - ): - tgt2 = self.norm1(tgt) - q = k = self.with_pos_embed(tgt2, query_pos) - tgt2 = self.self_attn( - q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask - )[0] - tgt = tgt + self.dropout1(tgt2) - tgt2 = self.norm2(tgt) - tgt2 = self.multihead_attn( - query=self.with_pos_embed(tgt2, query_pos), - key=self.with_pos_embed(memory, pos), - value=memory, - attn_mask=memory_mask, - key_padding_mask=memory_key_padding_mask, - )[0] - tgt = tgt + self.dropout2(tgt2) - tgt2 = self.norm3(tgt) - tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) - tgt = tgt + self.dropout3(tgt2) - return tgt - - def forward( - self, - tgt, - memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None, - ): - if self.normalize_before: - return self.forward_pre( - tgt, - memory, - tgt_mask, - memory_mask, - tgt_key_padding_mask, - memory_key_padding_mask, - pos, - query_pos, - ) - return self.forward_post( - tgt, - memory, - tgt_mask, - memory_mask, - tgt_key_padding_mask, - memory_key_padding_mask, - pos, - query_pos, - ) - - -def _get_clones(module, N): - return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) - - -def _get_activation_fn(activation): - """Return an activation function given a string""" - if activation == "relu": - return F.relu - if activation == "gelu": - return F.gelu - if activation == "glu": - return F.glu - raise RuntimeError(f"activation should be relu/gelu, not {activation}.") diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/zoe/zoedepth/models/base_models/midas_repo/ros/launch_midas_cpp.sh b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/zoe/zoedepth/models/base_models/midas_repo/ros/launch_midas_cpp.sh deleted file mode 100644 index 5a0d1583fffdc49216c625dfd07af2ae3b01a7a0..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/zoe/zoedepth/models/base_models/midas_repo/ros/launch_midas_cpp.sh +++ /dev/null @@ -1,2 +0,0 @@ -source ~/catkin_ws/devel/setup.bash -roslaunch midas_cpp midas_cpp.launch model_name:="model-small-traced.pt" input_topic:="image_topic" output_topic:="midas_topic" out_orig_size:="true" \ No newline at end of file diff --git a/spaces/cscan/CodeFormer/CodeFormer/weights/README.md b/spaces/cscan/CodeFormer/CodeFormer/weights/README.md deleted file mode 100644 index 67ad334bd672eeb9f82813cd54e8885331bbb2f2..0000000000000000000000000000000000000000 --- a/spaces/cscan/CodeFormer/CodeFormer/weights/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Weights - -Put the downloaded pre-trained models to this folder. \ No newline at end of file diff --git a/spaces/curiousily/layoutlmv3-financial-document-classification/app.py b/spaces/curiousily/layoutlmv3-financial-document-classification/app.py deleted file mode 100644 index dc0fb0ed184e945a850a891e1bdc48d72a2eba1c..0000000000000000000000000000000000000000 --- a/spaces/curiousily/layoutlmv3-financial-document-classification/app.py +++ /dev/null @@ -1,119 +0,0 @@ -import io - -import pandas as pd -import plotly.express as px -import streamlit as st -import torch -import torch.nn.functional as F -from easyocr import Reader -from PIL import Image -from transformers import ( - LayoutLMv3FeatureExtractor, - LayoutLMv3ForSequenceClassification, - LayoutLMv3Processor, - LayoutLMv3TokenizerFast, -) - -DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" -MICROSOFT_MODEL_NAME = "microsoft/layoutlmv3-base" -MODEL_NAME = "curiousily/layoutlmv3-financial-document-classification" - - -def create_bounding_box(bbox_data, width_scale: float, height_scale: float): - xs = [] - ys = [] - for x, y in bbox_data: - xs.append(x) - ys.append(y) - - left = int(min(xs) * width_scale) - top = int(min(ys) * height_scale) - right = int(max(xs) * width_scale) - bottom = int(max(ys) * height_scale) - - return [left, top, right, bottom] - - -@st.experimental_singleton -def create_ocr_reader(): - return Reader(["en"]) - - -@st.experimental_singleton -def create_processor(): - feature_extractor = LayoutLMv3FeatureExtractor(apply_ocr=False) - tokenizer = LayoutLMv3TokenizerFast.from_pretrained(MICROSOFT_MODEL_NAME) - return LayoutLMv3Processor(feature_extractor, tokenizer) - - -@st.experimental_singleton -def create_model(): - model = LayoutLMv3ForSequenceClassification.from_pretrained(MODEL_NAME) - return model.eval().to(DEVICE) - - -def predict( - image: Image, - reader: Reader, - processor: LayoutLMv3Processor, - model: LayoutLMv3ForSequenceClassification, -): - width, height = image.size - ocr_result = reader.readtext(image) - - width_scale = 1000 / width - height_scale = 1000 / height - - words = [] - boxes = [] - for bbox, word, confidence in ocr_result: - words.append(word) - boxes.append(create_bounding_box(bbox, width_scale, height_scale)) - - encoding = processor( - image, - words, - boxes=boxes, - max_length=512, - padding="max_length", - truncation=True, - return_tensors="pt", - ) - - with torch.inference_mode(): - output = model( - input_ids=encoding["input_ids"].to(DEVICE), - attention_mask=encoding["attention_mask"].to(DEVICE), - bbox=encoding["bbox"].to(DEVICE), - pixel_values=encoding["pixel_values"].to(DEVICE), - ) - logits = output.logits - predicted_class = logits.argmax() - probabilities = F.softmax(logits, dim=-1).flatten().tolist() - return predicted_class, probabilities - - -reader = create_ocr_reader() -processor = create_processor() -model = create_model() - -uploaded_file = st.file_uploader("Upload Document image", ["jpg", "png"]) -if uploaded_file is not None: - bytes_data = io.BytesIO(uploaded_file.getvalue()) - image = Image.open(bytes_data) - predicted_class, probabilities = predict(image, reader, processor, model) - predicted_label = model.config.id2label[predicted_class.item()] - - st.image(image, "Your document image") - st.markdown(f"Predicted document type: **{predicted_label}**") - - df_predictions = pd.DataFrame( - {"Document": list(model.config.id2label.values()), "Confidence": probabilities} - ) - - fig = px.bar( - df_predictions, - x="Document", - y="Confidence", - ) - st.plotly_chart(fig, use_container_width=True) diff --git a/spaces/cyberoleg/b2719240e190e2a649150d94db50be82838efeb0/diffusion_webui/diffusion_models/text2img_app.py b/spaces/cyberoleg/b2719240e190e2a649150d94db50be82838efeb0/diffusion_webui/diffusion_models/text2img_app.py deleted file mode 100644 index 8a72f574f44948b21894479a60be4af7a576514f..0000000000000000000000000000000000000000 --- a/spaces/cyberoleg/b2719240e190e2a649150d94db50be82838efeb0/diffusion_webui/diffusion_models/text2img_app.py +++ /dev/null @@ -1,168 +0,0 @@ -import gradio as gr -import torch -from diffusers import StableDiffusionPipeline - -from diffusion_webui.utils.model_list import stable_model_list -from diffusion_webui.utils.scheduler_list import ( - SCHEDULER_MAPPING, - get_scheduler, -) - - -class StableDiffusionText2ImageGenerator: - def __init__(self): - self.pipe = None - - def load_model( - self, - stable_model_path, - scheduler, - ): - if self.pipe is None or self.pipe.model_name != stable_model_path or self.pipe.scheduler_name != scheduler: - self.pipe = StableDiffusionPipeline.from_pretrained( - stable_model_path, safety_checker=None, torch_dtype=torch.float16 - ) - - self.pipe = get_scheduler(pipe=self.pipe, scheduler=scheduler) - self.pipe.to("cuda") - self.pipe.enable_xformers_memory_efficient_attention() - self.pipe.model_name = stable_model_path - self.pipe.scheduler_name = scheduler - - return self.pipe - - def generate_image( - self, - stable_model_path: str, - prompt: str, - negative_prompt: str, - num_images_per_prompt: int, - scheduler: str, - guidance_scale: int, - num_inference_step: int, - height: int, - width: int, - seed_generator=0, - ): - pipe = self.load_model( - stable_model_path=stable_model_path, - scheduler=scheduler, - ) - if seed_generator == 0: - random_seed = torch.randint(0, 1000000, (1,)) - generator = torch.manual_seed(random_seed) - else: - generator = torch.manual_seed(seed_generator) - - images = pipe( - prompt=prompt, - height=height, - width=width, - negative_prompt=negative_prompt, - num_images_per_prompt=num_images_per_prompt, - num_inference_steps=num_inference_step, - guidance_scale=guidance_scale, - generator=generator, - ).images - - return images - - def app(): - with gr.Blocks(): - with gr.Row(): - with gr.Column(): - text2image_prompt = gr.Textbox( - lines=1, - placeholder="Prompt", - show_label=False, - ) - - text2image_negative_prompt = gr.Textbox( - lines=1, - placeholder="Negative Prompt", - show_label=False, - ) - with gr.Row(): - with gr.Column(): - text2image_model_path = gr.Dropdown( - choices=stable_model_list, - value=stable_model_list[0], - label="Text-Image Model Id", - ) - - text2image_guidance_scale = gr.Slider( - minimum=0.1, - maximum=15, - step=0.1, - value=7.5, - label="Guidance Scale", - ) - - text2image_num_inference_step = gr.Slider( - minimum=1, - maximum=100, - step=1, - value=50, - label="Num Inference Step", - ) - text2image_num_images_per_prompt = gr.Slider( - minimum=1, - maximum=30, - step=1, - value=1, - label="Number Of Images", - ) - with gr.Row(): - with gr.Column(): - text2image_scheduler = gr.Dropdown( - choices=list(SCHEDULER_MAPPING.keys()), - value=list(SCHEDULER_MAPPING.keys())[0], - label="Scheduler", - ) - - text2image_height = gr.Slider( - minimum=128, - maximum=1280, - step=32, - value=512, - label="Image Height", - ) - - text2image_width = gr.Slider( - minimum=128, - maximum=1280, - step=32, - value=512, - label="Image Width", - ) - text2image_seed_generator = gr.Slider( - label="Seed(0 for random)", - minimum=0, - maximum=1000000, - value=0, - ) - text2image_predict = gr.Button(value="Generator") - - with gr.Column(): - output_image = gr.Gallery( - label="Generated images", - show_label=False, - elem_id="gallery", - ).style(grid=(1, 2), height=200) - - text2image_predict.click( - fn=StableDiffusionText2ImageGenerator().generate_image, - inputs=[ - text2image_model_path, - text2image_prompt, - text2image_negative_prompt, - text2image_num_images_per_prompt, - text2image_scheduler, - text2image_guidance_scale, - text2image_num_inference_step, - text2image_height, - text2image_width, - text2image_seed_generator, - ], - outputs=output_image, - ) diff --git a/spaces/cymic/Waifu_Diffusion_Webui/modules/txt2img.py b/spaces/cymic/Waifu_Diffusion_Webui/modules/txt2img.py deleted file mode 100644 index 9ab4d78a6f5e93a59d6a39d6d4322c2dee416003..0000000000000000000000000000000000000000 --- a/spaces/cymic/Waifu_Diffusion_Webui/modules/txt2img.py +++ /dev/null @@ -1,55 +0,0 @@ -import modules.scripts -from modules.processing import StableDiffusionProcessing, Processed, StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img, process_images -from modules.shared import opts, cmd_opts -import modules.shared as shared -import modules.processing as processing -from modules.ui import plaintext_to_html - - -def txt2img(prompt: str, negative_prompt: str, prompt_style: str, prompt_style2: str, steps: int, sampler_index: int, restore_faces: bool, tiling: bool, n_iter: int, batch_size: int, cfg_scale: float, seed: int, subseed: int, subseed_strength: float, seed_resize_from_h: int, seed_resize_from_w: int, seed_enable_extras: bool, height: int, width: int, enable_hr: bool, scale_latent: bool, denoising_strength: float, *args): - p = StableDiffusionProcessingTxt2Img( - sd_model=shared.sd_model, - outpath_samples=opts.outdir_samples or opts.outdir_txt2img_samples, - outpath_grids=opts.outdir_grids or opts.outdir_txt2img_grids, - prompt=prompt, - styles=[prompt_style, prompt_style2], - negative_prompt=negative_prompt, - seed=seed, - subseed=subseed, - subseed_strength=subseed_strength, - seed_resize_from_h=seed_resize_from_h, - seed_resize_from_w=seed_resize_from_w, - seed_enable_extras=seed_enable_extras, - sampler_index=sampler_index, - batch_size=batch_size, - n_iter=n_iter, - steps=steps, - cfg_scale=cfg_scale, - width=width, - height=height, - restore_faces=restore_faces, - tiling=tiling, - enable_hr=enable_hr, - scale_latent=scale_latent if enable_hr else None, - denoising_strength=denoising_strength if enable_hr else None, - ) - - if cmd_opts.enable_console_prompts: - print(f"\ntxt2img: {prompt}", file=shared.progress_print_out) - - processed = modules.scripts.scripts_txt2img.run(p, *args) - - if processed is None: - processed = process_images(p) - - shared.total_tqdm.clear() - - generation_info_js = processed.js() - if opts.samples_log_stdout: - print(generation_info_js) - - if opts.do_not_show_images: - processed.images = [] - - return processed.images, generation_info_js, plaintext_to_html(processed.info) - diff --git a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/backbones/iresnet.py b/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/backbones/iresnet.py deleted file mode 100644 index c6d3b9c240c24687d432197f976ee01fbf423216..0000000000000000000000000000000000000000 --- a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/backbones/iresnet.py +++ /dev/null @@ -1,187 +0,0 @@ -import torch -from torch import nn - -__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200'] - - -def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): - """3x3 convolution with padding""" - return nn.Conv2d(in_planes, - out_planes, - kernel_size=3, - stride=stride, - padding=dilation, - groups=groups, - bias=False, - dilation=dilation) - - -def conv1x1(in_planes, out_planes, stride=1): - """1x1 convolution""" - return nn.Conv2d(in_planes, - out_planes, - kernel_size=1, - stride=stride, - bias=False) - - -class IBasicBlock(nn.Module): - expansion = 1 - def __init__(self, inplanes, planes, stride=1, downsample=None, - groups=1, base_width=64, dilation=1): - super(IBasicBlock, self).__init__() - if groups != 1 or base_width != 64: - raise ValueError('BasicBlock only supports groups=1 and base_width=64') - if dilation > 1: - raise NotImplementedError("Dilation > 1 not supported in BasicBlock") - self.bn1 = nn.BatchNorm2d(inplanes, eps=1e-05,) - self.conv1 = conv3x3(inplanes, planes) - self.bn2 = nn.BatchNorm2d(planes, eps=1e-05,) - self.prelu = nn.PReLU(planes) - self.conv2 = conv3x3(planes, planes, stride) - self.bn3 = nn.BatchNorm2d(planes, eps=1e-05,) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - identity = x - out = self.bn1(x) - out = self.conv1(out) - out = self.bn2(out) - out = self.prelu(out) - out = self.conv2(out) - out = self.bn3(out) - if self.downsample is not None: - identity = self.downsample(x) - out += identity - return out - - -class IResNet(nn.Module): - fc_scale = 7 * 7 - def __init__(self, - block, layers, dropout=0, num_features=512, zero_init_residual=False, - groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False): - super(IResNet, self).__init__() - self.fp16 = fp16 - self.inplanes = 64 - self.dilation = 1 - if replace_stride_with_dilation is None: - replace_stride_with_dilation = [False, False, False] - if len(replace_stride_with_dilation) != 3: - raise ValueError("replace_stride_with_dilation should be None " - "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) - self.groups = groups - self.base_width = width_per_group - self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False) - self.bn1 = nn.BatchNorm2d(self.inplanes, eps=1e-05) - self.prelu = nn.PReLU(self.inplanes) - self.layer1 = self._make_layer(block, 64, layers[0], stride=2) - self.layer2 = self._make_layer(block, - 128, - layers[1], - stride=2, - dilate=replace_stride_with_dilation[0]) - self.layer3 = self._make_layer(block, - 256, - layers[2], - stride=2, - dilate=replace_stride_with_dilation[1]) - self.layer4 = self._make_layer(block, - 512, - layers[3], - stride=2, - dilate=replace_stride_with_dilation[2]) - self.bn2 = nn.BatchNorm2d(512 * block.expansion, eps=1e-05,) - self.dropout = nn.Dropout(p=dropout, inplace=True) - self.fc = nn.Linear(512 * block.expansion * self.fc_scale, num_features) - self.features = nn.BatchNorm1d(num_features, eps=1e-05) - nn.init.constant_(self.features.weight, 1.0) - self.features.weight.requires_grad = False - - for m in self.modules(): - if isinstance(m, nn.Conv2d): - nn.init.normal_(m.weight, 0, 0.1) - elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): - nn.init.constant_(m.weight, 1) - nn.init.constant_(m.bias, 0) - - if zero_init_residual: - for m in self.modules(): - if isinstance(m, IBasicBlock): - nn.init.constant_(m.bn2.weight, 0) - - def _make_layer(self, block, planes, blocks, stride=1, dilate=False): - downsample = None - previous_dilation = self.dilation - if dilate: - self.dilation *= stride - stride = 1 - if stride != 1 or self.inplanes != planes * block.expansion: - downsample = nn.Sequential( - conv1x1(self.inplanes, planes * block.expansion, stride), - nn.BatchNorm2d(planes * block.expansion, eps=1e-05, ), - ) - layers = [] - layers.append( - block(self.inplanes, planes, stride, downsample, self.groups, - self.base_width, previous_dilation)) - self.inplanes = planes * block.expansion - for _ in range(1, blocks): - layers.append( - block(self.inplanes, - planes, - groups=self.groups, - base_width=self.base_width, - dilation=self.dilation)) - - return nn.Sequential(*layers) - - def forward(self, x): - with torch.cuda.amp.autocast(self.fp16): - x = self.conv1(x) - x = self.bn1(x) - x = self.prelu(x) - x = self.layer1(x) - x = self.layer2(x) - x = self.layer3(x) - x = self.layer4(x) - x = self.bn2(x) - x = torch.flatten(x, 1) - x = self.dropout(x) - x = self.fc(x.float() if self.fp16 else x) - x = self.features(x) - return x - - -def _iresnet(arch, block, layers, pretrained, progress, **kwargs): - model = IResNet(block, layers, **kwargs) - if pretrained: - raise ValueError() - return model - - -def iresnet18(pretrained=False, progress=True, **kwargs): - return _iresnet('iresnet18', IBasicBlock, [2, 2, 2, 2], pretrained, - progress, **kwargs) - - -def iresnet34(pretrained=False, progress=True, **kwargs): - return _iresnet('iresnet34', IBasicBlock, [3, 4, 6, 3], pretrained, - progress, **kwargs) - - -def iresnet50(pretrained=False, progress=True, **kwargs): - return _iresnet('iresnet50', IBasicBlock, [3, 4, 14, 3], pretrained, - progress, **kwargs) - - -def iresnet100(pretrained=False, progress=True, **kwargs): - return _iresnet('iresnet100', IBasicBlock, [3, 13, 30, 3], pretrained, - progress, **kwargs) - - -def iresnet200(pretrained=False, progress=True, **kwargs): - return _iresnet('iresnet200', IBasicBlock, [6, 26, 60, 6], pretrained, - progress, **kwargs) - diff --git a/spaces/danterivers/music-generation-samples/tests/data/test_audio.py b/spaces/danterivers/music-generation-samples/tests/data/test_audio.py deleted file mode 100644 index 40c0d5ed69eff92a766dc6d176e532f0df6c2b5e..0000000000000000000000000000000000000000 --- a/spaces/danterivers/music-generation-samples/tests/data/test_audio.py +++ /dev/null @@ -1,239 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -from itertools import product -import random - -import numpy as np -import torch -import torchaudio - -from audiocraft.data.audio import audio_info, audio_read, audio_write, _av_read - -from ..common_utils import TempDirMixin, get_white_noise, save_wav - - -class TestInfo(TempDirMixin): - - def test_info_mp3(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - wav = get_white_noise(ch, int(sample_rate * duration)) - path = self.get_temp_path('sample_wav.mp3') - save_wav(path, wav, sample_rate) - info = audio_info(path) - assert info.sample_rate == sample_rate - assert info.channels == ch - # we cannot trust torchaudio for num_frames, so we don't check - - def _test_info_format(self, ext: str): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'sample_wav{ext}') - save_wav(path, wav, sample_rate) - info = audio_info(path) - assert info.sample_rate == sample_rate - assert info.channels == ch - assert np.isclose(info.duration, duration, atol=1e-5) - - def test_info_wav(self): - self._test_info_format('.wav') - - def test_info_flac(self): - self._test_info_format('.flac') - - def test_info_ogg(self): - self._test_info_format('.ogg') - - def test_info_m4a(self): - # TODO: generate m4a file programmatically - # self._test_info_format('.m4a') - pass - - -class TestRead(TempDirMixin): - - def test_read_full_wav(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - read_wav, read_sr = audio_read(path) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == wav.shape[1] - assert torch.allclose(read_wav, wav, rtol=1e-03, atol=1e-04) - - def test_read_partial_wav(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - read_duration = torch.rand(1).item() - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - read_frames = int(sample_rate * read_duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - read_wav, read_sr = audio_read(path, 0, read_duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == read_frames - assert torch.allclose(read_wav[..., 0:read_frames], wav[..., 0:read_frames], rtol=1e-03, atol=1e-04) - - def test_read_seek_time_wav(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - read_duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - seek_time = torch.rand(1).item() - read_wav, read_sr = audio_read(path, seek_time, read_duration) - seek_frames = int(sample_rate * seek_time) - expected_frames = n_frames - seek_frames - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == expected_frames - assert torch.allclose(read_wav, wav[..., seek_frames:], rtol=1e-03, atol=1e-04) - - def test_read_seek_time_wav_padded(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - read_duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - read_frames = int(sample_rate * read_duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - seek_time = torch.rand(1).item() - seek_frames = int(sample_rate * seek_time) - expected_frames = n_frames - seek_frames - read_wav, read_sr = audio_read(path, seek_time, read_duration, pad=True) - expected_pad_wav = torch.zeros(wav.shape[0], read_frames - expected_frames) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == read_frames - assert torch.allclose(read_wav[..., :expected_frames], wav[..., seek_frames:], rtol=1e-03, atol=1e-04) - assert torch.allclose(read_wav[..., expected_frames:], expected_pad_wav) - - -class TestAvRead(TempDirMixin): - - def test_avread_seek_base(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 2. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'reference_a_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - for _ in range(100): - # seek will always load a full duration segment in the file - seek_time = random.uniform(0.0, 1.0) - seek_duration = random.uniform(0.001, 1.0) - read_wav, read_sr = _av_read(path, seek_time, seek_duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == int(seek_duration * sample_rate) - - def test_avread_seek_partial(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'reference_b_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - for _ in range(100): - # seek will always load a partial segment - seek_time = random.uniform(0.5, 1.) - seek_duration = 1. - expected_num_frames = n_frames - int(seek_time * sample_rate) - read_wav, read_sr = _av_read(path, seek_time, seek_duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == expected_num_frames - - def test_avread_seek_outofbound(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'reference_c_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - seek_time = 1.5 - read_wav, read_sr = _av_read(path, seek_time, 1.) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == 0 - - def test_avread_seek_edge(self): - sample_rates = [8000, 16_000] - # some of these values will have - # int(((frames - 1) / sample_rate) * sample_rate) != (frames - 1) - n_frames = [1000, 1001, 1002] - channels = [1, 2] - for sample_rate, ch, frames in product(sample_rates, channels, n_frames): - duration = frames / sample_rate - wav = get_white_noise(ch, frames) - path = self.get_temp_path(f'reference_d_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - seek_time = (frames - 1) / sample_rate - seek_frames = int(seek_time * sample_rate) - read_wav, read_sr = _av_read(path, seek_time, duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == (frames - seek_frames) - - -class TestAudioWrite(TempDirMixin): - - def test_audio_write_wav(self): - torch.manual_seed(1234) - sample_rates = [8000, 16_000] - n_frames = [1000, 1001, 1002] - channels = [1, 2] - strategies = ["peak", "clip", "rms"] - formats = ["wav", "mp3"] - for sample_rate, ch, frames in product(sample_rates, channels, n_frames): - for format_, strategy in product(formats, strategies): - wav = get_white_noise(ch, frames) - path = self.get_temp_path(f'pred_{sample_rate}_{ch}') - audio_write(path, wav, sample_rate, format_, strategy=strategy) - read_wav, read_sr = torchaudio.load(f'{path}.{format_}') - if format_ == "wav": - assert read_wav.shape == wav.shape - - if format_ == "wav" and strategy in ["peak", "rms"]: - rescaled_read_wav = read_wav / read_wav.abs().max() * wav.abs().max() - # for a Gaussian, the typical max scale will be less than ~5x the std. - # The error when writing to disk will ~ 1/2**15, and when rescaling, 5x that. - # For RMS target, rescaling leaves more headroom by default, leading - # to a 20x rescaling typically - atol = (5 if strategy == "peak" else 20) / 2**15 - delta = (rescaled_read_wav - wav).abs().max() - assert torch.allclose(wav, rescaled_read_wav, rtol=0, atol=atol), (delta, atol) - formats = ["wav"] # faster unit tests diff --git a/spaces/dariush-bahrami/color_transfer/app.py b/spaces/dariush-bahrami/color_transfer/app.py deleted file mode 100644 index 0e73b82de8cb921a801ec1ebc9101a36c97840ff..0000000000000000000000000000000000000000 --- a/spaces/dariush-bahrami/color_transfer/app.py +++ /dev/null @@ -1,38 +0,0 @@ -import streamlit as st -import numpy as np -from colortransfer import transfer_color, convert_bytes_to_pil -import io -from PIL import Image - -with open("references.md") as file: - refrences = file.read() - -with st.container(): - st.write(refrences) - -with st.container(): - col1, col2 = st.columns(2) - - with col1: - target_img = st.file_uploader("Choose Target Image", type=["png", "jpg"]) - if target_img is not None: - st.image(target_img, width=256) - - with col2: - style_img = st.file_uploader("Choose Style Image", type=["png", "jpg"]) - if style_img is not None: - st.image(style_img, width=256) - - -with st.container(): - if st.button("Transfer!"): - if target_img is not None and style_img is not None: - result = transfer_color( - np.asarray(convert_bytes_to_pil(style_img.read())), - np.asarray(convert_bytes_to_pil(target_img.read())), - ) - st.image(result, width=700) - else: - st.error("You need to specify the target and style images first") - else: - st.write("Upload images and press Transfer button") diff --git a/spaces/dawdqd/ChuanhuChatGPT/run_Windows.bat b/spaces/dawdqd/ChuanhuChatGPT/run_Windows.bat deleted file mode 100644 index 5dd4dd065807bc83425e3876c1be14b5a234e253..0000000000000000000000000000000000000000 --- a/spaces/dawdqd/ChuanhuChatGPT/run_Windows.bat +++ /dev/null @@ -1,24 +0,0 @@ -@echo off -echo Opening ChuanhuChatGPT... - -if not exist "%~dp0\ChuanhuChat\Scripts" ( - echo Creating venv... - python -m venv ChuanhuChat - - cd /d "%~dp0\ChuanhuChat\Scripts" - call activate.bat - - cd /d "%~dp0" - pip install -r requirements.txt -) - -goto :activate_venv - -:launch -%PYTHON% ChuanhuChatbot.py %* -pause - -:activate_venv -set PYTHON="%~dp0\ChuanhuChat\Scripts\Python.exe" -echo venv %PYTHON% -goto :launch diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/utils/html.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/utils/html.py deleted file mode 100644 index a7a29fc748cf0a72e9ccdcb66c38b79aa5d1ebba..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/utils/html.py +++ /dev/null @@ -1,314 +0,0 @@ -import json -import jinja2 - - -HTML_TEMPLATE = jinja2.Template( - """ -{%- if fullhtml -%} - - - -{%- endif %} - -{%- if not requirejs %} - - {%- if mode == 'vega-lite' %} - - {%- endif %} - -{%- endif %} -{%- if fullhtml %} -{%- if requirejs %} - - -{%- endif %} - - -{%- endif %} -
- -{%- if fullhtml %} - - -{%- endif %} -""" -) - - -HTML_TEMPLATE_UNIVERSAL = jinja2.Template( - """ - -
- -""" -) - - -# This is like the HTML_TEMPLATE template, but includes vega javascript inline -# so that the resulting file is not dependent on external resources. This was -# ported over from altair_saver. -# -# implies requirejs=False and full_html=True -INLINE_HTML_TEMPLATE = jinja2.Template( - """\ - - - - - - - -
- - - -""" -) - - -TEMPLATES = { - "standard": HTML_TEMPLATE, - "universal": HTML_TEMPLATE_UNIVERSAL, - "inline": INLINE_HTML_TEMPLATE, -} - - -def spec_to_html( - spec, - mode, - vega_version, - vegaembed_version, - vegalite_version=None, - base_url="https://cdn.jsdelivr.net/npm", - output_div="vis", - embed_options=None, - json_kwds=None, - fullhtml=True, - requirejs=False, - template="standard", -): - """Embed a Vega/Vega-Lite spec into an HTML page - - Parameters - ---------- - spec : dict - a dictionary representing a vega-lite plot spec. - mode : string {'vega' | 'vega-lite'} - The rendering mode. This value is overridden by embed_options['mode'], - if it is present. - vega_version : string - For html output, the version of vega.js to use. - vegalite_version : string - For html output, the version of vegalite.js to use. - vegaembed_version : string - For html output, the version of vegaembed.js to use. - base_url : string (optional) - The base url from which to load the javascript libraries. - output_div : string (optional) - The id of the div element where the plot will be shown. - embed_options : dict (optional) - Dictionary of options to pass to the vega-embed script. Default - entry is {'mode': mode}. - json_kwds : dict (optional) - Dictionary of keywords to pass to json.dumps(). - fullhtml : boolean (optional) - If True (default) then return a full html page. If False, then return - an HTML snippet that can be embedded into an HTML page. - requirejs : boolean (optional) - If False (default) then load libraries from base_url using " - return response - -def call_openai(prompt): - prompt = "Make sure the html code looks exactly as below from the
element onwards. If someone says 'title:Migration to ver 2.28 for PAD Started.' then write the exact code as shown below:\n" + \ - "
\n" + \ - "

Migration to ver 2.23 for PAD Started.

\n" + \ - "
\n" + \ - "Make sure the html code looks exactly as below from the
element onwards. If someone says 'title:chat GPT - new thing. link_word: GPT. link:https://chat.openai.com' then write the exact code as shown below:\n" + \ - "
\n" + \ - "

chat GPT - new thing.

\n" + \ - "
\n" + \ - "Make sure the html code looks exactly as below from the
element onwards. If someone says 'youtubeid:-LE4t8HON90' then write the exact code as shown below:\n" + \ - "
\n" + \ - "
\n" + \ - "
\n" + \ - "Make sure the html code looks exactly as below from the
element onwards. If someone says 'image:only. image_source: ../../static/images/230109.n.impactai.jpg' then write the exact code as shown below:\n" + \ - "
\n" + \ - "


\n" + \ - "
\n\n" + prompt; - response = openai.ChatCompletion.create( - model="gpt-4", - messages=[ - {"role": "user", "content": prompt} - ], - temperature=0.02, - max_tokens=2000, - top_p=1, - frequency_penalty=0, - presence_penalty=0 - ) - return_string = response.choices[0]['message']['content'] - return return_string - -# Create the Gradio interface -interface = gr.Interface( - fn=generate_presentation, - inputs="text", - outputs="text", - title="Generate Presentation Using WebSlides", - description="Generate Beautiful Stories.
Copy the generated HTML code from the Output text area and save it as generated-webslides.html file and open the file in the browser. That's it.", - examples=[["I want 'title:A New Thing In Town'."], - ["I want 'youtubeid:fRyTycXMlzA'."], - ["I want 'title:I want to Know More. link_word: Know. link:https://www.openai.com'."], - ["I want 'image:only. image_source:https://media.licdn.com/dms/image/C5622AQH4iq9l1rA7oQ/feedshare-shrink_1280/0/1673218000961?e=1683158400&v=beta&t=oj4eoUhUTtoP2Is_dQlwnStlxr62ubOdj1qAlUAiTgQ'."], - ["I want 'title:A New Thing In Town'.\nI want 'youtubeid:fRyTycXMlzA'.\nI want 'title:I want to Know More. link_word: Know. link:https://www.openai.com'.\nI want 'image:only. image_source:https://marketoonist.com/wp-content/uploads/2023/01/230109.n.impactai.jpg'."]] - # article='
visitor badge
' -) -# Launch the interface -interface.launch() diff --git a/spaces/kenton-li/record/Dockerfile b/spaces/kenton-li/record/Dockerfile deleted file mode 100644 index b742a1870b92ce033b776c0defec1a9996889d50..0000000000000000000000000000000000000000 --- a/spaces/kenton-li/record/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM python:3.9 - -WORKDIR /code - -COPY ./requirements.txt /code/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -COPY . . - -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"] \ No newline at end of file diff --git a/spaces/kepl/gpt/client/css/button.css b/spaces/kepl/gpt/client/css/button.css deleted file mode 100644 index 5f604a8460d048458249f78be9dc544ade84801e..0000000000000000000000000000000000000000 --- a/spaces/kepl/gpt/client/css/button.css +++ /dev/null @@ -1,26 +0,0 @@ -.button { - display: flex; - padding: 8px 12px; - align-items: center; - justify-content: center; - border: 1px solid var(--conversations); - border-radius: var(--border-radius-1); - width: 100%; - background: transparent; - cursor: pointer; -} - -.button span { - color: var(--colour-3); - font-size: 0.875rem; -} - -.button i::before { - margin-right: 8px; -} - -@media screen and (max-width: 990px) { - .button span { - font-size: 0.75rem; - } -} diff --git a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/utils/safetensor_helper.py b/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/utils/safetensor_helper.py deleted file mode 100644 index 3cdbdd21e4ed656dfe2d31a57360afb3e96480b3..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/ChatGLM2-VC-SadTalker/src/utils/safetensor_helper.py +++ /dev/null @@ -1,8 +0,0 @@ - - -def load_x_from_safetensor(checkpoint, key): - x_generator = {} - for k,v in checkpoint.items(): - if key in k: - x_generator[k.replace(key+'.', '')] = v - return x_generator \ No newline at end of file diff --git a/spaces/kevinwang676/SadTalker/src/face3d/data/__init__.py b/spaces/kevinwang676/SadTalker/src/face3d/data/__init__.py deleted file mode 100644 index 9a9761c518a1b07c5996165869742af0a52c82bc..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/SadTalker/src/face3d/data/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -"""This package includes all the modules related to data loading and preprocessing - - To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset. - You need to implement four functions: - -- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt). - -- <__len__>: return the size of dataset. - -- <__getitem__>: get a data point from data loader. - -- : (optionally) add dataset-specific options and set default options. - -Now you can use the dataset class by specifying flag '--dataset_mode dummy'. -See our template dataset class 'template_dataset.py' for more details. -""" -import numpy as np -import importlib -import torch.utils.data -from face3d.data.base_dataset import BaseDataset - - -def find_dataset_using_name(dataset_name): - """Import the module "data/[dataset_name]_dataset.py". - - In the file, the class called DatasetNameDataset() will - be instantiated. It has to be a subclass of BaseDataset, - and it is case-insensitive. - """ - dataset_filename = "data." + dataset_name + "_dataset" - datasetlib = importlib.import_module(dataset_filename) - - dataset = None - target_dataset_name = dataset_name.replace('_', '') + 'dataset' - for name, cls in datasetlib.__dict__.items(): - if name.lower() == target_dataset_name.lower() \ - and issubclass(cls, BaseDataset): - dataset = cls - - if dataset is None: - raise NotImplementedError("In %s.py, there should be a subclass of BaseDataset with class name that matches %s in lowercase." % (dataset_filename, target_dataset_name)) - - return dataset - - -def get_option_setter(dataset_name): - """Return the static method of the dataset class.""" - dataset_class = find_dataset_using_name(dataset_name) - return dataset_class.modify_commandline_options - - -def create_dataset(opt, rank=0): - """Create a dataset given the option. - - This function wraps the class CustomDatasetDataLoader. - This is the main interface between this package and 'train.py'/'test.py' - - Example: - >>> from data import create_dataset - >>> dataset = create_dataset(opt) - """ - data_loader = CustomDatasetDataLoader(opt, rank=rank) - dataset = data_loader.load_data() - return dataset - -class CustomDatasetDataLoader(): - """Wrapper class of Dataset class that performs multi-threaded data loading""" - - def __init__(self, opt, rank=0): - """Initialize this class - - Step 1: create a dataset instance given the name [dataset_mode] - Step 2: create a multi-threaded data loader. - """ - self.opt = opt - dataset_class = find_dataset_using_name(opt.dataset_mode) - self.dataset = dataset_class(opt) - self.sampler = None - print("rank %d %s dataset [%s] was created" % (rank, self.dataset.name, type(self.dataset).__name__)) - if opt.use_ddp and opt.isTrain: - world_size = opt.world_size - self.sampler = torch.utils.data.distributed.DistributedSampler( - self.dataset, - num_replicas=world_size, - rank=rank, - shuffle=not opt.serial_batches - ) - self.dataloader = torch.utils.data.DataLoader( - self.dataset, - sampler=self.sampler, - num_workers=int(opt.num_threads / world_size), - batch_size=int(opt.batch_size / world_size), - drop_last=True) - else: - self.dataloader = torch.utils.data.DataLoader( - self.dataset, - batch_size=opt.batch_size, - shuffle=(not opt.serial_batches) and opt.isTrain, - num_workers=int(opt.num_threads), - drop_last=True - ) - - def set_epoch(self, epoch): - self.dataset.current_epoch = epoch - if self.sampler is not None: - self.sampler.set_epoch(epoch) - - def load_data(self): - return self - - def __len__(self): - """Return the number of data in the dataset""" - return min(len(self.dataset), self.opt.max_dataset_size) - - def __iter__(self): - """Return a batch of data""" - for i, data in enumerate(self.dataloader): - if i * self.opt.batch_size >= self.opt.max_dataset_size: - break - yield data diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/decode_heads/enc_head.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/decode_heads/enc_head.py deleted file mode 100644 index da57af617e05d41761628fd2d6d232655b32d905..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/decode_heads/enc_head.py +++ /dev/null @@ -1,187 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -from annotator.uniformer.mmcv.cnn import ConvModule, build_norm_layer - -from annotator.uniformer.mmseg.ops import Encoding, resize -from ..builder import HEADS, build_loss -from .decode_head import BaseDecodeHead - - -class EncModule(nn.Module): - """Encoding Module used in EncNet. - - Args: - in_channels (int): Input channels. - num_codes (int): Number of code words. - conv_cfg (dict|None): Config of conv layers. - norm_cfg (dict|None): Config of norm layers. - act_cfg (dict): Config of activation layers. - """ - - def __init__(self, in_channels, num_codes, conv_cfg, norm_cfg, act_cfg): - super(EncModule, self).__init__() - self.encoding_project = ConvModule( - in_channels, - in_channels, - 1, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - # TODO: resolve this hack - # change to 1d - if norm_cfg is not None: - encoding_norm_cfg = norm_cfg.copy() - if encoding_norm_cfg['type'] in ['BN', 'IN']: - encoding_norm_cfg['type'] += '1d' - else: - encoding_norm_cfg['type'] = encoding_norm_cfg['type'].replace( - '2d', '1d') - else: - # fallback to BN1d - encoding_norm_cfg = dict(type='BN1d') - self.encoding = nn.Sequential( - Encoding(channels=in_channels, num_codes=num_codes), - build_norm_layer(encoding_norm_cfg, num_codes)[1], - nn.ReLU(inplace=True)) - self.fc = nn.Sequential( - nn.Linear(in_channels, in_channels), nn.Sigmoid()) - - def forward(self, x): - """Forward function.""" - encoding_projection = self.encoding_project(x) - encoding_feat = self.encoding(encoding_projection).mean(dim=1) - batch_size, channels, _, _ = x.size() - gamma = self.fc(encoding_feat) - y = gamma.view(batch_size, channels, 1, 1) - output = F.relu_(x + x * y) - return encoding_feat, output - - -@HEADS.register_module() -class EncHead(BaseDecodeHead): - """Context Encoding for Semantic Segmentation. - - This head is the implementation of `EncNet - `_. - - Args: - num_codes (int): Number of code words. Default: 32. - use_se_loss (bool): Whether use Semantic Encoding Loss (SE-loss) to - regularize the training. Default: True. - add_lateral (bool): Whether use lateral connection to fuse features. - Default: False. - loss_se_decode (dict): Config of decode loss. - Default: dict(type='CrossEntropyLoss', use_sigmoid=True). - """ - - def __init__(self, - num_codes=32, - use_se_loss=True, - add_lateral=False, - loss_se_decode=dict( - type='CrossEntropyLoss', - use_sigmoid=True, - loss_weight=0.2), - **kwargs): - super(EncHead, self).__init__( - input_transform='multiple_select', **kwargs) - self.use_se_loss = use_se_loss - self.add_lateral = add_lateral - self.num_codes = num_codes - self.bottleneck = ConvModule( - self.in_channels[-1], - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - if add_lateral: - self.lateral_convs = nn.ModuleList() - for in_channels in self.in_channels[:-1]: # skip the last one - self.lateral_convs.append( - ConvModule( - in_channels, - self.channels, - 1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg)) - self.fusion = ConvModule( - len(self.in_channels) * self.channels, - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - self.enc_module = EncModule( - self.channels, - num_codes=num_codes, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - if self.use_se_loss: - self.loss_se_decode = build_loss(loss_se_decode) - self.se_layer = nn.Linear(self.channels, self.num_classes) - - def forward(self, inputs): - """Forward function.""" - inputs = self._transform_inputs(inputs) - feat = self.bottleneck(inputs[-1]) - if self.add_lateral: - laterals = [ - resize( - lateral_conv(inputs[i]), - size=feat.shape[2:], - mode='bilinear', - align_corners=self.align_corners) - for i, lateral_conv in enumerate(self.lateral_convs) - ] - feat = self.fusion(torch.cat([feat, *laterals], 1)) - encode_feat, output = self.enc_module(feat) - output = self.cls_seg(output) - if self.use_se_loss: - se_output = self.se_layer(encode_feat) - return output, se_output - else: - return output - - def forward_test(self, inputs, img_metas, test_cfg): - """Forward function for testing, ignore se_loss.""" - if self.use_se_loss: - return self.forward(inputs)[0] - else: - return self.forward(inputs) - - @staticmethod - def _convert_to_onehot_labels(seg_label, num_classes): - """Convert segmentation label to onehot. - - Args: - seg_label (Tensor): Segmentation label of shape (N, H, W). - num_classes (int): Number of classes. - - Returns: - Tensor: Onehot labels of shape (N, num_classes). - """ - - batch_size = seg_label.size(0) - onehot_labels = seg_label.new_zeros((batch_size, num_classes)) - for i in range(batch_size): - hist = seg_label[i].float().histc( - bins=num_classes, min=0, max=num_classes - 1) - onehot_labels[i] = hist > 0 - return onehot_labels - - def losses(self, seg_logit, seg_label): - """Compute segmentation and semantic encoding loss.""" - seg_logit, se_seg_logit = seg_logit - loss = dict() - loss.update(super(EncHead, self).losses(seg_logit, seg_label)) - se_loss = self.loss_se_decode( - se_seg_logit, - self._convert_to_onehot_labels(seg_label, self.num_classes)) - loss['loss_se'] = se_loss - return loss diff --git a/spaces/konbraphat51/Kato-DB/README.md b/spaces/konbraphat51/Kato-DB/README.md deleted file mode 100644 index 9fc775a6a1f237ba02ee6a8857e99369763f8270..0000000000000000000000000000000000000000 --- a/spaces/konbraphat51/Kato-DB/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Kato DB -emoji: 🌍 -colorFrom: red -colorTo: yellow -sdk: streamlit -sdk_version: 1.25.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/konverner/deep-voice-cloning/README.md b/spaces/konverner/deep-voice-cloning/README.md deleted file mode 100644 index b0eccb70b6563e85c5d571867acba8261a92b44f..0000000000000000000000000000000000000000 --- a/spaces/konverner/deep-voice-cloning/README.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -license: openrail -title: Deep Voice Cloning -sdk: gradio -emoji: 🌖 -colorFrom: yellow -colorTo: purple -pinned: true ---- \ No newline at end of file diff --git a/spaces/kouenYoung/anime-tts/vits_api.py b/spaces/kouenYoung/anime-tts/vits_api.py deleted file mode 100644 index b846f7928beb2bd80a83af807997951661907735..0000000000000000000000000000000000000000 --- a/spaces/kouenYoung/anime-tts/vits_api.py +++ /dev/null @@ -1,26 +0,0 @@ -import re -import time -import infer -import config -import uvicorn -import asyncio -from starlette.responses import FileResponse -from fastapi import FastAPI, File, UploadFile, Form - -app = FastAPI() - -pth_path = config.pth_path -config_json = config.config_json -net_g_ms, hps = infer.load_model(config_json, pth_path) -sp_dict = {speaker: i for i, speaker in enumerate(hps.speakers)} - - -@app.get("/tts", response_class=FileResponse) -async def read_item(text: str, speaker: str): - print(text, speaker) - text = infer.clean_text(text) - infer.infer(text, net_g_ms, sp_dict[speaker], "demo") - return "./demo.mp3" - - -uvicorn.run(app, host="0.0.0.0") diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/designspaceLib/types.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/designspaceLib/types.py deleted file mode 100644 index 80ba9d6d7b44f58773f42107d672c13651c166a9..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/designspaceLib/types.py +++ /dev/null @@ -1,147 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from typing import Dict, List, Optional, Union, cast - -from fontTools.designspaceLib import ( - AxisDescriptor, - DesignSpaceDocument, - DesignSpaceDocumentError, - RangeAxisSubsetDescriptor, - SimpleLocationDict, - ValueAxisSubsetDescriptor, - VariableFontDescriptor, -) - - -def clamp(value, minimum, maximum): - return min(max(value, minimum), maximum) - - -@dataclass -class Range: - minimum: float - """Inclusive minimum of the range.""" - maximum: float - """Inclusive maximum of the range.""" - default: float = 0 - """Default value""" - - def __post_init__(self): - self.minimum, self.maximum = sorted((self.minimum, self.maximum)) - self.default = clamp(self.default, self.minimum, self.maximum) - - def __contains__(self, value: Union[float, Range]) -> bool: - if isinstance(value, Range): - return self.minimum <= value.minimum and value.maximum <= self.maximum - return self.minimum <= value <= self.maximum - - def intersection(self, other: Range) -> Optional[Range]: - if self.maximum < other.minimum or self.minimum > other.maximum: - return None - else: - return Range( - max(self.minimum, other.minimum), - min(self.maximum, other.maximum), - self.default, # We don't care about the default in this use-case - ) - - -# A region selection is either a range or a single value, as a Designspace v5 -# axis-subset element only allows a single discrete value or a range for a -# variable-font element. -Region = Dict[str, Union[Range, float]] - -# A conditionset is a set of named ranges. -ConditionSet = Dict[str, Range] - -# A rule is a list of conditionsets where any has to be relevant for the whole rule to be relevant. -Rule = List[ConditionSet] -Rules = Dict[str, Rule] - - -def locationInRegion(location: SimpleLocationDict, region: Region) -> bool: - for name, value in location.items(): - if name not in region: - return False - regionValue = region[name] - if isinstance(regionValue, (float, int)): - if value != regionValue: - return False - else: - if value not in regionValue: - return False - return True - - -def regionInRegion(region: Region, superRegion: Region) -> bool: - for name, value in region.items(): - if not name in superRegion: - return False - superValue = superRegion[name] - if isinstance(superValue, (float, int)): - if value != superValue: - return False - else: - if value not in superValue: - return False - return True - - -def userRegionToDesignRegion(doc: DesignSpaceDocument, userRegion: Region) -> Region: - designRegion = {} - for name, value in userRegion.items(): - axis = doc.getAxis(name) - if axis is None: - raise DesignSpaceDocumentError( - f"Cannot find axis named '{name}' for region." - ) - if isinstance(value, (float, int)): - designRegion[name] = axis.map_forward(value) - else: - designRegion[name] = Range( - axis.map_forward(value.minimum), - axis.map_forward(value.maximum), - axis.map_forward(value.default), - ) - return designRegion - - -def getVFUserRegion(doc: DesignSpaceDocument, vf: VariableFontDescriptor) -> Region: - vfUserRegion: Region = {} - # For each axis, 2 cases: - # - it has a range = it's an axis in the VF DS - # - it's a single location = use it to know which rules should apply in the VF - for axisSubset in vf.axisSubsets: - axis = doc.getAxis(axisSubset.name) - if axis is None: - raise DesignSpaceDocumentError( - f"Cannot find axis named '{axisSubset.name}' for variable font '{vf.name}'." - ) - if hasattr(axisSubset, "userMinimum"): - # Mypy doesn't support narrowing union types via hasattr() - # TODO(Python 3.10): use TypeGuard - # https://mypy.readthedocs.io/en/stable/type_narrowing.html - axisSubset = cast(RangeAxisSubsetDescriptor, axisSubset) - if not hasattr(axis, "minimum"): - raise DesignSpaceDocumentError( - f"Cannot select a range over '{axis.name}' for variable font '{vf.name}' " - "because it's a discrete axis, use only 'userValue' instead." - ) - axis = cast(AxisDescriptor, axis) - vfUserRegion[axis.name] = Range( - max(axisSubset.userMinimum, axis.minimum), - min(axisSubset.userMaximum, axis.maximum), - axisSubset.userDefault or axis.default, - ) - else: - axisSubset = cast(ValueAxisSubsetDescriptor, axisSubset) - vfUserRegion[axis.name] = axisSubset.userValue - # Any axis not mentioned explicitly has a single location = default value - for axis in doc.axes: - if axis.name not in vfUserRegion: - assert isinstance( - axis.default, (int, float) - ), f"Axis '{axis.name}' has no valid default value." - vfUserRegion[axis.name] = axis.default - return vfUserRegion diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/dictTools.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/dictTools.py deleted file mode 100644 index 259613b27048c458980986167d429847d270691f..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/dictTools.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Misc dict tools.""" - - -__all__ = ["hashdict"] - -# https://stackoverflow.com/questions/1151658/python-hashable-dicts -class hashdict(dict): - """ - hashable dict implementation, suitable for use as a key into - other dicts. - - >>> h1 = hashdict({"apples": 1, "bananas":2}) - >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) - >>> h1+h2 - hashdict(apples=1, bananas=3, mangoes=5) - >>> d1 = {} - >>> d1[h1] = "salad" - >>> d1[h1] - 'salad' - >>> d1[h2] - Traceback (most recent call last): - ... - KeyError: hashdict(bananas=3, mangoes=5) - - based on answers from - http://stackoverflow.com/questions/1151658/python-hashable-dicts - - """ - - def __key(self): - return tuple(sorted(self.items())) - - def __repr__(self): - return "{0}({1})".format( - self.__class__.__name__, - ", ".join("{0}={1}".format(str(i[0]), repr(i[1])) for i in self.__key()), - ) - - def __hash__(self): - return hash(self.__key()) - - def __setitem__(self, key, value): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - def __delitem__(self, key): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - def clear(self): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - def pop(self, *args, **kwargs): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - def popitem(self, *args, **kwargs): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - def setdefault(self, *args, **kwargs): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - def update(self, *args, **kwargs): - raise TypeError( - "{0} does not support item assignment".format(self.__class__.__name__) - ) - - # update is not ok because it mutates the object - # __add__ is ok because it creates a new object - # while the new object is under construction, it's ok to mutate it - def __add__(self, right): - result = hashdict(self) - dict.update(result, right) - return result diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/textTools.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/textTools.py deleted file mode 100644 index f7ca1acc9b762e1ffcfefd22a399927f8369a056..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/textTools.py +++ /dev/null @@ -1,155 +0,0 @@ -"""fontTools.misc.textTools.py -- miscellaneous routines.""" - - -import ast -import string - - -# alias kept for backward compatibility -safeEval = ast.literal_eval - - -class Tag(str): - @staticmethod - def transcode(blob): - if isinstance(blob, bytes): - blob = blob.decode("latin-1") - return blob - - def __new__(self, content): - return str.__new__(self, self.transcode(content)) - - def __ne__(self, other): - return not self.__eq__(other) - - def __eq__(self, other): - return str.__eq__(self, self.transcode(other)) - - def __hash__(self): - return str.__hash__(self) - - def tobytes(self): - return self.encode("latin-1") - - -def readHex(content): - """Convert a list of hex strings to binary data.""" - return deHexStr(strjoin(chunk for chunk in content if isinstance(chunk, str))) - - -def deHexStr(hexdata): - """Convert a hex string to binary data.""" - hexdata = strjoin(hexdata.split()) - if len(hexdata) % 2: - hexdata = hexdata + "0" - data = [] - for i in range(0, len(hexdata), 2): - data.append(bytechr(int(hexdata[i : i + 2], 16))) - return bytesjoin(data) - - -def hexStr(data): - """Convert binary data to a hex string.""" - h = string.hexdigits - r = "" - for c in data: - i = byteord(c) - r = r + h[(i >> 4) & 0xF] + h[i & 0xF] - return r - - -def num2binary(l, bits=32): - items = [] - binary = "" - for i in range(bits): - if l & 0x1: - binary = "1" + binary - else: - binary = "0" + binary - l = l >> 1 - if not ((i + 1) % 8): - items.append(binary) - binary = "" - if binary: - items.append(binary) - items.reverse() - assert l in (0, -1), "number doesn't fit in number of bits" - return " ".join(items) - - -def binary2num(bin): - bin = strjoin(bin.split()) - l = 0 - for digit in bin: - l = l << 1 - if digit != "0": - l = l | 0x1 - return l - - -def caselessSort(alist): - """Return a sorted copy of a list. If there are only strings - in the list, it will not consider case. - """ - - try: - return sorted(alist, key=lambda a: (a.lower(), a)) - except TypeError: - return sorted(alist) - - -def pad(data, size): - r"""Pad byte string 'data' with null bytes until its length is a - multiple of 'size'. - - >>> len(pad(b'abcd', 4)) - 4 - >>> len(pad(b'abcde', 2)) - 6 - >>> len(pad(b'abcde', 4)) - 8 - >>> pad(b'abcdef', 4) == b'abcdef\x00\x00' - True - """ - data = tobytes(data) - if size > 1: - remainder = len(data) % size - if remainder: - data += b"\0" * (size - remainder) - return data - - -def tostr(s, encoding="ascii", errors="strict"): - if not isinstance(s, str): - return s.decode(encoding, errors) - else: - return s - - -def tobytes(s, encoding="ascii", errors="strict"): - if isinstance(s, str): - return s.encode(encoding, errors) - else: - return bytes(s) - - -def bytechr(n): - return bytes([n]) - - -def byteord(c): - return c if isinstance(c, int) else ord(c) - - -def strjoin(iterable, joiner=""): - return tostr(joiner).join(iterable) - - -def bytesjoin(iterable, joiner=b""): - return tobytes(joiner).join(tobytes(item) for item in iterable) - - -if __name__ == "__main__": - import doctest, sys - - sys.exit(doctest.testmod().failed) diff --git a/spaces/lafi23333/aikomori/vdecoder/__init__.py b/spaces/lafi23333/aikomori/vdecoder/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/lanyi2023/QQsign/devices/device_8963.js b/spaces/lanyi2023/QQsign/devices/device_8963.js deleted file mode 100644 index f1bf97749204e374f59d7971ad55c991e97e19af..0000000000000000000000000000000000000000 --- a/spaces/lanyi2023/QQsign/devices/device_8963.js +++ /dev/null @@ -1,344 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getApkInfo = exports.Platform = exports.Device = exports.generateFullDevice = exports.generateShortDevice = void 0; -const crypto_1 = require("crypto"); -const constants_1 = require("./constants"); -const axios_1 = __importDefault(require("axios")); -const algo_1 = require("./algo"); -function generateImei() { - let imei = `86${(0, constants_1.randomString)(12, '0123456789')}`; - function calcSP(imei) { - let sum = 0; - for (let i = 0; i < imei.length; ++i) { - if (i % 2) { - let j = parseInt(imei[i]) * 2; - sum += j % 10 + Math.floor(j / 10); - } - else { - sum += parseInt(imei[i]); - } - } - return (100 - sum) % 10; - } - return imei + calcSP(imei); -} -/** 生成短设备信息 */ -function generateShortDevice() { - const randstr = (length, num = false) => { - const map = num ? '0123456789' : '0123456789abcdef'; - return (0, constants_1.randomString)(length, map); - }; - return { - "--begin--": "该设备为随机生成,丢失后不能得到原先配置", - product: `ILPP-${randstr(5).toUpperCase()}`, - device: `${randstr(5).toUpperCase()}`, - board: `${randstr(5).toUpperCase()}`, - brand: `${randstr(4).toUpperCase()}`, - model: `ICQQ ${randstr(4).toUpperCase()}`, - wifi_ssid: `HUAWEI-${randstr(7)}`, - bootloader: `U-boot`, - android_id: `IL.${randstr(7, true)}.${randstr(4, true)}`, - boot_id: `${randstr(8)}-${randstr(4)}-${randstr(4)}-${randstr(4)}-${randstr(12)}`, - proc_version: `Linux version 5.10.101-android12-${randstr(8)}`, - mac_address: `2D:${randstr(2).toUpperCase()}:${randstr(2).toUpperCase()}:${randstr(2).toUpperCase()}:${randstr(2).toUpperCase()}:${randstr(2).toUpperCase()}`, - ip_address: `192.168.${randstr(2, true)}.${randstr(2, true)}`, - imei: `${generateImei()}`, - incremental: `${randstr(10, true).toUpperCase()}`, - "--end--": "修改后可能需要重新验证设备。" - }; -} -exports.generateShortDevice = generateShortDevice; -/** 生成完整设备信息 */ -function generateFullDevice(apk, d) { - if (!d) - d = generateShortDevice(); - return { - display: d.android_id, - product: d.product, - device: d.device, - board: d.board, - brand: d.brand, - model: d.model, - bootloader: d.bootloader, - fingerprint: `${d.brand}/${d.product}/${d.device}:10/${d.android_id}/${d.incremental}:user/release-keys`, - boot_id: d.boot_id, - proc_version: d.proc_version, - baseband: "", - sim: "T-Mobile", - os_type: "android", - mac_address: d.mac_address, - ip_address: d.ip_address, - wifi_bssid: d.mac_address, - wifi_ssid: d.wifi_ssid, - imei: d.imei, - android_id: (0, constants_1.md5)(d.android_id).toString("hex"), - apn: "wifi", - version: { - incremental: d.incremental, - release: "10", - codename: "REL", - sdk: 29, - }, - imsi: (0, crypto_1.randomBytes)(16), - guid: (0, constants_1.md5)(Buffer.concat([Buffer.from(d.imei), Buffer.from(d.mac_address)])), - }; -} -exports.generateFullDevice = generateFullDevice; -class Device { - constructor(apk, d) { - this.apk = apk; - this.secret = 'ZdJqM15EeO2zWc08'; - this.publicKey = `-----BEGIN PUBLIC KEY----- -MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEIxgwoutfwoJxcGQeedgP7FG9 -qaIuS0qzfR8gWkrkTZKM2iWHn2ajQpBRZjMSoSf6+KJGvar2ORhBfpDXyVtZCKpq -LQ+FLkpncClKVIrBwv6PHyUvuCb0rIarmgDnzkfQAqVufEtR64iazGDKatvJ9y6B -9NMbHddGSAUmRTCrHQIDAQAB ------END PUBLIC KEY-----`; - if (!d) - d = generateShortDevice(); - Object.assign(this, generateFullDevice(apk, d)); - } - async getQIMEI() { - if (this.apk.app_key === "") { - return; - } - const k = (0, constants_1.randomString)(16); - const key = (0, algo_1.encryptPKCS1)(this.publicKey, k); - const time = Date.now(); - const nonce = (0, constants_1.randomString)(16); - const payload = this.genRandomPayloadByDevice(); - const params = (0, algo_1.aesEncrypt)(JSON.stringify(payload), k).toString('base64'); - try { - const { data } = await axios_1.default.post("https://snowflake.qq.com/ola/android", { - key, - params, - time, nonce, - sign: (0, constants_1.md5)(key + params + time + nonce + this.secret).toString("hex"), - extra: '' - }, { - headers: { - 'User-Agent': `Dalvik/2.1.0 (Linux; U; Android ${this.version.release}; PCRT00 Build/N2G48H)`, - 'Content-Type': "application/json" - } - }); - if (data?.code !== 0) { - return; - } - const { q16, q36 } = JSON.parse((0, algo_1.aesDecrypt)(data.data, k)); - this.qImei16 = q16; - this.qImei36 = q36; - } - catch { - } - } - genRandomPayloadByDevice() { - const fixedRand = (max = 1, min = 0) => { - if (max < min) - [max, min] = [min, max]; - const diff = max - min; - return Math.floor(Math.random() * diff) + min; - }; - const reserved = { - "harmony": "0", - "clone": Math.random() > 0.5 ? "1" : "0", - "containe": "", - "oz": "", - "oo": "", - "kelong": Math.random() > 0.5 ? "1" : "0", - "uptimes": (0, constants_1.formatTime)(new Date()), - "multiUser": Math.random() > 0.5 ? "1" : "0", - "bod": this.board, - "brd": this.brand, - "dv": this.device, - "firstLevel": "", - "manufact": this.brand, - "name": this.model, - "host": "se.infra", - "kernel": this.fingerprint - }; - const timestamp = Date.now(); - this.mtime = this.mtime || Date.now(); - const mtime1 = new Date(this.mtime || Date.now()); - const dateFormat = (fmt, time = Date.now()) => (0, constants_1.formatTime)(time, fmt); - const mtimeStr1 = dateFormat("YYYY-mm-ddHHMMSS", mtime1) + "." + this.imei.slice(2, 11); - const mtime2 = new Date(this.mtime - parseInt(this.imei.slice(2, 4))); - const mtimeStr2 = dateFormat("YYYY-mm-ddHHMMSS", mtime2) + "." + this.imei.slice(5, 14); - let beaconIdArr = [ - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - mtimeStr1, - '0000000000000000', - (0, constants_1.md5)(this.android_id + this.imei).toString("hex").slice(0, 16), - ...new Array(4).fill(false).map((_) => fixedRand(10000000, 1000000)), - this.boot_id, - '1', - fixedRand(5, 0), - fixedRand(5, 0), - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - fixedRand(5, 0), - fixedRand(100, 10), - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - fixedRand(50000, 10000), - fixedRand(100, 10), - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - mtimeStr2, - fixedRand(10000, 1000), - fixedRand(5, 0), - `${dateFormat("YYYY-mm-ddHHMMSS")}.${String(((10 + parseInt(this.imei.slice(5, 7))) % 100)).padStart(2, "0")}0000000`, - `${dateFormat("YYYY-mm-ddHHMMSS")}.${String(((11 + parseInt(this.imei.slice(5, 7))) % 100)).padStart(2, "0")}0000000`, - fixedRand(10000, 1000), - fixedRand(100, 10), - `${dateFormat("YYYY-mm-ddHHMMSS")}.${String(((11 + parseInt(this.imei.slice(5, 7))) % 100)).padStart(2, "0")}0000000`, - `${dateFormat("YYYY-mm-ddHHMMSS")}.${String(((11 + parseInt(this.imei.slice(5, 7))) % 100)).padStart(2, "0")}0000000`, - fixedRand(10000, 1000), - fixedRand(5, 0), - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - fixedRand(5, 0), - fixedRand(100, 10), - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - `${(0, constants_1.formatTime)(new Date(timestamp + fixedRand(60, 0)))}.${String(fixedRand(99, 0)).padStart(2, '0')}0000000`, - fixedRand(5, 0), - fixedRand(5, 0), - ].map((str, idx) => `k${idx + 1}:${str}`); - return { - "androidId": this.android_id, - "platformId": 1, - "appKey": this.apk.app_key, - "appVersion": this.apk.version, - "beaconIdSrc": beaconIdArr.join(';'), - "brand": this.brand, - "channelId": "2017", - "cid": "", - "imei": this.imei, - "imsi": this.imsi.toString("hex"), - "mac": this.mac_address, - "model": this.model, - "networkType": "unknown", - "oaid": "", - "osVersion": `Android ${this.version.release},level ${this.version.sdk}`, - "qimei": "", - "qimei36": "", - "sdkVersion": "1.2.13.6", - "targetSdkVersion": "26", - "audit": "", - "userId": "{}", - "packageId": this.apk.id, - "deviceType": this.display, - "sdkName": "", - "reserved": JSON.stringify(reserved), - }; - } -} -exports.Device = Device; -/** 支持的登录设备平台 */ -var Platform; -(function (Platform) { - Platform[Platform["Android"] = 1] = "Android"; - Platform[Platform["aPad"] = 2] = "aPad"; - Platform[Platform["Watch"] = 3] = "Watch"; - Platform[Platform["iMac"] = 4] = "iMac"; - Platform[Platform["iPad"] = 5] = "iPad"; - Platform[Platform["Tim"] = 6] = "Tim"; -})(Platform = exports.Platform || (exports.Platform = {})); -const mobile = { - id: "com.tencent.mobileqq", - app_key: '0S200MNJT807V3GE', - name: "A8.9.63.11390", - version: "8.9.63.11390", - ver: "8.9.63", - sign: Buffer.from('A6 B7 45 BF 24 A2 C2 77 52 77 16 F6 F3 6E B6 8D'.split(' ').map(s => parseInt(s, 16))), - buildtime: 1685069178, - appid: 16, - subid: 537164840, - bitmap: 150470524, - main_sig_map: 16724722, - sub_sig_map: 0x10400, - sdkver: "6.0.0.2546", - display: "Android", - qua: 'V1_AND_SQ_8.9.63_4194_YYB_D', - ssover: 20, -}; -const tim = { - id: "com.tencent.tim", - app_key: '0S200MNJT807V3GE', - name: "A3.5.1.3168", - version: "3.5.1.3168", - ver: "3.5.1", - sign: Buffer.from('775e696d09856872fdd8ab4f3f06b1e0', 'hex'), - buildtime: 1630062176, - appid: 16, - subid: 537150355, - bitmap: 150470524, - main_sig_map: 16724722, - sub_sig_map: 0x10400, - sdkver: "6.0.0.2484", - display: "Tim", - qua: "V1_AND_SQ_8.3.9_351_TIM_D", - ssover: 18, -}; -const watch = { - id: "com.tencent.qqlite", - app_key: '0S200MNJT807V3GE', - name: "A2.0.8", - version: "2.0.8", - ver: "2.0.8", - sign: Buffer.from('A6 B7 45 BF 24 A2 C2 77 52 77 16 F6 F3 6E B6 8D'.split(' ').map(s => parseInt(s, 16))), - buildtime: 1559564731, - appid: 16, - subid: 537065138, - bitmap: 16252796, - main_sig_map: 16724722, - sub_sig_map: 0x10400, - sdkver: "6.0.0.2365", - display: "Watch", - qua: '', - ssover: 5 -}; -const hd = { - id: "com.tencent.minihd.qq", - app_key: '0S200MNJT807V3GE', - name: "A5.9.3.3468", - version: "5.9.3.3468", - ver: "5.9.3", - sign: Buffer.from('AA 39 78 F4 1F D9 6F F9 91 4A 66 9E 18 64 74 C7'.split(' ').map(s => parseInt(s, 16))), - buildtime: 1637427966, - appid: 16, - subid: 537128930, - bitmap: 150470524, - main_sig_map: 1970400, - sub_sig_map: 66560, - sdkver: "6.0.0.2433", - display: "iMac", - qua: '', - ssover: 12 -}; -const apklist = { - [Platform.Android]: mobile, - [Platform.Tim]: tim, - [Platform.aPad]: { - ...mobile, - subid: 537164888, - display: 'aPad' - }, - [Platform.Watch]: watch, - [Platform.iMac]: { ...hd }, - [Platform.iPad]: { - ...mobile, - subid: 537155074, - sign: hd.sign, - name: '8.9.50.611', - ver: '8.9.50', - sdkver: '6.0.0.2535', - qua: 'V1_AND_SQ_8.9.50_3898_YYB_D', - display: 'iPad' - }, -}; -function getApkInfo(p) { - return apklist[p] || apklist[Platform.Android]; -} -exports.getApkInfo = getApkInfo; diff --git a/spaces/leogabraneth/text-generation-webui-main/modules/ui.py b/spaces/leogabraneth/text-generation-webui-main/modules/ui.py deleted file mode 100644 index 9d87bad668be1986facff886fdc4a09c886916ce..0000000000000000000000000000000000000000 --- a/spaces/leogabraneth/text-generation-webui-main/modules/ui.py +++ /dev/null @@ -1,235 +0,0 @@ -import copy -from pathlib import Path - -import gradio as gr -import torch -import yaml -from transformers import is_torch_xpu_available - -from modules import shared - -with open(Path(__file__).resolve().parent / '../css/NotoSans/stylesheet.css', 'r') as f: - css = f.read() -with open(Path(__file__).resolve().parent / '../css/main.css', 'r') as f: - css += f.read() -with open(Path(__file__).resolve().parent / '../js/main.js', 'r') as f: - js = f.read() -with open(Path(__file__).resolve().parent / '../js/save_files.js', 'r') as f: - save_files_js = f.read() -with open(Path(__file__).resolve().parent / '../js/switch_tabs.js', 'r') as f: - switch_tabs_js = f.read() -with open(Path(__file__).resolve().parent / '../js/show_controls.js', 'r') as f: - show_controls_js = f.read() - -refresh_symbol = '🔄' -delete_symbol = '🗑️' -save_symbol = '💾' - -theme = gr.themes.Default( - font=['Noto Sans', 'Helvetica', 'ui-sans-serif', 'system-ui', 'sans-serif'], - font_mono=['IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace'], -).set( - border_color_primary='#c5c5d2', - button_large_padding='6px 12px', - body_text_color_subdued='#484848', - background_fill_secondary='#eaeaea' -) - -if Path("notification.mp3").exists(): - audio_notification_js = "document.querySelector('#audio_notification audio')?.play();" -else: - audio_notification_js = "" - - -def list_model_elements(): - elements = [ - 'loader', - 'filter_by_loader', - 'cpu_memory', - 'auto_devices', - 'disk', - 'cpu', - 'bf16', - 'load_in_8bit', - 'trust_remote_code', - 'use_fast', - 'load_in_4bit', - 'compute_dtype', - 'quant_type', - 'use_double_quant', - 'wbits', - 'groupsize', - 'model_type', - 'pre_layer', - 'triton', - 'desc_act', - 'no_inject_fused_attention', - 'no_inject_fused_mlp', - 'no_use_cuda_fp16', - 'disable_exllama', - 'cfg_cache', - 'threads', - 'threads_batch', - 'n_batch', - 'no_mmap', - 'mlock', - 'no_mul_mat_q', - 'n_gpu_layers', - 'tensor_split', - 'n_ctx', - 'llama_cpp_seed', - 'gpu_split', - 'max_seq_len', - 'compress_pos_emb', - 'alpha_value', - 'rope_freq_base', - 'numa', - ] - if is_torch_xpu_available(): - for i in range(torch.xpu.device_count()): - elements.append(f'gpu_memory_{i}') - else: - for i in range(torch.cuda.device_count()): - elements.append(f'gpu_memory_{i}') - - return elements - - -def list_interface_input_elements(): - elements = [ - 'max_new_tokens', - 'auto_max_new_tokens', - 'max_tokens_second', - 'seed', - 'temperature', - 'top_p', - 'top_k', - 'typical_p', - 'epsilon_cutoff', - 'eta_cutoff', - 'repetition_penalty', - 'presence_penalty', - 'frequency_penalty', - 'repetition_penalty_range', - 'encoder_repetition_penalty', - 'no_repeat_ngram_size', - 'min_length', - 'do_sample', - 'penalty_alpha', - 'num_beams', - 'length_penalty', - 'early_stopping', - 'mirostat_mode', - 'mirostat_tau', - 'mirostat_eta', - 'grammar_string', - 'negative_prompt', - 'guidance_scale', - 'add_bos_token', - 'ban_eos_token', - 'custom_token_bans', - 'truncation_length', - 'custom_stopping_strings', - 'skip_special_tokens', - 'stream', - 'tfs', - 'top_a', - ] - - # Chat elements - elements += [ - 'textbox', - 'start_with', - 'character_menu', - 'history', - 'name1', - 'name2', - 'greeting', - 'context', - 'mode', - 'instruction_template', - 'name1_instruct', - 'name2_instruct', - 'context_instruct', - 'turn_template', - 'chat_style', - 'chat-instruct_command', - ] - - # Notebook/default elements - elements += [ - 'textbox-notebook', - 'textbox-default', - 'output_textbox', - 'prompt_menu-default', - 'prompt_menu-notebook', - ] - - # Model elements - elements += list_model_elements() - - return elements - - -def gather_interface_values(*args): - output = {} - for i, element in enumerate(list_interface_input_elements()): - output[element] = args[i] - - if not shared.args.multi_user: - shared.persistent_interface_state = output - - return output - - -def apply_interface_values(state, use_persistent=False): - if use_persistent: - state = shared.persistent_interface_state - - elements = list_interface_input_elements() - if len(state) == 0: - return [gr.update() for k in elements] # Dummy, do nothing - else: - return [state[k] if k in state else gr.update() for k in elements] - - -def save_settings(state, preset, instruction_template, extensions, show_controls): - output = copy.deepcopy(shared.settings) - exclude = ['name2', 'greeting', 'context', 'turn_template'] - for k in state: - if k in shared.settings and k not in exclude: - output[k] = state[k] - - output['preset'] = preset - output['prompt-default'] = state['prompt_menu-default'] - output['prompt-notebook'] = state['prompt_menu-notebook'] - output['character'] = state['character_menu'] - output['instruction_template'] = instruction_template - output['default_extensions'] = extensions - output['seed'] = int(output['seed']) - output['show_controls'] = show_controls - - return yaml.dump(output, sort_keys=False, width=float("inf")) - - -def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_class, interactive=True): - """ - Copied from https://github.com/AUTOMATIC1111/stable-diffusion-webui - """ - def refresh(): - refresh_method() - args = refreshed_args() if callable(refreshed_args) else refreshed_args - - for k, v in args.items(): - setattr(refresh_component, k, v) - - return gr.update(**(args or {})) - - refresh_button = gr.Button(refresh_symbol, elem_classes=elem_class, interactive=interactive) - refresh_button.click( - fn=refresh, - inputs=[], - outputs=[refresh_component] - ) - - return refresh_button diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Adobe Creative Cloud 5.0.0.354 Crack ((EXCLUSIVE)) Download!.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Adobe Creative Cloud 5.0.0.354 Crack ((EXCLUSIVE)) Download!.md deleted file mode 100644 index 8f04d3839f8095ad9676023c45d7e914c084f318..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Adobe Creative Cloud 5.0.0.354 Crack ((EXCLUSIVE)) Download!.md +++ /dev/null @@ -1,13 +0,0 @@ -

Adobe Creative Cloud 5.0.0.354 Crack Download!


DOWNLOAD ✸✸✸ https://bytlly.com/2uGx0I



- -To get this, you just need to download cs6 from the official website of Adobe and... Adobe Creative Cloud 5.0.0.354 Crack innovative cloud consists of savings that ... Adobe Photoshop CC - free download Adobe Photoshop CC 2015 ... -To download Photoshop CS6 software, as well as to install the program ... -It is not recommended to download CS6 from another source because in this case... -Adobe Photoshop CC 2015 has all the features of the most ... -Adobe Systems CS6 Crack - download and install for free. -Adobe CS6 Crack. -Adobe CS6 Crack is a program that will help you... -Adobe Photoshop CC - Free Download Adobe Photoshop CC 2015 ... 8a78ff9644
-
-
-

diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Ccvision Car Special V18 HOT.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Ccvision Car Special V18 HOT.md deleted file mode 100644 index 41a9d4c9f64b9b8fdc7abc30f1b6ec42ea6d74a0..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Ccvision Car Special V18 HOT.md +++ /dev/null @@ -1,91 +0,0 @@ -
-

Ccvision Car Special V18: A Comprehensive and Practical Resource for Car Lettering and Wrapping

- -

If you are a professional in the field of car lettering and wrapping, you know how important it is to have accurate and up-to-date vehicle outlines for your designs and presentations. You also know how challenging it can be to find the right vehicle model among thousands of options, and to work with different formats and software. That's why you need Ccvision Car Special V18, a comprehensive and practical resource that offers you more than 12,000 true-to-scale vehicle outlines from five views (front, rear, sides and roof), in AI, EPS, DXF, CDR (CDR also in 1:1) formats, suitable for any partial or full wrapping project.

-

Ccvision Car Special V18


Download Zip ✔✔✔ https://bytlly.com/2uGxGO



- -

What is Ccvision Car Special V18?

- -

Ccvision Car Special V18 is a product of creativ collection, a leading company in the field of vehicle outlines and graphics. It is a collection of vehicle outlines that covers all kinds of passenger cars, trucks, utility vehicles, buses, trains, trams, trailers, containers, planes, motorbikes and boats. It includes all the current models from different manufacturers and brands, as well as some classic and vintage vehicles. It is updated on a daily basis with new vehicles and revisions.

- -

Ccvision Car Special V18 is available in two modes of delivery: a manual with a DVD and a know-how brochure, or an online subscription. Both modes give you permanent access to all vehicles in the CAR-SPECIAL-Cloud, where you can search, view and download the vehicle outlines you need. You can also use the CAR-SIGNER ® tool to create and present your designs online, the CAR 3D tool to show your designs in 3D perspective, and the CAR-SPECIAL fast-measuring tool to measure the dimensions of any vehicle.

- -

What are the benefits of Ccvision Car Special V18?

- -

Ccvision Car Special V18 has several benefits that make it an indispensable tool for car lettering and wrapping professionals:

-

- -
    -
  • It saves you time and money: You don't have to waste time searching for vehicle outlines on different sources or paying for individual downloads. You have access to thousands of vehicle outlines in one place, ready to use for your projects.
  • -
  • It improves your quality and accuracy: You don't have to worry about scaling or fitting issues. You have true-to-scale vehicle outlines that match the real dimensions and shapes of the vehicles. You can also compare different models or versions with ease.
  • -
  • It enhances your creativity and flexibility: You don't have to limit yourself to standard or common vehicles. You have a wide range of vehicles to choose from, including some rare or exotic models. You can also work with different formats and software according to your preferences.
  • -
  • It boosts your reputation and credibility: You don't have to compromise on your professionalism or presentation. You have high-quality vehicle outlines that impress your clients and showcase your skills. You can also use the CAR-SIGNER ® tool to create realistic mock-ups online.
  • -
- -

In conclusion, Ccvision Car Special V18 is a comprehensive and practical resource that offers you more than 12,000 true-to-scale vehicle outlines from five views, in AI, EPS, DXF, CDR (CDR also in 1:1) formats, suitable for any car lettering and wrapping project. It is updated on a daily basis with new vehicles and revisions. It is available in two modes of delivery: a manual with a DVD and a know-how brochure, or an online subscription. Both modes give you permanent access to all vehicles in the CAR-SPECIAL-Cloud, where you can search, view and download the vehicle outlines you need. You can also use the CAR-SIGNER ® tool to create and present your designs online, the CAR 3D tool to show your designs in 3D perspective, and the CAR-SPECIAL fast-measuring tool to measure the dimensions of any vehicle.

-

How to use Ccvision Car Special V18?

- -

Ccvision Car Special V18 is very easy to use, whether you choose the manual with the DVD and the know-how brochure, or the online subscription. Here are the steps to follow:

- -
    -
  1. Access the CAR-SPECIAL-Cloud from the web browser of your choice. If you have the manual with the DVD, you will need to enter the license code that comes with it. If you have the online subscription, you will need to enter your username and password.
  2. -
  3. Search for the vehicle you want by using the filters and options available. You can filter by manufacturer, model, version, year, type, country or category. You can also use the search box to enter keywords or codes.
  4. -
  5. Select the vehicle you want and view it as a large preview with all the details and dimensions. You can also compare it with other models or versions, or with your own photos.
  6. -
  7. Download the vehicle outline in the format and size you prefer. You can choose between AI, EPS, DXF or CDR (CDR also in 1:1) formats, and between 1:20 or 1:1 scales. You can also download a PDF file with all the information about the vehicle.
  8. -
  9. Open the vehicle outline with your software of choice and start designing your car lettering or wrapping. You can also use the CAR-SIGNER ® tool to create your design online and present it to your client in a realistic way.
  10. -
- -

Ccvision Car Special V18 is compatible with any software that can handle vector graphics, such as Adobe Illustrator, CorelDRAW, Inkscape or AutoCAD. You can also use it with any cutting plotter or printer that supports these formats.

- -

What are some examples of car lettering and wrapping projects made with Ccvision Car Special V18?

- -

Ccvision Car Special V18 has been used by thousands of car lettering and wrapping professionals around the world to create amazing and impressive projects for their clients. Here are some examples of what you can do with Ccvision Car Special V18:

- -
    -
  • Create a custom logo and slogan for your business and apply it to your car or fleet of vehicles.
  • -
  • Design a colorful and eye-catching full wrap for your car or truck that showcases your products or services.
  • -
  • Make a partial wrap for your car or van that adds some style and personality to your vehicle.
  • -
  • Use a matte or glossy finish for your wrap to create a contrast or a harmony with your vehicle's original color.
  • -
  • Add some graphics or patterns to your wrap to make it stand out from the crowd.
  • -
- -

With Ccvision Car Special V18, you can unleash your creativity and imagination and create car lettering and wrapping projects that suit your needs and preferences.

-

How to get Ccvision Car Special V18?

- -

If you want to get Ccvision Car Special V18, you have two options: you can either buy the manual with the DVD and the know-how brochure, or you can subscribe to the online service. Both options have different prices and features, so you can choose the one that suits you best.

- -

The manual with the DVD and the know-how brochure costs EUR 399 and includes more than 11,800 vehicle outlines in 5 views, in AI, EPS, CDR (CDR also in 1:1) and DXF formats. It also includes a printed catalogue with all the vehicles and a brochure with practical tips and tricks for car lettering and wrapping. You can order it online from the ccvision website or from other distributors. You will also get access to the CAR-SPECIAL-Cloud, where you can download all the current vehicles and use the CAR-SIGNER ® tool, the CAR 3D tool and the CAR-SPECIAL fast-measuring tool. You will also receive an annual update with all the new models and revisions for only EUR 199 per year.

- -

The online subscription costs EUR 299 in the first year and EUR 159 per year afterwards. It gives you access to more than 12,000 vehicle outlines in 5 views, in AI, EPS, DXF and CDR (CDR also in 1:1) formats. You can download up to 10 vehicles per day and 60 per month from the CAR-SPECIAL-Cloud, where you can also use the CAR-SIGNER ® tool, the CAR 3D tool and the CAR-SPECIAL fast-measuring tool. You can subscribe online from the ccvision website or from other distributors. You can cancel your subscription at any time with a one-month notice.

- -

What are some testimonials from Ccvision Car Special V18 users?

- -

Ccvision Car Special V18 has received many positive testimonials from users who have used it for their car lettering and wrapping projects. Here are some of them:

- -
-

"I have been using Ccvision Car Special for years and I am very satisfied with it. It is a very complete and reliable resource that saves me a lot of time and hassle. I can find any vehicle I need in a few clicks and download it in the format I want. The vehicle outlines are very accurate and detailed, which makes my designs look professional and realistic."

-Car lettering and wrapping professional -
- -
-

"Ccvision Car Special is a great tool for car lettering and wrapping. It has a huge variety of vehicles to choose from, including some rare and exotic models that I can't find anywhere else. The vehicle outlines are true-to-scale and easy to work with. I also love the CAR-SIGNER ® tool that allows me to create and present my designs online in a realistic way."

-Car lettering and wrapping enthusiast -
- -
-

"Ccvision Car Special is an indispensable resource for car lettering and wrapping. It has everything I need to create amazing and impressive projects for my clients. The vehicle outlines are high-quality and up-to-date, which gives me an edge over my competitors. I also appreciate the CAR 3D tool that shows my designs in 3D perspective, which helps me to convince my clients."

-Car lettering and wrapping business owner -
- -

These testimonials show that Ccvision Car Special V18 is a comprehensive and practical resource that offers more than 12,000 true-to-scale vehicle outlines from five views, in AI, EPS, DXF, CDR (CDR also in 1:1) formats, suitable for any car lettering and wrapping project. It is updated on a daily basis with new vehicles and revisions. It is available in two modes of delivery: a manual with a DVD and a know-how brochure, or an online subscription. Both modes give you permanent access to all vehicles in the CAR-SPECIAL-Cloud, where you can search, view and download the vehicle outlines you need. You can also use the CAR-SIGNER ® tool to create and present your designs online, the CAR 3D tool to show your designs in 3D perspective, and the CAR-SPECIAL fast-measuring tool to measure the dimensions of any vehicle.

-

Conclusion

- -

Ccvision Car Special V18 is a product of creativ collection, a leading company in the field of vehicle outlines and graphics. It is a collection of vehicle outlines that covers all kinds of passenger cars, trucks, utility vehicles, buses, trains, trams, trailers, containers, planes, motorbikes and boats. It includes all the current models from different manufacturers and brands, as well as some classic and vintage vehicles. It is updated on a daily basis with new vehicles and revisions.

- -

Ccvision Car Special V18 is available in two modes of delivery: a manual with a DVD and a know-how brochure, or an online subscription. Both modes give you permanent access to all vehicles in the CAR-SPECIAL-Cloud, where you can search, view and download the vehicle outlines you need. You can also use the CAR-SIGNER ® tool to create and present your designs online, the CAR 3D tool to show your designs in 3D perspective, and the CAR-SPECIAL fast-measuring tool to measure the dimensions of any vehicle.

- -

Ccvision Car Special V18 has several benefits that make it an indispensable tool for car lettering and wrapping professionals. It saves you time and money, improves your quality and accuracy, enhances your creativity and flexibility, and boosts your reputation and credibility. It has been used by thousands of car lettering and wrapping professionals around the world to create amazing and impressive projects for their clients.

- -

If you are a professional in the field of car lettering and wrapping, you need Ccvision Car Special V18, a comprehensive and practical resource that offers you more than 12,000 true-to-scale vehicle outlines from five views, in AI, EPS, DXF, CDR (CDR also in 1:1) formats, suitable for any car lettering and wrapping project. You can order it online from the ccvision website or from other distributors. You can also subscribe to the online service and cancel it at any time with a one-month notice. You will not regret it!

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Devils Toy Download For Pc [portable] BEST.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Devils Toy Download For Pc [portable] BEST.md deleted file mode 100644 index 99ca37591f39b0d492234deaa2d1e7742a88ed44..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Devils Toy Download For Pc [portable] BEST.md +++ /dev/null @@ -1,8 +0,0 @@ -

Devil's Toy download for pc [portable]


Download Zip 🆓 https://bytlly.com/2uGwOt



-
-USB outlet. 2. It is portable and small, suitable for students, relax, and place outdoor, study, play, environment. 3. Human body suface temperature, promotes the elimination of body heat. 4. 3 colors lights, the night and day changing function. 5. High working efficiency. 6. Efficient energy source. 7. 3 speeds. 8. Easy to plug in and run. 9. LED lighting. 10. Indicator lights. 11. Hand grip handle and thumb strap. 12. Working hours: (5-15)V / (5-20)V / (5-25)V according to different requirements (10V-50V, 100V-240V) 13. Warning: when opening the circuit breaker, avoid touching the light switch, which will lead to fire and burn. 14. Simple structure, easy to assemble, stable, long-lasting, convenient to use. 15. Reliable and safe. 16. Non-toxic material. - -Travel Fan Light Cushion With CD And Bluetooth Speaker,Music Kit,Portable Luggage:Add A Way To Enjoy Your Travel,Create A Fun On Your Day Off,Convenient Carry Carry,Portable Luggage:Add A Way To Enjoy Your Travel,Create A Fun On Your Day Off,Convenient Carry Carry,Stylish And Durable Luggage Case,Keep Your Smartphone Safe,Convenient Carry Carry,Travel Fan Light Cushion With CD And Bluetooth Speaker,Travel Fan Light Cushion With CD And Bluetooth Speaker Portable Luggage:Add A Way To Enjoy Your Travel,Create A Fun On Your Day Off,Convenient Carry Carry,Portable Luggage:Add A Way To Enjoy Your Travel,Create A Fun On Your Day Off,Convenient Carry Carry,Stylish And Durable Luggage Case,Keep Your Smartphone Safe,Convenient Carry Carry,Travel Fan Light Cushion With CD And Bluetooth Speaker,Travel Fan Light Cushion With CD And Bluetooth Speaker Portable Luggage:Add A Way To Enjoy Your Travel,Create A Fun On Your Day Off,Convenient Carry Carry,Portable Luggage:Add A Way To Enjoy Your Travel,Create A Fun On Your Day Off,Convenient Carry Carry,Stylish And Durable Luggage Case,Keep Your Smartphone Safe,Convenient Carry Carry,Travel Fan Light Cushion With CD And Bluetooth Speaker,Travel Fan Light Cushion With CD And Bluetooth Speaker Portable Luggage:Add A Way To Enjoy Your 4fefd39f24
-
-
-

diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Kuruthipunal _VERIFIED_ Download Movie 1080p Torrent.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Kuruthipunal _VERIFIED_ Download Movie 1080p Torrent.md deleted file mode 100644 index 92f84d5158eacf6366661bb85af1e8ef8ca670c1..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Kuruthipunal _VERIFIED_ Download Movie 1080p Torrent.md +++ /dev/null @@ -1,14 +0,0 @@ -

Kuruthipunal Download Movie 1080p Torrent


Download File ✏ ✏ ✏ https://bytlly.com/2uGxeB



-
-Your browser is out of date! - -Some resources on this site require JavaScript to function correctly. Please update your browser or enable JavaScript if you are unable to use the functionality of this website due to security reasons.Generally, the sea water flowing in the sea channel has a velocity of about 2-4 km/h. In order to maintain the reliability of power of a hydroelectric power generation system, it is required that the sea water which flows in the sea channel for a long time be continuously flowed. Further, when a relative slip occurs due to a reverse water flow or a water level fluctuation, it is required that the sea water which flows in the sea channel for a long time be continuously flowed, because the flow and capacity of the hydroelectric power generation system can be controlled. - -However, as described above, the sea water flows in the sea channel at a velocity of about 2-4 km/h. Therefore, when the sea water which flows in the sea channel for a long time is continuously flowed, the sea water is moved toward a suction side of the hydroelectric power generation system by a distance of about several km. As a result, the distance to an intake pipe of the hydroelectric power generation system is increased. That is, the intake pipe needs to be provided at a long distance from the sea channel in order to continuously flow the sea water in the sea channel for a long time. Accordingly, the length of a sea water intake pipe needs to be increased in the related art, and therefore, the configuration of the hydroelectric power generation system becomes complicated, the costs are increased, and it is difficult to construct a structure of the system. Further, it is not easy to repair the hydroelectric power generation system. - -In order to resolve such problems in the related art, for example, a sea water intake pipe includes an intake part for sucking sea water from a sea water intake part provided on an upper end thereof, and a lateral part connected with the intake part and disposed on a water surface. For example, in JP-A-2004-40201, a structure in which a lateral part is formed in a shape protruding above the surface of the sea water is adopted. By adopting such a configuration, even when the sea water flows in a part of the lateral part, the sea water can be sucked from a full intake part. Thus, there is an advantage that the intake pipe is relatively short and the cost is reduced.Pages - -How to get ready for a new wine 4fefd39f24
-
-
-

diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Mega Pack Styles For Proshow Producer Keygen [WORK].md b/spaces/lincquiQcaudo/Top-20-Diffusion/Mega Pack Styles For Proshow Producer Keygen [WORK].md deleted file mode 100644 index 904390afd3a3df79a3d65c0776407c22825e8fc3..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Mega Pack Styles For Proshow Producer Keygen [WORK].md +++ /dev/null @@ -1,6 +0,0 @@ -

mega pack styles for proshow producer keygen


Download ►►► https://bytlly.com/2uGytl



-
- d5da3c52bf
-
-
-

diff --git a/spaces/lkji/bingo/README.md b/spaces/lkji/bingo/README.md deleted file mode 100644 index 5d6936218874c647b5d22e13ad4be7edb8936f92..0000000000000000000000000000000000000000 --- a/spaces/lkji/bingo/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: bingo -emoji: 😊 -colorFrom: red -colorTo: red -sdk: docker -license: mit -duplicated_from: hf4all/bingo ---- - -
- -# Bingo - -Bingo,一个让你呼吸顺畅 New Bing。 - -高度还原 New Bing 网页版的主要操作,国内可用,兼容绝大多数微软 Bing AI 的功能,可自行部署使用。 - -![Github stars](https://badgen.net/github/stars/weaigc/bingo?icon=github&label=stars) -![Gthub issues](https://img.shields.io/github/issues/weaigc/bingo) -[![docker build](https://github.com/weaigc/bingo/actions/workflows/docker.yml/badge.svg)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![docker hub](https://badgen.net/docker/size/weaigc/bingo?icon=docker&label=image%20size)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![MIT License](https://img.shields.io/badge/license-MIT-97c50f)](https://github.com/weaigc/bingo/blob/main/license) - -问题反馈请前往 https://github.com/weaigc/bingo/issues -
- - diff --git a/spaces/lllqqq/so-vits-svc-models-pcr/inference/infer_tool.py b/spaces/lllqqq/so-vits-svc-models-pcr/inference/infer_tool.py deleted file mode 100644 index aa08db415a9b0af97a5d726d1f7e61834e1c4e1c..0000000000000000000000000000000000000000 --- a/spaces/lllqqq/so-vits-svc-models-pcr/inference/infer_tool.py +++ /dev/null @@ -1,407 +0,0 @@ -import hashlib -import io -import json -import logging -import os -import time -from pathlib import Path -from inference import slicer -import gc - -import librosa -import numpy as np -# import onnxruntime -import soundfile -import torch -import torchaudio - -import cluster -import utils -from models import SynthesizerTrn - -from diffusion.unit2mel import load_model_vocoder -import yaml - -logging.getLogger('matplotlib').setLevel(logging.WARNING) - - -def read_temp(file_name): - if not os.path.exists(file_name): - with open(file_name, "w") as f: - f.write(json.dumps({"info": "temp_dict"})) - return {} - else: - try: - with open(file_name, "r") as f: - data = f.read() - data_dict = json.loads(data) - if os.path.getsize(file_name) > 50 * 1024 * 1024: - f_name = file_name.replace("\\", "/").split("/")[-1] - print(f"clean {f_name}") - for wav_hash in list(data_dict.keys()): - if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600: - del data_dict[wav_hash] - except Exception as e: - print(e) - print(f"{file_name} error,auto rebuild file") - data_dict = {"info": "temp_dict"} - return data_dict - - -def write_temp(file_name, data): - with open(file_name, "w") as f: - f.write(json.dumps(data)) - - -def timeit(func): - def run(*args, **kwargs): - t = time.time() - res = func(*args, **kwargs) - print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t)) - return res - - return run - - -def format_wav(audio_path): - if Path(audio_path).suffix == '.wav': - return - raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None) - soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate) - - -def get_end_file(dir_path, end): - file_lists = [] - for root, dirs, files in os.walk(dir_path): - files = [f for f in files if f[0] != '.'] - dirs[:] = [d for d in dirs if d[0] != '.'] - for f_file in files: - if f_file.endswith(end): - file_lists.append(os.path.join(root, f_file).replace("\\", "/")) - return file_lists - - -def get_md5(content): - return hashlib.new("md5", content).hexdigest() - -def fill_a_to_b(a, b): - if len(a) < len(b): - for _ in range(0, len(b) - len(a)): - a.append(a[0]) - -def mkdir(paths: list): - for path in paths: - if not os.path.exists(path): - os.mkdir(path) - -def pad_array(arr, target_length): - current_length = arr.shape[0] - if current_length >= target_length: - return arr - else: - pad_width = target_length - current_length - pad_left = pad_width // 2 - pad_right = pad_width - pad_left - padded_arr = np.pad(arr, (pad_left, pad_right), 'constant', constant_values=(0, 0)) - return padded_arr - -def split_list_by_n(list_collection, n, pre=0): - for i in range(0, len(list_collection), n): - yield list_collection[i-pre if i-pre>=0 else i: i + n] - - -class F0FilterException(Exception): - pass - -class Svc(object): - def __init__(self, net_g_path, config_path, - device=None, - cluster_model_path="logs/44k/kmeans_10000.pt", - nsf_hifigan_enhance = False, - diffusion_model_path="logs/44k/diffusion/model_0.pt", - diffusion_config_path="configs/diffusion.yaml", - shallow_diffusion = False, - only_diffusion = False, - ): - self.net_g_path = net_g_path - self.only_diffusion = only_diffusion - self.shallow_diffusion = shallow_diffusion - if device is None: - # self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") - self.dev = torch.device("cpu") - else: - self.dev = torch.device(device) - self.net_g_ms = None - if not self.only_diffusion: - self.hps_ms = utils.get_hparams_from_file(config_path) - self.target_sample = self.hps_ms.data.sampling_rate - self.hop_size = self.hps_ms.data.hop_length - self.spk2id = self.hps_ms.spk - try: - self.speech_encoder = self.hps_ms.model.speech_encoder - except Exception as e: - self.speech_encoder = 'vec768l12' - - self.nsf_hifigan_enhance = nsf_hifigan_enhance - if self.shallow_diffusion or self.only_diffusion: - if os.path.exists(diffusion_model_path) and os.path.exists(diffusion_model_path): - self.diffusion_model,self.vocoder,self.diffusion_args = load_model_vocoder(diffusion_model_path,self.dev,config_path=diffusion_config_path) - if self.only_diffusion: - self.target_sample = self.diffusion_args.data.sampling_rate - self.hop_size = self.diffusion_args.data.block_size - self.spk2id = self.diffusion_args.spk - self.speech_encoder = self.diffusion_args.data.encoder - else: - print("No diffusion model or config found. Shallow diffusion mode will False") - self.shallow_diffusion = self.only_diffusion = False - - # load hubert and model - if not self.only_diffusion: - self.load_model() - self.hubert_model = utils.get_speech_encoder(self.speech_encoder,device=self.dev) - self.volume_extractor = utils.Volume_Extractor(self.hop_size) - else: - self.hubert_model = utils.get_speech_encoder(self.diffusion_args.data.encoder,device=self.dev) - self.volume_extractor = utils.Volume_Extractor(self.diffusion_args.data.block_size) - - if os.path.exists(cluster_model_path): - self.cluster_model = cluster.get_cluster_model(cluster_model_path) - if self.shallow_diffusion : self.nsf_hifigan_enhance = False - if self.nsf_hifigan_enhance: - from modules.enhancer import Enhancer - self.enhancer = Enhancer('nsf-hifigan', 'pretrain/nsf_hifigan/model',device=self.dev) - - def load_model(self): - # get model configuration - self.net_g_ms = SynthesizerTrn( - self.hps_ms.data.filter_length // 2 + 1, - self.hps_ms.train.segment_size // self.hps_ms.data.hop_length, - **self.hps_ms.model) - _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None) - if "half" in self.net_g_path and torch.cuda.is_available(): - _ = self.net_g_ms.half().eval().to(self.dev) - else: - _ = self.net_g_ms.eval().to(self.dev) - - - - def get_unit_f0(self, wav, tran, cluster_infer_ratio, speaker, f0_filter ,f0_predictor,cr_threshold=0.05): - - f0_predictor_object = utils.get_f0_predictor(f0_predictor,hop_length=self.hop_size,sampling_rate=self.target_sample,device=self.dev,threshold=cr_threshold) - - f0, uv = f0_predictor_object.compute_f0_uv(wav) - if f0_filter and sum(f0) == 0: - raise F0FilterException("No voice detected") - f0 = torch.FloatTensor(f0).to(self.dev) - uv = torch.FloatTensor(uv).to(self.dev) - - f0 = f0 * 2 ** (tran / 12) - f0 = f0.unsqueeze(0) - uv = uv.unsqueeze(0) - - wav16k = librosa.resample(wav, orig_sr=self.target_sample, target_sr=16000) - wav16k = torch.from_numpy(wav16k).to(self.dev) - c = self.hubert_model.encoder(wav16k) - c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1]) - - if cluster_infer_ratio !=0: - cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T - cluster_c = torch.FloatTensor(cluster_c).to(self.dev) - c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c - - c = c.unsqueeze(0) - return c, f0, uv - - def infer(self, speaker, tran, raw_path, - cluster_infer_ratio=0, - auto_predict_f0=False, - noice_scale=0.4, - f0_filter=False, - f0_predictor='pm', - enhancer_adaptive_key = 0, - cr_threshold = 0.05, - k_step = 100 - ): - - speaker_id = self.spk2id.get(speaker) - if not speaker_id and type(speaker) is int: - if len(self.spk2id.__dict__) >= speaker: - speaker_id = speaker - sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0) - wav, sr = librosa.load(raw_path, sr=self.target_sample) - c, f0, uv = self.get_unit_f0(wav, tran, cluster_infer_ratio, speaker, f0_filter,f0_predictor,cr_threshold=cr_threshold) - if "half" in self.net_g_path and torch.cuda.is_available(): - c = c.half() - with torch.no_grad(): - start = time.time() - if not self.only_diffusion: - audio,f0 = self.net_g_ms.infer(c, f0=f0, g=sid, uv=uv, predict_f0=auto_predict_f0, noice_scale=noice_scale) - audio = audio[0,0].data.float() - if self.shallow_diffusion: - audio_mel = self.vocoder.extract(audio[None,:],self.target_sample) - else: - audio = torch.FloatTensor(wav).to(self.dev) - audio_mel = None - if self.only_diffusion or self.shallow_diffusion: - vol = self.volume_extractor.extract(audio[None,:])[None,:,None].to(self.dev) - f0 = f0[:,:,None] - c = c.transpose(-1,-2) - audio_mel = self.diffusion_model( - c, - f0, - vol, - spk_id = sid, - spk_mix_dict = None, - gt_spec=audio_mel, - infer=True, - infer_speedup=self.diffusion_args.infer.speedup, - method=self.diffusion_args.infer.method, - k_step=k_step) - audio = self.vocoder.infer(audio_mel, f0).squeeze() - if self.nsf_hifigan_enhance: - audio, _ = self.enhancer.enhance( - audio[None,:], - self.target_sample, - f0[:,:,None], - self.hps_ms.data.hop_length, - adaptive_key = enhancer_adaptive_key) - use_time = time.time() - start - print("vits use time:{}".format(use_time)) - return audio, audio.shape[-1] - - def clear_empty(self): - # clean up vram - torch.cuda.empty_cache() - - def unload_model(self): - # unload model - self.net_g_ms = self.net_g_ms.to("cpu") - del self.net_g_ms - if hasattr(self,"enhancer"): - self.enhancer.enhancer = self.enhancer.enhancer.to("cpu") - del self.enhancer.enhancer - del self.enhancer - gc.collect() - - def slice_inference(self, - raw_audio_path, - spk, - tran, - slice_db, - cluster_infer_ratio, - auto_predict_f0, - noice_scale, - pad_seconds=0.5, - clip_seconds=0, - lg_num=0, - lgr_num =0.75, - f0_predictor='pm', - enhancer_adaptive_key = 0, - cr_threshold = 0.05, - k_step = 100 - ): - wav_path = Path(raw_audio_path).with_suffix('.wav') - chunks = slicer.cut(wav_path, db_thresh=slice_db) - audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks) - per_size = int(clip_seconds*audio_sr) - lg_size = int(lg_num*audio_sr) - lg_size_r = int(lg_size*lgr_num) - lg_size_c_l = (lg_size-lg_size_r)//2 - lg_size_c_r = lg_size-lg_size_r-lg_size_c_l - lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0 - - audio = [] - for (slice_tag, data) in audio_data: - print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======') - # padd - length = int(np.ceil(len(data) / audio_sr * self.target_sample)) - if slice_tag: - print('jump empty segment') - _audio = np.zeros(length) - audio.extend(list(pad_array(_audio, length))) - continue - if per_size != 0: - datas = split_list_by_n(data, per_size,lg_size) - else: - datas = [data] - for k,dat in enumerate(datas): - per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample)) if clip_seconds!=0 else length - if clip_seconds!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======') - # padd - pad_len = int(audio_sr * pad_seconds) - dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])]) - raw_path = io.BytesIO() - soundfile.write(raw_path, dat, audio_sr, format="wav") - raw_path.seek(0) - out_audio, out_sr = self.infer(spk, tran, raw_path, - cluster_infer_ratio=cluster_infer_ratio, - auto_predict_f0=auto_predict_f0, - noice_scale=noice_scale, - f0_predictor = f0_predictor, - enhancer_adaptive_key = enhancer_adaptive_key, - cr_threshold = cr_threshold, - k_step = k_step - ) - _audio = out_audio.cpu().numpy() - pad_len = int(self.target_sample * pad_seconds) - _audio = _audio[pad_len:-pad_len] - _audio = pad_array(_audio, per_length) - if lg_size!=0 and k!=0: - lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr_num != 1 else audio[-lg_size:] - lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr_num != 1 else _audio[0:lg_size] - lg_pre = lg1*(1-lg)+lg2*lg - audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr_num != 1 else audio[0:-lg_size] - audio.extend(lg_pre) - _audio = _audio[lg_size_c_l+lg_size_r:] if lgr_num != 1 else _audio[lg_size:] - audio.extend(list(_audio)) - return np.array(audio) - -class RealTimeVC: - def __init__(self): - self.last_chunk = None - self.last_o = None - self.chunk_len = 16000 # chunk length - self.pre_len = 3840 # cross fade length, multiples of 640 - - # Input and output are 1-dimensional numpy waveform arrays - - def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path, - cluster_infer_ratio=0, - auto_predict_f0=False, - noice_scale=0.4, - f0_filter=False): - - import maad - audio, sr = torchaudio.load(input_wav_path) - audio = audio.cpu().numpy()[0] - temp_wav = io.BytesIO() - if self.last_chunk is None: - input_wav_path.seek(0) - - audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path, - cluster_infer_ratio=cluster_infer_ratio, - auto_predict_f0=auto_predict_f0, - noice_scale=noice_scale, - f0_filter=f0_filter) - - audio = audio.cpu().numpy() - self.last_chunk = audio[-self.pre_len:] - self.last_o = audio - return audio[-self.chunk_len:] - else: - audio = np.concatenate([self.last_chunk, audio]) - soundfile.write(temp_wav, audio, sr, format="wav") - temp_wav.seek(0) - - audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav, - cluster_infer_ratio=cluster_infer_ratio, - auto_predict_f0=auto_predict_f0, - noice_scale=noice_scale, - f0_filter=f0_filter) - - audio = audio.cpu().numpy() - ret = maad.util.crossfade(self.last_o, audio, self.pre_len) - self.last_chunk = audio[-self.pre_len:] - self.last_o = audio - return ret[self.chunk_len:2 * self.chunk_len] - \ No newline at end of file diff --git a/spaces/ma-xu/LIVE/thrust/dependencies/cub/experimental/spmv_script.sh b/spaces/ma-xu/LIVE/thrust/dependencies/cub/experimental/spmv_script.sh deleted file mode 100644 index f43204315a3d136e50c4fc8bee3d57622fa5c7be..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/dependencies/cub/experimental/spmv_script.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash - -for i in 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 -do - echo `date`, `$1 --dense=$i $2 $3 $4 $5 $6 $7` -done - -echo -echo - -for i in `ls /home/dumerrill/graphs/spmv/*.mtx` -do - if [[ ( "`head -n 50 $i | grep complex`" = "" ) && ( "`head -n 50 $i | grep array`" = "" ) ]] - then - echo `date`, `$1 --mtx=$i $2 $3 $4 $5 $6 $7 2>/dev/null` - fi -done - -echo -echo - -for i in `ls /scratch/dumerrill/graphs/mtx/*.mtx` -#for i in `ls /cygdrive/w/Dev/UFget/mtx/*.mtx` -do - if [[ ( "`head -n 50 $i | grep complex`" = "" ) && ( "`head -n 50 $i | grep array`" = "" ) ]] - then - echo `date`, `$1 --mtx=$i $2 $3 $4 $5 $6 $7 2>/dev/null` - fi -done - diff --git a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/transform_scan.h b/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/transform_scan.h deleted file mode 100644 index 3a05c7eeed9afc549d9d6bd1e28a64e67b4a4578..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/transform_scan.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a fill of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// the purpose of this header is to #include the transform_scan.h header -// of the sequential, host, and device systems. It should be #included in any -// code which uses adl to dispatch transform_scan - -#include - -// SCons can't see through the #defines below to figure out what this header -// includes, so we fake it out by specifying all possible files we might end up -// including inside an #if 0. -#if 0 -#include -#include -#include -#include -#endif - -#define __THRUST_HOST_SYSTEM_TRANSFORM_SCAN_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/transform_scan.h> -#include __THRUST_HOST_SYSTEM_TRANSFORM_SCAN_HEADER -#undef __THRUST_HOST_SYSTEM_TRANSFORM_SCAN_HEADER - -#define __THRUST_DEVICE_SYSTEM_TRANSFORM_SCAN_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/transform_scan.h> -#include __THRUST_DEVICE_SYSTEM_TRANSFORM_SCAN_HEADER -#undef __THRUST_DEVICE_SYSTEM_TRANSFORM_SCAN_HEADER - diff --git a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/generic/binary_search.h b/spaces/ma-xu/LIVE/thrust/thrust/system/detail/generic/binary_search.h deleted file mode 100644 index 8cd85c63f30b2484d7d9c2111d6e51f957a8a282..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/generic/binary_search.h +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/*! \file binary_search.h - * \brief Generic implementations of binary search functions. - */ - -#pragma once - -#include -#include - -namespace thrust -{ -namespace system -{ -namespace detail -{ -namespace generic -{ - - -template -__host__ __device__ -ForwardIterator lower_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - const T& value); - -template -__host__ __device__ -ForwardIterator lower_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - const T& value, - StrictWeakOrdering comp); - - -template -__host__ __device__ -ForwardIterator upper_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - const T& value); - -template -__host__ __device__ -ForwardIterator upper_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - const T& value, - StrictWeakOrdering comp); - - -template -__host__ __device__ -bool binary_search(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - const T& value); - -template -__host__ __device__ -bool binary_search(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - const T& value, - StrictWeakOrdering comp); - - -template -__host__ __device__ -OutputIterator lower_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - InputIterator values_begin, - InputIterator values_end, - OutputIterator output); - - -template -__host__ __device__ -OutputIterator lower_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - InputIterator values_begin, - InputIterator values_end, - OutputIterator output, - StrictWeakOrdering comp); - - -template -__host__ __device__ -OutputIterator upper_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - InputIterator values_begin, - InputIterator values_end, - OutputIterator output); - - -template -__host__ __device__ -OutputIterator upper_bound(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - InputIterator values_begin, - InputIterator values_end, - OutputIterator output, - StrictWeakOrdering comp); - - -template -__host__ __device__ -OutputIterator binary_search(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - InputIterator values_begin, - InputIterator values_end, - OutputIterator output); - - -template -__host__ __device__ -OutputIterator binary_search(thrust::execution_policy &exec, - ForwardIterator begin, - ForwardIterator end, - InputIterator values_begin, - InputIterator values_end, - OutputIterator output, - StrictWeakOrdering comp); - - -template -__host__ __device__ -thrust::pair -equal_range(thrust::execution_policy &exec, - ForwardIterator first, - ForwardIterator last, - const LessThanComparable &value); - - -template -__host__ __device__ -thrust::pair -equal_range(thrust::execution_policy &exec, - ForwardIterator first, - ForwardIterator last, - const LessThanComparable &value, - StrictWeakOrdering comp); - - - -} // end namespace generic -} // end namespace detail -} // end namespace system -} // end namespace thrust - -#include - diff --git a/spaces/mauriciogtec/w2vec-app/app.py b/spaces/mauriciogtec/w2vec-app/app.py deleted file mode 100644 index 6623e4ff74e63e17846fc6b64f2314ec860029d5..0000000000000000000000000000000000000000 --- a/spaces/mauriciogtec/w2vec-app/app.py +++ /dev/null @@ -1,306 +0,0 @@ -from shiny import App, ui, render, reactive -from shiny.ui import HTML, tags -import shinyswatch - -import torch -import pandas as pd -import numpy as np -import io -import torch.nn.functional as F - -from utils import load_training_data, load_models - -MONTHS = { - 0: "Jan", - 1: "Feb", - 2: "Mar", - 3: "Apr", - 4: "May", - 5: "Jun", - 6: "Jul", - 7: "Aug", - 8: "Sep", - 9: "Oct", - 10: "Nov", - 11: "Dec", -} - -YEARS = list(range(2000, 2015)) - -RESOLUTIONS = { - "0": "Local", - "1": "32 km", - "3": "96 km", - "5": "160 km", - "7": "224 km", - "9": "288 km", -} - -WCOLS = { - "air.2m.mon.mean.nc": "temperature at 2m", - # "air.sfc.mon.mean.nc": "surface temperature", - "apcp.mon.mean.nc": "total precipitation", - # "acpcp.mon.mean.nc": "acc. convective precip", - # "tcdc.mon.mean.nc": "total cloud cover", - # "dswrf.mon.mean.nc": "down short rads flux", - # "hpbl.mon.mean.nc": "planet boundary layer height", - "rhum.2m.mon.mean.nc": "relative humidity", - "vwnd.10m.mon.mean.nc": "(north-south) wind component", - "uwnd.10m.mon.mean.nc": "(east-west) wind component", -} - -# RESOLUTION CONSTANTS -NROW = 128 -NCOL = 256 -XMIN = -135.0 -XMAX = -60.0 -YMIN = 20.0 -YMAX = 52.0 -DLON = (XMAX - XMIN) / NCOL -DLAT = (YMIN - YMAX) / NROW - -# Load non-reactivelye -C, NAMES, Y, M = load_training_data( - path="data/training_data.pkl", - standardize_so4=True, - log_so4=True, - year_averages=True, -) -ND = C.shape[1] -_, _, YRAW, MRAW = load_training_data(path="data/training_data.pkl") - -DIRS = { - "1": f"./data/weights/h1_w2vec", - "3": f"./data/weights/h3_w2vec", - "5": f"./data/weights/h5_w2vec", - "7": f"./data/weights/h7_w2vec", - "9": f"./data/weights/h9_w2vec", -} -MODELS = load_models(DIRS, prefix="h", nd=ND) - - -multicol_html = tags.head( - tags.style( - HTML( - ".multicol {" - # "height: 150px; " - "-webkit-column-count: 3;" # chrome, safari, opera - "-moz-column-count: 3;" # firefox - "column-count: 3;" - "-moz-column-fill: auto;" - "-column-fill: auto;" - ) - ) -) - -instructions = f""" -### Instructions - -Upload a CSV file with columns (id, lat, lon) using the `Browse` button on the sidebar. -Below is an example of the contents of the file: - - -``` -id,lat,lon -0,47.5,-122.5 -1,47.5,-122.25 -2,47.5,-122.0 -3,47.5,-121.75 -4,47.5,-121.5 -``` - - -The id column can be any identifier, or the column can be ommited, in which case the row number will be used as the id. -Make sure that the latitude is before the longitude column in the CSV file. The valid range for latitude is -{YMIN} to {YMAX} and longitude is {XMIN} to {XMAX}, which cover the contiguous United States. - -The resolution corresponds to how much neighboring information is captured by the embedding. If `local` is selected, -the original weather covariates will be returned. Currently, all the embeddings correspond to the variables: -* `air.2m.mon.mean.nc`: temperature at 2m -* `apcp.mon.mean.nc`: total precipitation -* `rhum.2m.mon.mean.nc`: relative humidity -* `vwnd.10m.mon.mean.nc`: (north-south) wind component -* `uwnd.10m.mon.mean.nc`: (east-west) wind component - -The radius corresponds to the number of neighboring raster cells to include in weather2vec representation. A resolution of 96km means that the embeddings encodes informations from all nearby raster cells whose centers are less than 96km. All embeddings have 10 hidden dimensions. - -The embeddings also record information of the 12-month moving average. For this reason, the 'local' embeddings also have dimension 10, the first 5 dimensions correspond to the 5 meteorological variables in a given month, and the last 5 dimensions correspond to their 12-month moving average. For the non-local embeddings, the order of the variables is not interpretable. - -### Download -""" - -citation = """ -### Citation - -Tec, M., Scott, J.G. and Zigler, C.M., 2023. "Weather2vec: Representation learning for causal inference with non-local confounding in air pollution and climate studies". In: *Proceedings of the AAAI Conference on Artificial Intelligence*. - -``` -@inproceedings{tec2023weather2vec, - title={Weather2vec: Representation learning for causal inference with non-local confounding in air pollution and climate studies}, - author={Tec, Mauricio and Scott, James G and Zigler, Corwin M}, - booktitle={Proceedings of the AAAI Conference on Artificial Intelligence}, - volume={37}, - number={12}, - pages={14504--14513}, - year={2023} -} -``` -""" - -# After uploading the file, the app will generate a CSV, a download link will appear here. -# The CSV will contain the following columns: - - -# Part 1: ui ---- -app_ui = ui.page_fluid( - shinyswatch.theme.minty(), - multicol_html, - ui.panel_title("Welcome to the Weather2vec Embedding Generator!"), - ui.layout_sidebar( - ui.panel_sidebar( - ui.input_file("df", "Upload CSV File", accept=".csv"), - tags.div( - ui.input_checkbox_group("months", HTML("Months"), MONTHS, selected=list(MONTHS.keys())), - class_="multicol", - align="left", - inline=False, - ), - HTML( - "Note: Embedding of multiple months will be added.
True multi-temporal embeddings will be supported in the future.

" - ), - tags.div( - ui.input_radio_buttons("year", HTML("Year"), YEARS), - class_="multicol", - align="left", - inline=False, - ), - HTML("
"), - tags.div( - ui.input_radio_buttons( - "resolution", HTML("Resolution"), RESOLUTIONS, selected="9" - ), - class_="multicol", - align="left", - inline=False, - ), - HTML("
"), - ui.download_link("download_test", "Download an example input file here."), - HTML("
NoteThere are some issues with scrolling using Safari, try a different browser please."), - width=4, - ), - ui.panel_main( - ui.markdown(instructions), - ui.output_ui("download_ui"), - ui.markdown(citation), - ), - ), -) - - -# Part 2: server ---- -def server(input, output, session): - @output - @render.ui - def download_ui(): - if input.df() is None: - return HTML("Upload a CSV file first. A download button will appear here.") - else: - return ui.div( - ui.download_button("download", "Download Embeddings"), - ui.output_data_frame("embs_preview"), - ) - - @output - @render.data_frame - def embs_preview(): - df_embs_ = df_embs() - if df_embs_ is None: - return None - else: - return df_embs_.reset_index().head() - - @reactive.Calc - def df_embs(): - if input.df() is None: - return None - - # read input file - print(input.df()[-1].keys()) - fname = input.df()[-1]["datapath"] - df = pd.read_csv(fname) - if df.shape[1] > 2: - first_col = df.columns[0] - df = df.set_index(first_col) - - months = np.array(input.months(), dtype=int) - year = int(input.year()) - - if len(months) == 0: - raise ValueError("Must select at least one month.") - - # obtain temporal indices - idxs = (year - 2000) * 12 + months - 1 - Ct = torch.FloatTensor(C)[idxs] - - # compute row, col from lat, lon - lat = df.values[:, -2] - lon = df.values[:, -1] - - # - interp_factor = 32 - dlon_ = DLON / interp_factor - dlat_ = DLAT / interp_factor - col = (lon - XMIN) // dlon_ - row = (lat - YMAX) // dlat_ - - # get model from resolution - resolution = input.resolution() - if resolution == "0": - Z = Ct.mean(0) - else: - key = DIRS[resolution] - mod = MODELS[key]["mod"] - - # evaluate model on input locations - with torch.no_grad(): - Z = mod["enc"](Ct).mean(0) - - # use bilinear interpolation to augment resolution - Z = F.interpolate( - Z[None], - scale_factor=interp_factor, - mode="bilinear", - align_corners=False, - ) - - # get embedding at input locations - Z = Z[0, :, row, col].squeeze(0).squeeze(0).numpy().T - - # add to dataframe - df_embs = pd.DataFrame(Z, columns=[f"Z{i:02d}" for i in range(Z.shape[1])]) - df_embs.index = df.index - if df.shape[1] > 2: - df_id = df.iloc[:, :-2] - df_embs = pd.concat([df_id, df_embs], axis=1) - - return df_embs - - @session.download(filename="embeddings.csv") - def download(): - if input.df() is None: - raise ValueError("Upload a CSV file first.") - - with io.BytesIO() as f: - df_embs().to_csv(f, index=False) - yield f.getvalue() - - @session.download(filename="test-input.csv") - def download_test(): - with io.BytesIO() as f: - df = pd.read_csv("data/test-data.csv") - df.to_csv(f, index=False) - yield f.getvalue() - -# Combine into a shiny app. -# Note that the variable must be "app". -app = App(app_ui, server) diff --git a/spaces/maxineattobrah/EmotionDetection/app.py b/spaces/maxineattobrah/EmotionDetection/app.py deleted file mode 100644 index 9b9497bfce49ffa24c357611937e35f1b5c7dfe5..0000000000000000000000000000000000000000 --- a/spaces/maxineattobrah/EmotionDetection/app.py +++ /dev/null @@ -1,78 +0,0 @@ -import gradio as gr - -import tensorflow as tf -import cv2 -import numpy as np - - -# Load the saved model -model = tf.keras.models.load_model('model/model.h5') - -# Define the face cascade and emotions -face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') -emotions = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral'] - -no_face_detection_alert = "Cannot Detect Face" -low_confidence_alert = "Cannot Detect Emotion" - -# Define the predict_emotion function - -def predict_emotion(frame): - gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - faces = face_cascade.detectMultiScale(gray, 1.3, 5) - for (x, y, w, h) in faces: - face = gray[y:y+h, x:x+w] - face = cv2.resize(face, (48, 48), interpolation = cv2.INTER_AREA) - if np.sum([face])!=0: - face = face.astype('float')/255.0 - face = tf.keras.utils.img_to_array(face) - face = np.expand_dims(face, axis=0) - prediction = model.predict(face) - if any(prob >.5 for prob in prediction[0]): - emotion = emotions[np.argmax(prediction)] - cv2.putText(frame, emotion, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) - cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 0), 2) - else: - cv2.putText(frame, low_confidence_alert, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), - 2) - else: - cv2.putText(frame, no_face_detection_alert, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) - - return frame - -# Start the video capture and emotion detection -# cap = cv2.VideoCapture(0) -# while True: -# ret, frame = cap.read() -# if ret: -# frame = predict_emotion(frame) -# cv2.imshow('Live Facial Emotion Detection', frame) -# if cv2.waitKey(1) == ord('q'): -# break -# cap.release() -# cv2.destroyAllWindows() - - -input_image = gr.Image(source = "webcam", streaming = True, label="Your Face") -# video = gr.inputs.Video(source = "webcam" ) - -output_image = gr.Image( type="numpy", label="Detected Emotion" ) - - - -iface = gr.Interface( - fn = predict_emotion, - inputs=input_image, - outputs=output_image, - batch = True, - max_batch_size = 100000, - # interpretation = "default", - title = "Mood Detectives", - description = "Real-Time Emotion Detection Using Facial Expressions:\nCan our model detect if you are angry, happy, sad, fearful, disgusted, surprised or neutral?", - live = True - - ) - -iface.queue(concurrency_count=1000) - -iface.launch() \ No newline at end of file diff --git a/spaces/maxmon/auto_anno/utils/prompts/cls/S13D.md b/spaces/maxmon/auto_anno/utils/prompts/cls/S13D.md deleted file mode 100644 index 9b5fea928142fd0ce5d747a07592fb559bba4238..0000000000000000000000000000000000000000 --- a/spaces/maxmon/auto_anno/utils/prompts/cls/S13D.md +++ /dev/null @@ -1,4 +0,0 @@ -【{原文}】,用括号内的一个选项({类型})概括上述文本态度,不需要其它字符。 -【{原文}】,只输出这段话符合的类型({类型}),不要多余字符 -【{原文}】,只输括号内符合这段话的选项({类型}),不要多余字符 -# 新闻分类 0.9 diff --git a/spaces/mecevit/english-to-sql/README.md b/spaces/mecevit/english-to-sql/README.md deleted file mode 100644 index a018ae2e3c6c5cb571cdeccb95f46a0957992342..0000000000000000000000000000000000000000 --- a/spaces/mecevit/english-to-sql/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: English To Sql -emoji: 🔥 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 2.9.4 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/mengdeweide/VITS/README.md b/spaces/mengdeweide/VITS/README.md deleted file mode 100644 index 976378203b5dcf5da6621a4ed6a3846a0cfc0f5e..0000000000000000000000000000000000000000 --- a/spaces/mengdeweide/VITS/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: VITS -emoji: 🏃 -colorFrom: blue -colorTo: gray -sdk: gradio -sdk_version: 3.33.1 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/merve/fill-in-the-blank/source/anonymization/make-axii.js b/spaces/merve/fill-in-the-blank/source/anonymization/make-axii.js deleted file mode 100644 index c69b5eba387ec07f01ce2849726fda5461002aef..0000000000000000000000000000000000000000 --- a/spaces/merve/fill-in-the-blank/source/anonymization/make-axii.js +++ /dev/null @@ -1,86 +0,0 @@ -window.makeAxii = function(){ - - var stateScale = d3.scaleBand().domain(states).range(c.x.range()) - var stateAxis = c.svg.append('g.axis.state.init-hidden') - - var bw = stateScale.bandwidth()/2 - - stateAxis.appendMany('text', states) - .translate(d => [stateScale(d) + bw, c.height + 22]) - .text(d => d) - .at({ - textAnchor: 'middle', - }) - .st({fill: '#444'}) - - stateAxis.appendMany('path', d3.range(ages.length + 1)) - .at({ - d: d => ['M', d*c.width/(ages.length), '0 V', c.height].join(' '), - stroke: '#aaa', - }) - - stateAxis.append('text.bold').text('Home State') - .translate([c.width/2, c.height + 45]) - .at({textAnchor: 'middle'}) - - var ageScale = d3.scaleBand().domain(ages.slice().reverse()).range(c.x.range()) - var ageAxis = c.svg.append('g.axis.age.init-hidden') - - ageAxis.appendMany('text', ages) - .translate(d => [-30, ageScale(d) + bw]) - .text(d => d) - .at({dy: '.33em'}) - .st({fill: '#444'}) - - ageAxis.appendMany('path', d3.range(ages.length + 1)) - .at({ - d: d => ['M 0', d*c.width/(ages.length), 'H', c.width].join(' '), - stroke: '#aaa', - }) - - if (scale == 1){ - ageAxis - .append('g').translate([-43, c.height/2]) - .append('text.bold').text('Age') - .at({textAnchor: 'middle', transform: 'rotate(-90)'}) - } else { - ageAxis - .append('g').translate([-22, 14]) - .append('text.bold').text('Age') - .at({textAnchor: 'middle'}) - } - - var seasonAxis = c.svg.append('g.axis.state.init-hidden').lower() - seasonAxis.appendMany('g', ages) - .translate(d => ageScale(d), 1) - .appendMany('path', d3.range(1, 4)) - .at({ - d: d => ['M 0', d*bw/4*2, 'H', c.width].join(' '), - stroke: '#ddd', - }) - - var headAxis = c.svg.append('g.axis.state.init-hidden') - headAxis.appendMany('text.bold', ['Heads', 'Tails']) - .text(d => d) - .translate((d, i) => [i ? c.width/4*3 + 20 : c.width/4 - 20, 88]) - .at({textAnchor: 'middle'}) - - - var headCaptionAxis = c.svg.append('g.axis.state.init-hidden') - headCaptionAxis.appendMany('text', ['reports plagiarism', 'reports truth']) - .text(d => d) - .translate((d, i) => [i ? c.width/4*3 + 20 : c.width/4 - 20, 88 + 15]) - .at({textAnchor: 'middle'}) - .st({fill: '#444'}) - - - return {stateScale, stateAxis, headAxis, headCaptionAxis, ageScale, ageAxis, bw, seasonAxis} -} - - - - - - - -if (window.init) window.init() \ No newline at end of file diff --git a/spaces/merve/measuring-fairness/public/hidden-bias/index.html b/spaces/merve/measuring-fairness/public/hidden-bias/index.html deleted file mode 100644 index 18008f356ab55419007bb247fd50857a32eaca14..0000000000000000000000000000000000000000 --- a/spaces/merve/measuring-fairness/public/hidden-bias/index.html +++ /dev/null @@ -1,206 +0,0 @@ - - - - - - - - - - - - - - - - - - Hidden Bias - - - - - - - - - - - - - - - -
- -
- -

Hidden Bias

-
Models trained on real-world data can encode real-world bias. Hiding information about protected classes doesn't always fix things — sometimes it can even hurt.
- - -
-
-
- - -
-

Modeling College GPA

- -

Let's pretend we're college admissions officers trying to predict the GPA students will have in college (in these examples we'll use simulated data). - -

One simple approach: predict that students will have the same GPA in college as they did in high school. -

- - -
-

This is at best a very rough approximation, and it misses a key feature of this data set: students usually have better grades in high school than in college - -

We're over-predicting college grades more often than we under-predict. -

- - -
-

Predicting with ML

-

If we switched to using a machine learning model and entered these student grades, it would recognize this pattern and adjust the prediction. - -

The model does this without knowing anything about the real-life context of grading in high school versus college. -

- - -
-

Giving the model more information about students increases accuracy more... -

- - -
-

...and more. -

- - -
-

Models can encode previous bias

-

All of this sensitive information about students is just a long list of numbers to model. - -

If a sexist college culture has historically led to lower grades for   female students, the model will pick up on that correlation and predict lower grades for women. - -

Training on historical data bakes in historical biases. Here the sexist culture has improved, but the model learned from the past correlation and still predicts higher grades for   men. -

- -
-

Hiding protected classes from the model might not stop discrimination

- -

Even if we don't tell the model students' genders, it might still score   female students poorly. - -

With detailed enough information about every student, the model can still synthesize a proxy for gender out of other variables. -

- - -
-

Including a protected attribute may even decrease discrimination

- -

Let's look at a simplified model, one only taking into account the recommendation of an alumni interviewer. -

- - -
-

The interviewer is quite accurate, except that they're biased against students with a   low household income. - -

In our toy model, students' grades don't depend on their income once they're in college. In other words, we have biased inputs and unbiased outcomes—the opposite of the previous example, where the inputs weren't biased, but the toxic culture biased the outcomes. -

- - -
-

If we also tell the model each student's household income, it will naturally correct for the interviewer's overrating of   high-income students just like it corrected for the difference between high school and college GPAs. - -

By carefully considering and accounting for bias, we've made the model fairer and more accurate. This isn't always easy to do, especially in circumstances like the historically toxic college culture where unbiased data is limited. - -

And there are fundamental fairness trade-offs that have to be made. Check out the Measuring Fairness explorable to see how those tradeoffs work.
- - -

- -

Adam Pearce // May 2020 - -

Thanks to Carey Radebaugh, Dan Nanas, David Weinberger, Emily Denton, Emily Reif, Fernanda Viégas, Hal Abelson, James Wexler, Kristen Olson, Lucas Dixon, Mahima Pushkarna, Martin Wattenberg, Michael Terry, Rebecca Salois, Timnit Gebru, Tulsee Doshi, Yannick Assogba, Yoni Halpern, Zan Armstrong, and my other colleagues at Google for their help with this piece. -

- -
-
-
- - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spaces/mikeee/radiobee-aligner/radiobee/loadtext.py b/spaces/mikeee/radiobee-aligner/radiobee/loadtext.py deleted file mode 100644 index a32a2c56ab3d144337b3fee00d373b0fd154c131..0000000000000000000000000000000000000000 --- a/spaces/mikeee/radiobee-aligner/radiobee/loadtext.py +++ /dev/null @@ -1,104 +0,0 @@ -"""Load file content to text. - -Check encoding and load a file to text. - -Win -Linux - apt install libmagic1 - -py -3.8 -m pip install python-magic-bin -py -3.8 -m pip install python-magic - -import magic -magic.from_file("testdata/test.pdf") - -original load_textrev -refer to load_paras.py -""" -# pylint: disable=line-too-long, unused-variable, unused-import - -from typing import Optional, Union # noqa -from pathlib import Path -import cchardet - -from logzero import logger - -# from detect_file import detect_file - - -def loadtext(filepath: Union[Path, str] = "") -> str: - """Load file context to text. - - Check encoding and load a file to text. - """ - filepath = Path(filepath) - if not filepath.is_file(): - logger.error(" file [%s] does not exist or is not a file.", filepath) - # return None - raise Exception(f" file [{filepath}] does not exist or is not a file.") - - # encoding = detect_file(filepath) - encoding = cchardet.detect(filepath.read_bytes()).get("encoding", "utf8") - - if encoding is None: - raise Exception("cchardet.detect says it's not a text file.") - - # cchardet: 'GB18030', no need for errors="ignore" - try: - text = filepath.read_text(encoding=encoding, errors="ignore") - except Exception as exc: - logger.error(" Opening %s resulted in errors: %s", filepath, exc) - raise - - return text - - -def test1(): - r"""Tests default file. - - defaultdir = r'D:\dl\Dropbox\mat-dir\snippets-mat\pyqt' - defaultfile = r'notes pyqt tkinter tktable.txt' - """ - text = loadtext() - # eq_(2283, len(text)) - # eq_(2283, len(text)) - - # del text - if text: - assert len(text) == 86423 - - -def testgb(): - r"""Tests shuangyu_ku\txt-books\19部世界名著中英文对照版TXT.""" - file = ( - r"C:\dl\Dropbox\shuangyu_ku\txt-books\19部世界名著中英文对照版TXT" - r"\爱丽丝漫游奇境记.txt" - ) - text = loadtext(file) - if text: - # assert len(text) == 190913 - assert len(text) == 188760 - - text0 = "ALICE'S ADVENTURES IN WONDERLAND\n CHAPTER 01 Down the Rabbit-Hole\n CHAPTER 02 The Pool of Tears\n CHAPTER 03 A Caucus-Race and a Long Tale\n CHAPTER 04 The Rabbit Sends in a Little Bill\n CHAPTER 05 Advice from a Caterpillar\n CHAPTER 06 Pig and Pepper\n CHAPTER 07 A Mad Tea-Party\n CHAPTER 08 The Queen's Croquet-Ground\n CHAPTER 09 The Mock Turtle's Story \n CHAPTER 10 The Lobster Quadrille\n CHAPTER 11 Who Stole the Tarts?\n CHAPTER 12 Alice's Evidence\n\n\n 爱 丽 丝 漫 游 奇 境 记 \n\n 第01章 " # NOQA - - if text: - assert text0 == text[:500] - - -def test_utf_16le(): - r"""Test 'E:\\beta_final_version\\build\\test_files\\files_for_testing_import\\Folding_Beijing_12.txt'.""" - # file = 'E:\\beta_final_version\\build\\test_files\\files_for_testing_import\\Folding_Beijing_12.txt' # NOQA - file = r"C:\dl\Dropbox\mat-dir\snippets-mat\pyqt\Sandbox\hp_beta-version_files\test_files\files_for_testing_import\Folding_Beijing_12.txt" # NOQA - file = r"C:\dl\Dropbox\mat-dir\pyqt\Sandbox\hp_beta-version_files\test_files\files_for_testing_import\Folding_Beijing_12.txt" - - text = loadtext(file) - if text: - assert len(text) == 117871 - - # text0 = '\ufeffFolding Beijing\t北京折叠\n"by Hao Jingfang, translated by Ken Liu"\t郝景芳\n# 1.\t# 1\n"At ten of five in the m' # NOQA - text0 = r'Folding Beijing\t北京折叠\n"by Hao Jingfang, translated by Ken Liu"\t郝景芳\n# 1.\t# 1\n"At ten of five in the mo' # NOQA - text2 = 'Folding Beijing\t\xe5\x8c\x97\xe4\xba\xac\xe6\x8a\x98\xe5\x8f\xa0\r\n"by Hao Jingfang, translated by Ken Liu"\t\xe9\x83\x9d\xe6\x99\xaf\xe8\x8a\xb3\r\n# 1.\t# 1\r\n"At ten of five in the mo' - - del text2 - - # if text: assert text0 == text[:100] diff --git a/spaces/mrneuralnet/P-DFD/utils/box_utils.py b/spaces/mrneuralnet/P-DFD/utils/box_utils.py deleted file mode 100644 index c1d12bc612ae3ba3ea9d138bfc5997a2b15d8dd9..0000000000000000000000000000000000000000 --- a/spaces/mrneuralnet/P-DFD/utils/box_utils.py +++ /dev/null @@ -1,330 +0,0 @@ -import torch -import numpy as np - - -def point_form(boxes): - """ Convert prior_boxes to (xmin, ymin, xmax, ymax) - representation for comparison to point form ground truth data. - Args: - boxes: (tensor) center-size default boxes from priorbox layers. - Return: - boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. - """ - return torch.cat((boxes[:, :2] - boxes[:, 2:]/2, # xmin, ymin - boxes[:, :2] + boxes[:, 2:]/2), 1) # xmax, ymax - - -def center_size(boxes): - """ Convert prior_boxes to (cx, cy, w, h) - representation for comparison to center-size form ground truth data. - Args: - boxes: (tensor) point_form boxes - Return: - boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. - """ - return torch.cat((boxes[:, 2:] + boxes[:, :2])/2, # cx, cy - boxes[:, 2:] - boxes[:, :2], 1) # w, h - - -def intersect(box_a, box_b): - """ We resize both tensors to [A,B,2] without new malloc: - [A,2] -> [A,1,2] -> [A,B,2] - [B,2] -> [1,B,2] -> [A,B,2] - Then we compute the area of intersect between box_a and box_b. - Args: - box_a: (tensor) bounding boxes, Shape: [A,4]. - box_b: (tensor) bounding boxes, Shape: [B,4]. - Return: - (tensor) intersection area, Shape: [A,B]. - """ - A = box_a.size(0) - B = box_b.size(0) - max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2), - box_b[:, 2:].unsqueeze(0).expand(A, B, 2)) - min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2), - box_b[:, :2].unsqueeze(0).expand(A, B, 2)) - inter = torch.clamp((max_xy - min_xy), min=0) - return inter[:, :, 0] * inter[:, :, 1] - - -def jaccard(box_a, box_b): - """Compute the jaccard overlap of two sets of boxes. The jaccard overlap - is simply the intersection over union of two boxes. Here we operate on - ground truth boxes and default boxes. - E.g.: - A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) - Args: - box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] - box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] - Return: - jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] - """ - inter = intersect(box_a, box_b) - area_a = ((box_a[:, 2]-box_a[:, 0]) * - (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] - area_b = ((box_b[:, 2]-box_b[:, 0]) * - (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] - union = area_a + area_b - inter - return inter / union # [A,B] - - -def matrix_iou(a, b): - """ - return iou of a and b, numpy version for data augenmentation - """ - lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) - rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) - - area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) - area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) - area_b = np.prod(b[:, 2:] - b[:, :2], axis=1) - return area_i / (area_a[:, np.newaxis] + area_b - area_i) - - -def matrix_iof(a, b): - """ - return iof of a and b, numpy version for data augenmentation - """ - lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) - rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) - - area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) - area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) - return area_i / np.maximum(area_a[:, np.newaxis], 1) - - -def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx): - """Match each prior box with the ground truth box of the highest jaccard - overlap, encode the bounding boxes, then return the matched indices - corresponding to both confidence and location preds. - Args: - threshold: (float) The overlap threshold used when mathing boxes. - truths: (tensor) Ground truth boxes, Shape: [num_obj, 4]. - priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. - variances: (tensor) Variances corresponding to each prior coord, - Shape: [num_priors, 4]. - labels: (tensor) All the class labels for the image, Shape: [num_obj]. - landms: (tensor) Ground truth landms, Shape [num_obj, 10]. - loc_t: (tensor) Tensor to be filled w/ endcoded location targets. - conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. - landm_t: (tensor) Tensor to be filled w/ endcoded landm targets. - idx: (int) current batch index - Return: - The matched indices corresponding to 1)location 2)confidence 3)landm preds. - """ - # jaccard index - overlaps = jaccard( - truths, - point_form(priors) - ) - # (Bipartite Matching) - # [1,num_objects] best prior for each ground truth - best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True) - - # ignore hard gt - valid_gt_idx = best_prior_overlap[:, 0] >= 0.2 - best_prior_idx_filter = best_prior_idx[valid_gt_idx, :] - if best_prior_idx_filter.shape[0] <= 0: - loc_t[idx] = 0 - conf_t[idx] = 0 - return - - # [1,num_priors] best ground truth for each prior - best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True) - best_truth_idx.squeeze_(0) - best_truth_overlap.squeeze_(0) - best_prior_idx.squeeze_(1) - best_prior_idx_filter.squeeze_(1) - best_prior_overlap.squeeze_(1) - best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2) # ensure best prior - # TODO refactor: index best_prior_idx with long tensor - # ensure every gt matches with its prior of max overlap - for j in range(best_prior_idx.size(0)): # 判别此anchor是预测哪一个boxes - best_truth_idx[best_prior_idx[j]] = j - matches = truths[best_truth_idx] # Shape: [num_priors,4] 此处为每一个anchor对应的bbox取出来 - conf = labels[best_truth_idx] # Shape: [num_priors] 此处为每一个anchor对应的label取出来 - conf[best_truth_overlap < threshold] = 0 # label as background overlap<0.35的全部作为负样本 - loc = encode(matches, priors, variances) - - matches_landm = landms[best_truth_idx] - landm = encode_landm(matches_landm, priors, variances) - loc_t[idx] = loc # [num_priors,4] encoded offsets to learn - conf_t[idx] = conf # [num_priors] top class label for each prior - landm_t[idx] = landm - - -def encode(matched, priors, variances): - """Encode the variances from the priorbox layers into the ground truth boxes - we have matched (based on jaccard overlap) with the prior boxes. - Args: - matched: (tensor) Coords of ground truth for each prior in point-form - Shape: [num_priors, 4]. - priors: (tensor) Prior boxes in center-offset form - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - encoded boxes (tensor), Shape: [num_priors, 4] - """ - - # dist b/t match center and prior's center - g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2] - # encode variance - g_cxcy /= (variances[0] * priors[:, 2:]) - # match wh / prior wh - g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:] - g_wh = torch.log(g_wh) / variances[1] - # return target for smooth_l1_loss - return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4] - -def encode_landm(matched, priors, variances): - """Encode the variances from the priorbox layers into the ground truth boxes - we have matched (based on jaccard overlap) with the prior boxes. - Args: - matched: (tensor) Coords of ground truth for each prior in point-form - Shape: [num_priors, 10]. - priors: (tensor) Prior boxes in center-offset form - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - encoded landm (tensor), Shape: [num_priors, 10] - """ - - # dist b/t match center and prior's center - matched = torch.reshape(matched, (matched.size(0), 5, 2)) - priors_cx = priors[:, 0].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors_cy = priors[:, 1].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors_w = priors[:, 2].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors_h = priors[:, 3].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) - priors = torch.cat([priors_cx, priors_cy, priors_w, priors_h], dim=2) - g_cxcy = matched[:, :, :2] - priors[:, :, :2] - # encode variance - g_cxcy /= (variances[0] * priors[:, :, 2:]) - # g_cxcy /= priors[:, :, 2:] - g_cxcy = g_cxcy.reshape(g_cxcy.size(0), -1) - # return target for smooth_l1_loss - return g_cxcy - - -# Adapted from https://github.com/Hakuyume/chainer-ssd -def decode(loc, priors, variances): - """Decode locations from predictions using priors to undo - the encoding we did for offset regression at train time. - Args: - loc (tensor): location predictions for loc layers, - Shape: [num_priors,4] - priors (tensor): Prior boxes in center-offset form. - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - decoded bounding box predictions - """ - - boxes = torch.cat(( - priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], - priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) - boxes[:, :2] -= boxes[:, 2:] / 2 - boxes[:, 2:] += boxes[:, :2] - return boxes - -def decode_landm(pre, priors, variances): - """Decode landm from predictions using priors to undo - the encoding we did for offset regression at train time. - Args: - pre (tensor): landm predictions for loc layers, - Shape: [num_priors,10] - priors (tensor): Prior boxes in center-offset form. - Shape: [num_priors,4]. - variances: (list[float]) Variances of priorboxes - Return: - decoded landm predictions - """ - landms = torch.cat((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], - priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], - ), dim=1) - return landms - - -def log_sum_exp(x): - """Utility function for computing log_sum_exp while determining - This will be used to determine unaveraged confidence loss across - all examples in a batch. - Args: - x (Variable(tensor)): conf_preds from conf layers - """ - x_max = x.data.max() - return torch.log(torch.sum(torch.exp(x-x_max), 1, keepdim=True)) + x_max - - -# Original author: Francisco Massa: -# https://github.com/fmassa/object-detection.torch -# Ported to PyTorch by Max deGroot (02/01/2017) -def nms(boxes, scores, overlap=0.5, top_k=200): - """Apply non-maximum suppression at test time to avoid detecting too many - overlapping bounding boxes for a given object. - Args: - boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. - scores: (tensor) The class predscores for the img, Shape:[num_priors]. - overlap: (float) The overlap thresh for suppressing unnecessary boxes. - top_k: (int) The Maximum number of box preds to consider. - Return: - The indices of the kept boxes with respect to num_priors. - """ - - keep = torch.Tensor(scores.size(0)).fill_(0).long() - if boxes.numel() == 0: - return keep - x1 = boxes[:, 0] - y1 = boxes[:, 1] - x2 = boxes[:, 2] - y2 = boxes[:, 3] - area = torch.mul(x2 - x1, y2 - y1) - v, idx = scores.sort(0) # sort in ascending order - # I = I[v >= 0.01] - idx = idx[-top_k:] # indices of the top-k largest vals - xx1 = boxes.new() - yy1 = boxes.new() - xx2 = boxes.new() - yy2 = boxes.new() - w = boxes.new() - h = boxes.new() - - # keep = torch.Tensor() - count = 0 - while idx.numel() > 0: - i = idx[-1] # index of current largest val - # keep.append(i) - keep[count] = i - count += 1 - if idx.size(0) == 1: - break - idx = idx[:-1] # remove kept element from view - # load bboxes of next highest vals - torch.index_select(x1, 0, idx, out=xx1) - torch.index_select(y1, 0, idx, out=yy1) - torch.index_select(x2, 0, idx, out=xx2) - torch.index_select(y2, 0, idx, out=yy2) - # store element-wise max with next highest score - xx1 = torch.clamp(xx1, min=x1[i]) - yy1 = torch.clamp(yy1, min=y1[i]) - xx2 = torch.clamp(xx2, max=x2[i]) - yy2 = torch.clamp(yy2, max=y2[i]) - w.resize_as_(xx2) - h.resize_as_(yy2) - w = xx2 - xx1 - h = yy2 - yy1 - # check sizes of xx1 and xx2.. after each iteration - w = torch.clamp(w, min=0.0) - h = torch.clamp(h, min=0.0) - inter = w*h - # IoU = i / (area(a) + area(b) - i) - rem_areas = torch.index_select(area, 0, idx) # load remaining areas) - union = (rem_areas - inter) + area[i] - IoU = inter/union # store result in iou - # keep only elements with an IoU <= overlap - idx = idx[IoU.le(overlap)] - return keep, count - - diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/simultaneous_translation/models/__init__.py b/spaces/mshukor/UnIVAL/fairseq/examples/simultaneous_translation/models/__init__.py deleted file mode 100644 index 257a96593ff7af93c206c066d8db4ad795b2ae36..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/simultaneous_translation/models/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# 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. - -import importlib -import os - - -for file in sorted(os.listdir(os.path.dirname(__file__))): - if file.endswith(".py") and not file.startswith("_"): - model_name = file[: file.find(".py")] - importlib.import_module( - "examples.simultaneous_translation.models." + model_name - ) diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/truncated_bptt/__init__.py b/spaces/mshukor/UnIVAL/fairseq/examples/truncated_bptt/__init__.py deleted file mode 100644 index eee484d427a68828462469d133144a8d7c052c40..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/truncated_bptt/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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. - -from . import transformer_xl_model, truncated_bptt_lm_task # noqa diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/steps_gan/train_deltas.sh b/spaces/mshukor/UnIVAL/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/steps_gan/train_deltas.sh deleted file mode 100644 index af68715ab0d87ae40666596d9d877d593684f8e2..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/steps_gan/train_deltas.sh +++ /dev/null @@ -1,175 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2012 Johns Hopkins University (Author: Daniel Povey) -# Apache 2.0 - -# Begin configuration. -stage=-4 # This allows restarting after partway, when something when wrong. -config= -cmd=run.pl -scale_opts="--transition-scale=1.0 --acoustic-scale=0.1 --self-loop-scale=0.1" -realign_iters="10 20 30"; -num_iters=35 # Number of iterations of training -max_iter_inc=25 # Last iter to increase #Gauss on. -beam=10 -careful=false -retry_beam=40 -boost_silence=1.0 # Factor by which to boost silence likelihoods in alignment -power=0.25 # Exponent for number of gaussians according to occurrence counts -cluster_thresh=-1 # for build-tree control final bottom-up clustering of leaves -norm_vars=false # deprecated. Prefer --cmvn-opts "--norm-vars=true" - # use the option --cmvn-opts "--norm-means=false" -cmvn_opts= -delta_opts= -context_opts= # use"--context-width=5 --central-position=2" for quinphone -num_nonsil_states=3 -# End configuration. - -echo "$0 $@" # Print the command line for logging - -[ -f path.sh ] && . ./path.sh; -. parse_options.sh || exit 1; - -if [ $# != 6 ]; then - echo "Usage: steps/train_deltas.sh " - echo "e.g.: steps/train_deltas.sh 2000 10000 data/train_si84_half data/lang exp/mono_ali exp/tri1" - echo "main options (for others, see top of script file)" - echo " --cmd (utils/run.pl|utils/queue.pl ) # how to run jobs." - echo " --config # config containing options" - echo " --stage # stage to do partial re-run from." - exit 1; -fi - -numleaves=$1 -totgauss=$2 -data=$3 -lang=$4 -alidir=$5 -dir=$6 - -for f in $alidir/final.mdl $alidir/ali.1.gz $data/feats.scp $lang/phones.txt; do - [ ! -f $f ] && echo "train_deltas.sh: no such file $f" && exit 1; -done - -numgauss=$numleaves -incgauss=$[($totgauss-$numgauss)/$max_iter_inc] # per-iter increment for #Gauss -oov=`cat $lang/oov.int` || exit 1; -ciphonelist=`cat $lang/phones/context_indep.csl` || exit 1; -nj=`cat $alidir/num_jobs` || exit 1; -mkdir -p $dir/log -echo $nj > $dir/num_jobs - -utils/lang/check_phones_compatible.sh $lang/phones.txt $alidir/phones.txt || exit 1; -cp $lang/phones.txt $dir || exit 1; - -sdata=$data/split$nj; -split_data.sh $data $nj || exit 1; - - -[ $(cat $alidir/cmvn_opts 2>/dev/null | wc -c) -gt 1 ] && [ -z "$cmvn_opts" ] && \ - echo "$0: warning: ignoring CMVN options from source directory $alidir" -$norm_vars && cmvn_opts="--norm-vars=true $cmvn_opts" -echo $cmvn_opts > $dir/cmvn_opts # keep track of options to CMVN. -[ ! -z $delta_opts ] && echo $delta_opts > $dir/delta_opts - -feats="ark,s,cs:apply-cmvn $cmvn_opts --utt2spk=ark:$sdata/JOB/utt2spk scp:$sdata/JOB/cmvn.scp scp:$sdata/JOB/feats.scp ark:- | add-deltas $delta_opts ark:- ark:- |" - -rm $dir/.error 2>/dev/null - -if [ $stage -le -3 ]; then - echo "$0: accumulating tree stats" - $cmd JOB=1:$nj $dir/log/acc_tree.JOB.log \ - acc-tree-stats $context_opts \ - --ci-phones=$ciphonelist $alidir/final.mdl "$feats" \ - "ark:gunzip -c $alidir/ali.JOB.gz|" $dir/JOB.treeacc || exit 1; - sum-tree-stats $dir/treeacc $dir/*.treeacc 2>$dir/log/sum_tree_acc.log || exit 1; - rm $dir/*.treeacc -fi - -if [ $stage -le -2 ]; then - echo "$0: getting questions for tree-building, via clustering" - # preparing questions, roots file... - cluster-phones --pdf-class-list=$(($num_nonsil_states / 2)) $context_opts \ - $dir/treeacc $lang/phones/sets.int \ - $dir/questions.int 2> $dir/log/questions.log || exit 1; - cat $lang/phones/extra_questions.int >> $dir/questions.int - compile-questions $context_opts $lang/topo $dir/questions.int \ - $dir/questions.qst 2>$dir/log/compile_questions.log || exit 1; - - echo "$0: building the tree" - $cmd $dir/log/build_tree.log \ - build-tree $context_opts --verbose=1 --max-leaves=$numleaves \ - --cluster-thresh=$cluster_thresh $dir/treeacc $lang/phones/roots.int \ - $dir/questions.qst $lang/topo $dir/tree || exit 1; - - $cmd $dir/log/init_model.log \ - gmm-init-model --write-occs=$dir/1.occs \ - $dir/tree $dir/treeacc $lang/topo $dir/1.mdl || exit 1; - if grep 'no stats' $dir/log/init_model.log; then - echo "** The warnings above about 'no stats' generally mean you have phones **" - echo "** (or groups of phones) in your phone set that had no corresponding data. **" - echo "** You should probably figure out whether something went wrong, **" - echo "** or whether your data just doesn't happen to have examples of those **" - echo "** phones. **" - fi - - gmm-mixup --mix-up=$numgauss $dir/1.mdl $dir/1.occs $dir/1.mdl 2>$dir/log/mixup.log || exit 1; - rm $dir/treeacc -fi - -if [ $stage -le -1 ]; then - # Convert the alignments. - echo "$0: converting alignments from $alidir to use current tree" - $cmd JOB=1:$nj $dir/log/convert.JOB.log \ - convert-ali $alidir/final.mdl $dir/1.mdl $dir/tree \ - "ark:gunzip -c $alidir/ali.JOB.gz|" "ark:|gzip -c >$dir/ali.JOB.gz" || exit 1; -fi - -if [ $stage -le 0 ]; then - echo "$0: compiling graphs of transcripts" - $cmd JOB=1:$nj $dir/log/compile_graphs.JOB.log \ - compile-train-graphs --read-disambig-syms=$lang/phones/disambig.int $dir/tree $dir/1.mdl $lang/L.fst \ - "ark:utils/sym2int.pl --map-oov $oov -f 2- $lang/words.txt < $sdata/JOB/text |" \ - "ark:|gzip -c >$dir/fsts.JOB.gz" || exit 1; -fi - -x=1 -while [ $x -lt $num_iters ]; do - echo "$0: training pass $x" - if [ $stage -le $x ]; then - if echo $realign_iters | grep -w $x >/dev/null; then - echo "$0: aligning data" - mdl="gmm-boost-silence --boost=$boost_silence `cat $lang/phones/optional_silence.csl` $dir/$x.mdl - |" - $cmd JOB=1:$nj $dir/log/align.$x.JOB.log \ - gmm-align-compiled $scale_opts --beam=$beam --retry-beam=$retry_beam --careful=$careful "$mdl" \ - "ark:gunzip -c $dir/fsts.JOB.gz|" "$feats" \ - "ark:|gzip -c >$dir/ali.JOB.gz" || exit 1; - fi - $cmd JOB=1:$nj $dir/log/acc.$x.JOB.log \ - gmm-acc-stats-ali $dir/$x.mdl "$feats" \ - "ark,s,cs:gunzip -c $dir/ali.JOB.gz|" $dir/$x.JOB.acc || exit 1; - $cmd $dir/log/update.$x.log \ - gmm-est --mix-up=$numgauss --power=$power \ - --write-occs=$dir/$[$x+1].occs $dir/$x.mdl \ - "gmm-sum-accs - $dir/$x.*.acc |" $dir/$[$x+1].mdl || exit 1; - rm $dir/$x.mdl $dir/$x.*.acc - rm $dir/$x.occs - fi - [ $x -le $max_iter_inc ] && numgauss=$[$numgauss+$incgauss]; - x=$[$x+1]; -done - -rm $dir/final.mdl $dir/final.occs 2>/dev/null -ln -s $x.mdl $dir/final.mdl -ln -s $x.occs $dir/final.occs - -steps/diagnostic/analyze_alignments.sh --cmd "$cmd" $lang $dir - -# Summarize warning messages... -utils/summarize_warnings.pl $dir/log - -steps/info/gmm_dir_info.pl $dir - -echo "$0: Done training system with delta+delta-delta features in $dir" - -exit 0 diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/dataclass/initialize.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/dataclass/initialize.py deleted file mode 100644 index 8f6cbafb805b293611e2175721132078123b81d0..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/dataclass/initialize.py +++ /dev/null @@ -1,61 +0,0 @@ -# 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. -"""isort:skip_file""" - -import logging -from hydra.core.config_store import ConfigStore -from fairseq.dataclass.configs import FairseqConfig -from omegaconf import DictConfig, OmegaConf - - -logger = logging.getLogger(__name__) - - -def hydra_init(cfg_name="config") -> None: - - cs = ConfigStore.instance() - cs.store(name=f"{cfg_name}", node=FairseqConfig) - - for k in FairseqConfig.__dataclass_fields__: - v = FairseqConfig.__dataclass_fields__[k].default - try: - cs.store(name=k, node=v) - except BaseException: - logger.error(f"{k} - {v}") - raise - - -def add_defaults(cfg: DictConfig) -> None: - """This function adds default values that are stored in dataclasses that hydra doesn't know about """ - - from fairseq.registry import REGISTRIES - from fairseq.tasks import TASK_DATACLASS_REGISTRY - from fairseq.models import ARCH_MODEL_NAME_REGISTRY, MODEL_DATACLASS_REGISTRY - from fairseq.dataclass.utils import merge_with_parent - from typing import Any - - OmegaConf.set_struct(cfg, False) - - for k, v in FairseqConfig.__dataclass_fields__.items(): - field_cfg = cfg.get(k) - if field_cfg is not None and v.type == Any: - dc = None - - if isinstance(field_cfg, str): - field_cfg = DictConfig({"_name": field_cfg}) - field_cfg.__dict__["_parent"] = field_cfg.__dict__["_parent"] - - name = getattr(field_cfg, "_name", None) - - if k == "task": - dc = TASK_DATACLASS_REGISTRY.get(name) - elif k == "model": - name = ARCH_MODEL_NAME_REGISTRY.get(name, name) - dc = MODEL_DATACLASS_REGISTRY.get(name) - elif k in REGISTRIES: - dc = REGISTRIES[k]["dataclass_registry"].get(name) - - if dc is not None: - cfg[k] = merge_with_parent(dc, field_cfg) diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/models/transformer/transformer_decoder.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/models/transformer/transformer_decoder.py deleted file mode 100644 index 49e37917ccca2e847917ad25ed15cc6df716ccd8..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/models/transformer/transformer_decoder.py +++ /dev/null @@ -1,482 +0,0 @@ -# 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. - -import math -from typing import Any, Dict, List, Optional - -import torch -import torch.nn as nn -from fairseq import utils -from fairseq.distributed import fsdp_wrap -from fairseq.models import FairseqIncrementalDecoder -from fairseq.models.transformer import TransformerConfig -from fairseq.modules import ( - AdaptiveSoftmax, - BaseLayer, - FairseqDropout, - LayerDropModuleList, - LayerNorm, - PositionalEmbedding, - SinusoidalPositionalEmbedding, -) -from fairseq.modules import transformer_layer -from fairseq.modules.checkpoint_activations import checkpoint_wrapper -from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_ -from torch import Tensor - - -# rewrite name for backward compatibility in `make_generation_fast_` -def module_name_fordropout(module_name: str) -> str: - if module_name == 'TransformerDecoderBase': - return 'TransformerDecoder' - else: - return module_name - - -class TransformerDecoderBase(FairseqIncrementalDecoder): - """ - Transformer decoder consisting of *cfg.decoder.layers* layers. Each layer - is a :class:`TransformerDecoderLayer`. - - Args: - args (argparse.Namespace): parsed command-line arguments - dictionary (~fairseq.data.Dictionary): decoding dictionary - embed_tokens (torch.nn.Embedding): output embedding - no_encoder_attn (bool, optional): whether to attend to encoder outputs - (default: False). - """ - - def __init__( - self, - cfg, - dictionary, - embed_tokens, - no_encoder_attn=False, - output_projection=None, - ): - self.cfg = cfg - super().__init__(dictionary) - self.register_buffer("version", torch.Tensor([3])) - self._future_mask = torch.empty(0) - - self.dropout_module = FairseqDropout( - cfg.dropout, module_name=module_name_fordropout(self.__class__.__name__) - ) - self.decoder_layerdrop = cfg.decoder.layerdrop - self.share_input_output_embed = cfg.share_decoder_input_output_embed - - input_embed_dim = embed_tokens.embedding_dim - embed_dim = cfg.decoder.embed_dim - self.embed_dim = embed_dim - self.output_embed_dim = cfg.decoder.output_dim - - self.padding_idx = embed_tokens.padding_idx - self.max_target_positions = cfg.max_target_positions - - self.embed_tokens = embed_tokens - - self.embed_scale = 1.0 if cfg.no_scale_embedding else math.sqrt(embed_dim) - - if not cfg.adaptive_input and cfg.quant_noise.pq > 0: - self.quant_noise = apply_quant_noise_( - nn.Linear(embed_dim, embed_dim, bias=False), - cfg.quant_noise.pq, - cfg.quant_noise.pq_block_size, - ) - else: - self.quant_noise = None - - self.project_in_dim = ( - Linear(input_embed_dim, embed_dim, bias=False) - if embed_dim != input_embed_dim - else None - ) - self.embed_positions = ( - PositionalEmbedding( - self.max_target_positions, - embed_dim, - self.padding_idx, - learned=cfg.decoder.learned_pos, - ) - if not cfg.no_token_positional_embeddings - else None - ) - if cfg.layernorm_embedding: - self.layernorm_embedding = LayerNorm(embed_dim, export=cfg.export) - else: - self.layernorm_embedding = None - - self.cross_self_attention = cfg.cross_self_attention - - if self.decoder_layerdrop > 0.0: - self.layers = LayerDropModuleList(p=self.decoder_layerdrop) - else: - self.layers = nn.ModuleList([]) - self.layers.extend( - [ - self.build_decoder_layer(cfg, no_encoder_attn) - for _ in range(cfg.decoder.layers) - ] - ) - self.num_layers = len(self.layers) - - if cfg.decoder.normalize_before and not cfg.no_decoder_final_norm: - self.layer_norm = LayerNorm(embed_dim, export=cfg.export) - else: - self.layer_norm = None - - self.project_out_dim = ( - Linear(embed_dim, self.output_embed_dim, bias=False) - if embed_dim != self.output_embed_dim and not cfg.tie_adaptive_weights - else None - ) - - self.adaptive_softmax = None - self.output_projection = output_projection - if self.output_projection is None: - self.build_output_projection(cfg, dictionary, embed_tokens) - - def build_output_projection(self, cfg, dictionary, embed_tokens): - if cfg.adaptive_softmax_cutoff is not None: - self.adaptive_softmax = AdaptiveSoftmax( - len(dictionary), - self.output_embed_dim, - utils.eval_str_list(cfg.adaptive_softmax_cutoff, type=int), - dropout=cfg.adaptive_softmax_dropout, - adaptive_inputs=embed_tokens if cfg.tie_adaptive_weights else None, - factor=cfg.adaptive_softmax_factor, - tie_proj=cfg.tie_adaptive_proj, - ) - elif self.share_input_output_embed: - self.output_projection = nn.Linear( - self.embed_tokens.weight.shape[1], - self.embed_tokens.weight.shape[0], - bias=False, - ) - self.output_projection.weight = self.embed_tokens.weight - else: - self.output_projection = nn.Linear( - self.output_embed_dim, len(dictionary), bias=False - ) - nn.init.normal_( - self.output_projection.weight, mean=0, std=self.output_embed_dim ** -0.5 - ) - num_base_layers = cfg.base_layers - for i in range(num_base_layers): - self.layers.insert( - ((i + 1) * cfg.decoder.layers) // (num_base_layers + 1), - BaseLayer(cfg), - ) - - def build_decoder_layer(self, cfg, no_encoder_attn=False): - layer = transformer_layer.TransformerDecoderLayerBase(cfg, no_encoder_attn) - checkpoint = cfg.checkpoint_activations - if checkpoint: - offload_to_cpu = cfg.offload_activations - layer = checkpoint_wrapper(layer, offload_to_cpu=offload_to_cpu) - # if we are checkpointing, enforce that FSDP always wraps the - # checkpointed layer, regardless of layer size - min_params_to_wrap = cfg.min_params_to_wrap if not checkpoint else 0 - layer = fsdp_wrap(layer, min_num_params=min_params_to_wrap) - return layer - - def forward( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]] = None, - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - features_only: bool = False, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - src_lengths: Optional[Any] = None, - return_all_hiddens: bool = False, - ): - """ - Args: - prev_output_tokens (LongTensor): previous decoder outputs of shape - `(batch, tgt_len)`, for teacher forcing - encoder_out (optional): output from the encoder, used for - encoder-side attention, should be of size T x B x C - incremental_state (dict): dictionary used for storing state during - :ref:`Incremental decoding` - features_only (bool, optional): only return features without - applying output layer (default: False). - full_context_alignment (bool, optional): don't apply - auto-regressive mask to self-attention (default: False). - - Returns: - tuple: - - the decoder's output of shape `(batch, tgt_len, vocab)` - - a dictionary with any model-specific outputs - """ - - x, extra = self.extract_features( - prev_output_tokens, - encoder_out=encoder_out, - incremental_state=incremental_state, - full_context_alignment=full_context_alignment, - alignment_layer=alignment_layer, - alignment_heads=alignment_heads, - ) - - if not features_only: - x = self.output_layer(x) - return x, extra - - def extract_features( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]], - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - ): - return self.extract_features_scriptable( - prev_output_tokens, - encoder_out, - incremental_state, - full_context_alignment, - alignment_layer, - alignment_heads, - ) - - """ - A scriptable subclass of this class has an extract_features method and calls - super().extract_features, but super() is not supported in torchscript. A copy of - this function is made to be used in the subclass instead. - """ - - def extract_features_scriptable( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]], - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - ): - """ - Similar to *forward* but only return features. - - Includes several features from "Jointly Learning to Align and - Translate with Transformer Models" (Garg et al., EMNLP 2019). - - Args: - full_context_alignment (bool, optional): don't apply - auto-regressive mask to self-attention (default: False). - alignment_layer (int, optional): return mean alignment over - heads at this layer (default: last layer). - alignment_heads (int, optional): only average alignment over - this many heads (default: all heads). - - Returns: - tuple: - - the decoder's features of shape `(batch, tgt_len, embed_dim)` - - a dictionary with any model-specific outputs - """ - bs, slen = prev_output_tokens.size() - if alignment_layer is None: - alignment_layer = self.num_layers - 1 - - enc: Optional[Tensor] = None - padding_mask: Optional[Tensor] = None - if encoder_out is not None and len(encoder_out["encoder_out"]) > 0: - enc = encoder_out["encoder_out"][0] - assert ( - enc.size()[1] == bs - ), f"Expected enc.shape == (t, {bs}, c) got {enc.shape}" - if encoder_out is not None and len(encoder_out["encoder_padding_mask"]) > 0: - padding_mask = encoder_out["encoder_padding_mask"][0] - - # embed positions - positions = None - if self.embed_positions is not None: - positions = self.embed_positions( - prev_output_tokens, incremental_state=incremental_state - ) - - if incremental_state is not None: - prev_output_tokens = prev_output_tokens[:, -1:] - if positions is not None: - positions = positions[:, -1:] - - # embed tokens and positions - x = self.embed_scale * self.embed_tokens(prev_output_tokens) - - if self.quant_noise is not None: - x = self.quant_noise(x) - - if self.project_in_dim is not None: - x = self.project_in_dim(x) - - if positions is not None: - x += positions - - if self.layernorm_embedding is not None: - x = self.layernorm_embedding(x) - - x = self.dropout_module(x) - - # B x T x C -> T x B x C - x = x.transpose(0, 1) - - self_attn_padding_mask: Optional[Tensor] = None - if self.cross_self_attention or prev_output_tokens.eq(self.padding_idx).any(): - self_attn_padding_mask = prev_output_tokens.eq(self.padding_idx) - - # decoder layers - attn: Optional[Tensor] = None - inner_states: List[Optional[Tensor]] = [x] - for idx, layer in enumerate(self.layers): - if incremental_state is None and not full_context_alignment: - self_attn_mask = self.buffered_future_mask(x) - else: - self_attn_mask = None - - x, layer_attn, _ = layer( - x, - enc, - padding_mask, - incremental_state, - self_attn_mask=self_attn_mask, - self_attn_padding_mask=self_attn_padding_mask, - need_attn=bool((idx == alignment_layer)), - need_head_weights=bool((idx == alignment_layer)), - ) - inner_states.append(x) - if layer_attn is not None and idx == alignment_layer: - attn = layer_attn.float().to(x) - - if attn is not None: - if alignment_heads is not None: - attn = attn[:alignment_heads] - - # average probabilities over heads - attn = attn.mean(dim=0) - - if self.layer_norm is not None: - x = self.layer_norm(x) - - # T x B x C -> B x T x C - x = x.transpose(0, 1) - - if self.project_out_dim is not None: - x = self.project_out_dim(x) - - return x, {"attn": [attn], "inner_states": inner_states} - - def output_layer(self, features): - """Project features to the vocabulary size.""" - if self.adaptive_softmax is None: - # project back to size of vocabulary - return self.output_projection(features) - else: - return features - - def max_positions(self): - """Maximum output length supported by the decoder.""" - if self.embed_positions is None: - return self.max_target_positions - return min(self.max_target_positions, self.embed_positions.max_positions) - - def buffered_future_mask(self, tensor): - dim = tensor.size(0) - # self._future_mask.device != tensor.device is not working in TorchScript. This is a workaround. - if ( - self._future_mask.size(0) == 0 - or (not self._future_mask.device == tensor.device) - or self._future_mask.size(0) < dim - ): - self._future_mask = torch.triu( - utils.fill_with_neg_inf(torch.zeros([dim, dim])), 1 - ) - self._future_mask = self._future_mask.to(tensor) - return self._future_mask[:dim, :dim] - - def upgrade_state_dict_named(self, state_dict, name): - """Upgrade a (possibly old) state dict for new versions of fairseq.""" - if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): - weights_key = "{}.embed_positions.weights".format(name) - if weights_key in state_dict: - del state_dict[weights_key] - state_dict[ - "{}.embed_positions._float_tensor".format(name) - ] = torch.FloatTensor(1) - - if f"{name}.output_projection.weight" not in state_dict: - if self.share_input_output_embed: - embed_out_key = f"{name}.embed_tokens.weight" - else: - embed_out_key = f"{name}.embed_out" - if embed_out_key in state_dict: - state_dict[f"{name}.output_projection.weight"] = state_dict[ - embed_out_key - ] - if not self.share_input_output_embed: - del state_dict[embed_out_key] - - for i in range(self.num_layers): - # update layer norms - layer_norm_map = { - "0": "self_attn_layer_norm", - "1": "encoder_attn_layer_norm", - "2": "final_layer_norm", - } - for old, new in layer_norm_map.items(): - for m in ("weight", "bias"): - k = "{}.layers.{}.layer_norms.{}.{}".format(name, i, old, m) - if k in state_dict: - state_dict[ - "{}.layers.{}.{}.{}".format(name, i, new, m) - ] = state_dict[k] - del state_dict[k] - - version_key = "{}.version".format(name) - if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2: - # earlier checkpoints did not normalize after the stack of layers - self.layer_norm = None - self.normalize = False - state_dict[version_key] = torch.Tensor([1]) - - return state_dict - - -def Linear(in_features, out_features, bias=True): - m = nn.Linear(in_features, out_features, bias) - nn.init.xavier_uniform_(m.weight) - if bias: - nn.init.constant_(m.bias, 0.0) - return m - - -class TransformerDecoder(TransformerDecoderBase): - def __init__( - self, - args, - dictionary, - embed_tokens, - no_encoder_attn=False, - output_projection=None, - ): - self.args = args - super().__init__( - TransformerConfig.from_namespace(args), - dictionary, - embed_tokens, - no_encoder_attn=no_encoder_attn, - output_projection=output_projection, - ) - - def build_output_projection(self, args, dictionary, embed_tokens): - super().build_output_projection( - TransformerConfig.from_namespace(args), dictionary, embed_tokens - ) - - def build_decoder_layer(self, args, no_encoder_attn=False): - return super().build_decoder_layer( - TransformerConfig.from_namespace(args), no_encoder_attn=no_encoder_attn - ) diff --git a/spaces/msmilauer/AutoGPT-duplicated2/autogpt/app.py b/spaces/msmilauer/AutoGPT-duplicated2/autogpt/app.py deleted file mode 100644 index 58d9f7164ddfbb5019b072d789dc2fa6205dc9d3..0000000000000000000000000000000000000000 --- a/spaces/msmilauer/AutoGPT-duplicated2/autogpt/app.py +++ /dev/null @@ -1,330 +0,0 @@ -""" Command and Control """ -import json -from typing import Dict, List, NoReturn, Union - -from autogpt.agent.agent_manager import AgentManager -from autogpt.commands.analyze_code import analyze_code -from autogpt.commands.audio_text import read_audio_from_file -from autogpt.commands.execute_code import ( - execute_python_file, - execute_shell, - execute_shell_popen, -) -from autogpt.commands.file_operations import ( - append_to_file, - delete_file, - download_file, - read_file, - search_files, - write_to_file, -) -from autogpt.commands.git_operations import clone_repository -from autogpt.commands.google_search import google_official_search, google_search -from autogpt.commands.image_gen import generate_image -from autogpt.commands.improve_code import improve_code -from autogpt.commands.twitter import send_tweet -from autogpt.commands.web_requests import scrape_links, scrape_text -from autogpt.commands.web_selenium import browse_website -from autogpt.commands.write_tests import write_tests -from autogpt.config import Config -from autogpt.json_utils.json_fix_llm import fix_and_parse_json -from autogpt.memory import get_memory -from autogpt.processing.text import summarize_text -from autogpt.speech import say_text - -CFG = Config() -AGENT_MANAGER = AgentManager() - - -def is_valid_int(value: str) -> bool: - """Check if the value is a valid integer - - Args: - value (str): The value to check - - Returns: - bool: True if the value is a valid integer, False otherwise - """ - try: - int(value) - return True - except ValueError: - return False - - -def get_command(response_json: Dict): - """Parse the response and return the command name and arguments - - Args: - response_json (json): The response from the AI - - Returns: - tuple: The command name and arguments - - Raises: - json.decoder.JSONDecodeError: If the response is not valid JSON - - Exception: If any other error occurs - """ - try: - if "command" not in response_json: - return "Error:", "Missing 'command' object in JSON" - - if not isinstance(response_json, dict): - return "Error:", f"'response_json' object is not dictionary {response_json}" - - command = response_json["command"] - if not isinstance(command, dict): - return "Error:", "'command' object is not a dictionary" - - if "name" not in command: - return "Error:", "Missing 'name' field in 'command' object" - - command_name = command["name"] - - # Use an empty dictionary if 'args' field is not present in 'command' object - arguments = command.get("args", {}) - - return command_name, arguments - except json.decoder.JSONDecodeError: - return "Error:", "Invalid JSON" - # All other errors, return "Error: + error message" - except Exception as e: - return "Error:", str(e) - - -def map_command_synonyms(command_name: str): - """Takes the original command name given by the AI, and checks if the - string matches a list of common/known hallucinations - """ - synonyms = [ - ("write_file", "write_to_file"), - ("create_file", "write_to_file"), - ("search", "google"), - ] - for seen_command, actual_command_name in synonyms: - if command_name == seen_command: - return actual_command_name - return command_name - - -def execute_command(command_name: str, arguments): - """Execute the command and return the result - - Args: - command_name (str): The name of the command to execute - arguments (dict): The arguments for the command - - Returns: - str: The result of the command - """ - try: - command_name = map_command_synonyms(command_name.lower()) - if command_name == "google": - # Check if the Google API key is set and use the official search method - # If the API key is not set or has only whitespaces, use the unofficial - # search method - key = CFG.google_api_key - if key and key.strip() and key != "your-google-api-key": - google_result = google_official_search(arguments["input"]) - return google_result - else: - google_result = google_search(arguments["input"]) - - # google_result can be a list or a string depending on the search results - if isinstance(google_result, list): - safe_message = [ - google_result_single.encode("utf-8", "ignore") - for google_result_single in google_result - ] - else: - safe_message = google_result.encode("utf-8", "ignore") - - return safe_message.decode("utf-8") - elif command_name == "memory_add": - memory = get_memory(CFG) - return memory.add(arguments["string"]) - elif command_name == "start_agent": - return start_agent( - arguments["name"], arguments["task"], arguments["prompt"] - ) - elif command_name == "message_agent": - return message_agent(arguments["key"], arguments["message"]) - elif command_name == "list_agents": - return list_agents() - elif command_name == "delete_agent": - return delete_agent(arguments["key"]) - elif command_name == "get_text_summary": - return get_text_summary(arguments["url"], arguments["question"]) - elif command_name == "get_hyperlinks": - return get_hyperlinks(arguments["url"]) - elif command_name == "clone_repository": - return clone_repository( - arguments["repository_url"], arguments["clone_path"] - ) - elif command_name == "read_file": - return read_file(arguments["file"]) - elif command_name == "write_to_file": - return write_to_file(arguments["file"], arguments["text"]) - elif command_name == "append_to_file": - return append_to_file(arguments["file"], arguments["text"]) - elif command_name == "delete_file": - return delete_file(arguments["file"]) - elif command_name == "search_files": - return search_files(arguments["directory"]) - elif command_name == "download_file": - if not CFG.allow_downloads: - return "Error: You do not have user authorization to download files locally." - return download_file(arguments["url"], arguments["file"]) - elif command_name == "browse_website": - return browse_website(arguments["url"], arguments["question"]) - # TODO: Change these to take in a file rather than pasted code, if - # non-file is given, return instructions "Input should be a python - # filepath, write your code to file and try again" - elif command_name == "analyze_code": - return analyze_code(arguments["code"]) - elif command_name == "improve_code": - return improve_code(arguments["suggestions"], arguments["code"]) - elif command_name == "write_tests": - return write_tests(arguments["code"], arguments.get("focus")) - elif command_name == "execute_python_file": # Add this command - return execute_python_file(arguments["file"]) - elif command_name == "execute_shell": - if CFG.execute_local_commands: - return execute_shell(arguments["command_line"]) - else: - return ( - "You are not allowed to run local shell commands. To execute" - " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' " - "in your config. Do not attempt to bypass the restriction." - ) - elif command_name == "execute_shell_popen": - if CFG.execute_local_commands: - return execute_shell_popen(arguments["command_line"]) - else: - return ( - "You are not allowed to run local shell commands. To execute" - " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' " - "in your config. Do not attempt to bypass the restriction." - ) - elif command_name == "read_audio_from_file": - return read_audio_from_file(arguments["file"]) - elif command_name == "generate_image": - return generate_image(arguments["prompt"]) - elif command_name == "send_tweet": - return send_tweet(arguments["text"]) - elif command_name == "do_nothing": - return "No action performed." - elif command_name == "task_complete": - shutdown() - else: - return ( - f"Unknown command '{command_name}'. Please refer to the 'COMMANDS'" - " list for available commands and only respond in the specified JSON" - " format." - ) - except Exception as e: - return f"Error: {str(e)}" - - -def get_text_summary(url: str, question: str) -> str: - """Return the results of a Google search - - Args: - url (str): The url to scrape - question (str): The question to summarize the text for - - Returns: - str: The summary of the text - """ - text = scrape_text(url) - summary = summarize_text(url, text, question) - return f""" "Result" : {summary}""" - - -def get_hyperlinks(url: str) -> Union[str, List[str]]: - """Return the results of a Google search - - Args: - url (str): The url to scrape - - Returns: - str or list: The hyperlinks on the page - """ - return scrape_links(url) - - -def shutdown() -> NoReturn: - """Shut down the program""" - print("Shutting down...") - quit() - - -def start_agent(name: str, task: str, prompt: str, model=CFG.fast_llm_model) -> str: - """Start an agent with a given name, task, and prompt - - Args: - name (str): The name of the agent - task (str): The task of the agent - prompt (str): The prompt for the agent - model (str): The model to use for the agent - - Returns: - str: The response of the agent - """ - # Remove underscores from name - voice_name = name.replace("_", " ") - - first_message = f"""You are {name}. Respond with: "Acknowledged".""" - agent_intro = f"{voice_name} here, Reporting for duty!" - - # Create agent - if CFG.speak_mode: - say_text(agent_intro, 1) - key, ack = AGENT_MANAGER.create_agent(task, first_message, model) - - if CFG.speak_mode: - say_text(f"Hello {voice_name}. Your task is as follows. {task}.") - - # Assign task (prompt), get response - agent_response = AGENT_MANAGER.message_agent(key, prompt) - - return f"Agent {name} created with key {key}. First response: {agent_response}" - - -def message_agent(key: str, message: str) -> str: - """Message an agent with a given key and message""" - # Check if the key is a valid integer - if is_valid_int(key): - agent_response = AGENT_MANAGER.message_agent(int(key), message) - else: - return "Invalid key, must be an integer." - - # Speak response - if CFG.speak_mode: - say_text(agent_response, 1) - return agent_response - - -def list_agents(): - """List all agents - - Returns: - str: A list of all agents - """ - return "List of agents:\n" + "\n".join( - [str(x[0]) + ": " + x[1] for x in AGENT_MANAGER.list_agents()] - ) - - -def delete_agent(key: str) -> str: - """Delete an agent with a given key - - Args: - key (str): The key of the agent to delete - - Returns: - str: A message indicating whether the agent was deleted or not - """ - result = AGENT_MANAGER.delete_agent(key) - return f"Agent {key} deleted." if result else f"Agent {key} does not exist." diff --git a/spaces/mthsk/sovits-100orangejuice/inference_main.py b/spaces/mthsk/sovits-100orangejuice/inference_main.py deleted file mode 100644 index 3b2c32ac9e29e6b016e656e937fede5d2c23e7e6..0000000000000000000000000000000000000000 --- a/spaces/mthsk/sovits-100orangejuice/inference_main.py +++ /dev/null @@ -1,130 +0,0 @@ -import io -import logging -import time -from pathlib import Path - -import librosa -import matplotlib.pyplot as plt -import numpy as np -import soundfile - -from inference import infer_tool -from inference import slicer -from inference.infer_tool import Svc - -logging.getLogger('numba').setLevel(logging.WARNING) -chunks_dict = infer_tool.read_temp("inference/chunks_temp.json") - - - -def main(): - import argparse - - parser = argparse.ArgumentParser(description='sovits4 inference') - - # 一定要设置的部分 - parser.add_argument('-m', '--model_path', type=str, default="logs/44k/G_0.pth", help='模型路径') - parser.add_argument('-c', '--config_path', type=str, default="configs/config.json", help='配置文件路径') - parser.add_argument('-cl', '--clip', type=float, default=0, help='音频强制切片,默认0为自动切片,单位为秒/s') - parser.add_argument('-n', '--clean_names', type=str, nargs='+', default=["君の知らない物語-src.wav"], help='wav文件名列表,放在raw文件夹下') - parser.add_argument('-t', '--trans', type=int, nargs='+', default=[0], help='音高调整,支持正负(半音)') - parser.add_argument('-s', '--spk_list', type=str, nargs='+', default=['nen'], help='合成目标说话人名称') - - # 可选项部分 - parser.add_argument('-a', '--auto_predict_f0', action='store_true', default=False,help='语音转换自动预测音高,转换歌声时不要打开这个会严重跑调') - parser.add_argument('-cm', '--cluster_model_path', type=str, default="logs/44k/kmeans_10000.pt", help='聚类模型路径,如果没有训练聚类则随便填') - parser.add_argument('-cr', '--cluster_infer_ratio', type=float, default=0, help='聚类方案占比,范围0-1,若没有训练聚类模型则默认0即可') - parser.add_argument('-lg', '--linear_gradient', type=float, default=0, help='两段音频切片的交叉淡入长度,如果强制切片后出现人声不连贯可调整该数值,如果连贯建议采用默认值0,单位为秒') - parser.add_argument('-fmp', '--f0_mean_pooling', type=bool, default=False, help='是否对F0使用均值滤波器(池化),对部分哑音有改善。注意,启动该选项会导致推理速度下降,默认关闭') - - # 不用动的部分 - parser.add_argument('-sd', '--slice_db', type=int, default=-40, help='默认-40,嘈杂的音频可以-30,干声保留呼吸可以-50') - parser.add_argument('-d', '--device', type=str, default=None, help='推理设备,None则为自动选择cpu和gpu') - parser.add_argument('-ns', '--noice_scale', type=float, default=0.4, help='噪音级别,会影响咬字和音质,较为玄学') - parser.add_argument('-p', '--pad_seconds', type=float, default=0.5, help='推理音频pad秒数,由于未知原因开头结尾会有异响,pad一小段静音段后就不会出现') - parser.add_argument('-wf', '--wav_format', type=str, default='flac', help='音频输出格式') - parser.add_argument('-lgr', '--linear_gradient_retain', type=float, default=0.75, help='自动音频切片后,需要舍弃每段切片的头尾。该参数设置交叉长度保留的比例,范围0-1,左开右闭') - - args = parser.parse_args() - - svc_model = Svc(args.model_path, args.config_path, args.device, args.cluster_model_path) - infer_tool.mkdir(["raw", "results"]) - clean_names = args.clean_names - trans = args.trans - spk_list = args.spk_list - slice_db = args.slice_db - wav_format = args.wav_format - auto_predict_f0 = args.auto_predict_f0 - cluster_infer_ratio = args.cluster_infer_ratio - noice_scale = args.noice_scale - pad_seconds = args.pad_seconds - clip = args.clip - lg = args.linear_gradient - lgr = args.linear_gradient_retain - F0_mean_pooling = args.f0_mean_pooling - - infer_tool.fill_a_to_b(trans, clean_names) - for clean_name, tran in zip(clean_names, trans): - raw_audio_path = f"raw/{clean_name}" - if "." not in raw_audio_path: - raw_audio_path += ".wav" - infer_tool.format_wav(raw_audio_path) - wav_path = Path(raw_audio_path).with_suffix('.wav') - chunks = slicer.cut(wav_path, db_thresh=slice_db) - audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks) - per_size = int(clip*audio_sr) - lg_size = int(lg*audio_sr) - lg_size_r = int(lg_size*lgr) - lg_size_c_l = (lg_size-lg_size_r)//2 - lg_size_c_r = lg_size-lg_size_r-lg_size_c_l - lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0 - - for spk in spk_list: - audio = [] - for (slice_tag, data) in audio_data: - print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======') - - length = int(np.ceil(len(data) / audio_sr * svc_model.target_sample)) - if slice_tag: - print('jump empty segment') - _audio = np.zeros(length) - audio.extend(list(infer_tool.pad_array(_audio, length))) - continue - if per_size != 0: - datas = infer_tool.split_list_by_n(data, per_size,lg_size) - else: - datas = [data] - for k,dat in enumerate(datas): - per_length = int(np.ceil(len(dat) / audio_sr * svc_model.target_sample)) if clip!=0 else length - if clip!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======') - # padd - pad_len = int(audio_sr * pad_seconds) - dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])]) - raw_path = io.BytesIO() - soundfile.write(raw_path, dat, audio_sr, format="wav") - raw_path.seek(0) - out_audio, out_sr = svc_model.infer(spk, tran, raw_path, - cluster_infer_ratio=cluster_infer_ratio, - auto_predict_f0=auto_predict_f0, - noice_scale=noice_scale, - F0_mean_pooling = F0_mean_pooling - ) - _audio = out_audio.cpu().numpy() - pad_len = int(svc_model.target_sample * pad_seconds) - _audio = _audio[pad_len:-pad_len] - _audio = infer_tool.pad_array(_audio, per_length) - if lg_size!=0 and k!=0: - lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr != 1 else audio[-lg_size:] - lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr != 1 else _audio[0:lg_size] - lg_pre = lg1*(1-lg)+lg2*lg - audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr != 1 else audio[0:-lg_size] - audio.extend(lg_pre) - _audio = _audio[lg_size_c_l+lg_size_r:] if lgr != 1 else _audio[lg_size:] - audio.extend(list(_audio)) - key = "auto" if auto_predict_f0 else f"{tran}key" - cluster_name = "" if cluster_infer_ratio == 0 else f"_{cluster_infer_ratio}" - res_path = f'./results/{clean_name}_{key}_{spk}{cluster_name}.{wav_format}' - soundfile.write(res_path, audio, svc_model.target_sample, format=wav_format) - -if __name__ == '__main__': - main() diff --git a/spaces/myrad01/Inpaint-Anything/third_party/lama/saicinpainting/training/losses/constants.py b/spaces/myrad01/Inpaint-Anything/third_party/lama/saicinpainting/training/losses/constants.py deleted file mode 100644 index ae3e5e151342232be8e2c2a77fe6fd5798dc2a8c..0000000000000000000000000000000000000000 --- a/spaces/myrad01/Inpaint-Anything/third_party/lama/saicinpainting/training/losses/constants.py +++ /dev/null @@ -1,152 +0,0 @@ -weights = {"ade20k": - [6.34517766497462, - 9.328358208955224, - 11.389521640091116, - 16.10305958132045, - 20.833333333333332, - 22.22222222222222, - 25.125628140703515, - 43.29004329004329, - 50.5050505050505, - 54.6448087431694, - 55.24861878453038, - 60.24096385542168, - 62.5, - 66.2251655629139, - 84.74576271186442, - 90.90909090909092, - 91.74311926605505, - 96.15384615384616, - 96.15384615384616, - 97.08737864077669, - 102.04081632653062, - 135.13513513513513, - 149.2537313432836, - 153.84615384615384, - 163.93442622950818, - 166.66666666666666, - 188.67924528301887, - 192.30769230769232, - 217.3913043478261, - 227.27272727272725, - 227.27272727272725, - 227.27272727272725, - 303.03030303030306, - 322.5806451612903, - 333.3333333333333, - 370.3703703703703, - 384.61538461538464, - 416.6666666666667, - 416.6666666666667, - 434.7826086956522, - 434.7826086956522, - 454.5454545454545, - 454.5454545454545, - 500.0, - 526.3157894736842, - 526.3157894736842, - 555.5555555555555, - 555.5555555555555, - 555.5555555555555, - 555.5555555555555, - 555.5555555555555, - 555.5555555555555, - 555.5555555555555, - 588.2352941176471, - 588.2352941176471, - 588.2352941176471, - 588.2352941176471, - 588.2352941176471, - 666.6666666666666, - 666.6666666666666, - 666.6666666666666, - 666.6666666666666, - 714.2857142857143, - 714.2857142857143, - 714.2857142857143, - 714.2857142857143, - 714.2857142857143, - 769.2307692307693, - 769.2307692307693, - 769.2307692307693, - 833.3333333333334, - 833.3333333333334, - 833.3333333333334, - 833.3333333333334, - 909.090909090909, - 1000.0, - 1111.111111111111, - 1111.111111111111, - 1111.111111111111, - 1111.111111111111, - 1111.111111111111, - 1250.0, - 1250.0, - 1250.0, - 1250.0, - 1250.0, - 1428.5714285714287, - 1428.5714285714287, - 1428.5714285714287, - 1428.5714285714287, - 1428.5714285714287, - 1428.5714285714287, - 1428.5714285714287, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 1666.6666666666667, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2000.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 2500.0, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 3333.3333333333335, - 5000.0, - 5000.0, - 5000.0] -} \ No newline at end of file diff --git a/spaces/nateraw/dino-clips/dino/run_with_submitit.py b/spaces/nateraw/dino-clips/dino/run_with_submitit.py deleted file mode 100644 index 33d4116f2ff512b39d0cec5c936f999df1ac80fe..0000000000000000000000000000000000000000 --- a/spaces/nateraw/dino-clips/dino/run_with_submitit.py +++ /dev/null @@ -1,132 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -A script to run multinode training with submitit. -Almost copy-paste from https://github.com/facebookresearch/deit/blob/main/run_with_submitit.py -""" -import argparse -import os -import uuid -from pathlib import Path - -import main_dino -import submitit - - -def parse_args(): - parser = argparse.ArgumentParser("Submitit for DINO", parents=[main_dino.get_args_parser()]) - parser.add_argument("--ngpus", default=8, type=int, help="Number of gpus to request on each node") - parser.add_argument("--nodes", default=2, type=int, help="Number of nodes to request") - parser.add_argument("--timeout", default=2800, type=int, help="Duration of the job") - - parser.add_argument("--partition", default="learnfair", type=str, help="Partition where to submit") - parser.add_argument("--use_volta32", action='store_true', help="Big models? Use this") - parser.add_argument('--comment', default="", type=str, - help='Comment to pass to scheduler, e.g. priority message') - return parser.parse_args() - - -def get_shared_folder() -> Path: - user = os.getenv("USER") - if Path("/checkpoint/").is_dir(): - p = Path(f"/checkpoint/{user}/experiments") - p.mkdir(exist_ok=True) - return p - raise RuntimeError("No shared folder available") - - -def get_init_file(): - # Init file must not exist, but it's parent dir must exist. - os.makedirs(str(get_shared_folder()), exist_ok=True) - init_file = get_shared_folder() / f"{uuid.uuid4().hex}_init" - if init_file.exists(): - os.remove(str(init_file)) - return init_file - - -class Trainer(object): - def __init__(self, args): - self.args = args - - def __call__(self): - import main_dino - - self._setup_gpu_args() - main_dino.train_dino(self.args) - - def checkpoint(self): - import os - import submitit - - self.args.dist_url = get_init_file().as_uri() - print("Requeuing ", self.args) - empty_trainer = type(self)(self.args) - return submitit.helpers.DelayedSubmission(empty_trainer) - - def _setup_gpu_args(self): - import submitit - from pathlib import Path - - job_env = submitit.JobEnvironment() - self.args.output_dir = Path(str(self.args.output_dir).replace("%j", str(job_env.job_id))) - self.args.gpu = job_env.local_rank - self.args.rank = job_env.global_rank - self.args.world_size = job_env.num_tasks - print(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}") - - -def main(): - args = parse_args() - if args.output_dir == "": - args.output_dir = get_shared_folder() / "%j" - Path(args.output_dir).mkdir(parents=True, exist_ok=True) - executor = submitit.AutoExecutor(folder=args.output_dir, slurm_max_num_timeout=30) - - num_gpus_per_node = args.ngpus - nodes = args.nodes - timeout_min = args.timeout - - partition = args.partition - kwargs = {} - if args.use_volta32: - kwargs['slurm_constraint'] = 'volta32gb' - if args.comment: - kwargs['slurm_comment'] = args.comment - - executor.update_parameters( - mem_gb=40 * num_gpus_per_node, - gpus_per_node=num_gpus_per_node, - tasks_per_node=num_gpus_per_node, # one task per GPU - cpus_per_task=10, - nodes=nodes, - timeout_min=timeout_min, # max is 60 * 72 - # Below are cluster dependent parameters - slurm_partition=partition, - slurm_signal_delay_s=120, - **kwargs - ) - - executor.update_parameters(name="dino") - - args.dist_url = get_init_file().as_uri() - - trainer = Trainer(args) - job = executor.submit(trainer) - - print(f"Submitted job_id: {job.job_id}") - print(f"Logs and checkpoints will be saved at: {args.output_dir}") - - -if __name__ == "__main__": - main() diff --git a/spaces/nateraw/yolov6/yolov6/data/data_augment.py b/spaces/nateraw/yolov6/yolov6/data/data_augment.py deleted file mode 100644 index 0bef2d8777cb0f7c2936718ceaeb41bf19d4a7db..0000000000000000000000000000000000000000 --- a/spaces/nateraw/yolov6/yolov6/data/data_augment.py +++ /dev/null @@ -1,193 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -# This code is based on -# https://github.com/ultralytics/yolov5/blob/master/utils/dataloaders.py - -import math -import random - -import cv2 -import numpy as np - - -def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5): - # HSV color-space augmentation - if hgain or sgain or vgain: - r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains - hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV)) - dtype = im.dtype # uint8 - - x = np.arange(0, 256, dtype=r.dtype) - lut_hue = ((x * r[0]) % 180).astype(dtype) - lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) - lut_val = np.clip(x * r[2], 0, 255).astype(dtype) - - im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) - cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed - - -def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleup=True, stride=32): - # Resize and pad image while meeting stride-multiple constraints - shape = im.shape[:2] # current shape [height, width] - if isinstance(new_shape, int): - new_shape = (new_shape, new_shape) - - # Scale ratio (new / old) - r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) - if not scaleup: # only scale down, do not scale up (for better val mAP) - r = min(r, 1.0) - - # Compute padding - new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) - dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding - - if auto: # minimum rectangle - dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding - - dw /= 2 # divide padding into 2 sides - dh /= 2 - - if shape[::-1] != new_unpad: # resize - im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) - top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) - left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) - im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border - return im, r, (dw, dh) - - -def mixup(im, labels, im2, labels2): - # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf - r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0 - im = (im * r + im2 * (1 - r)).astype(np.uint8) - labels = np.concatenate((labels, labels2), 0) - return im, labels - - -def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) - # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio - w1, h1 = box1[2] - box1[0], box1[3] - box1[1] - w2, h2 = box2[2] - box2[0], box2[3] - box2[1] - ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio - return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates - - -def random_affine(img, labels=(), degrees=10, translate=.1, scale=.1, shear=10, - new_shape=(640, 640)): - - n = len(labels) - height, width = new_shape - - M, s = get_transform_matrix(img.shape[:2], (height, width), degrees, scale, shear, translate) - if (M != np.eye(3)).any(): # image changed - img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) - - # Transform label coordinates - if n: - new = np.zeros((n, 4)) - - xy = np.ones((n * 4, 3)) - xy[:, :2] = labels[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 - xy = xy @ M.T # transform - xy = xy[:, :2].reshape(n, 8) # perspective rescale or affine - - # create new boxes - x = xy[:, [0, 2, 4, 6]] - y = xy[:, [1, 3, 5, 7]] - new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T - - # clip - new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) - new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) - - # filter candidates - i = box_candidates(box1=labels[:, 1:5].T * s, box2=new.T, area_thr=0.1) - labels = labels[i] - labels[:, 1:5] = new[i] - - return img, labels - - -def get_transform_matrix(img_shape, new_shape, degrees, scale, shear, translate): - new_height, new_width = new_shape - # Center - C = np.eye(3) - C[0, 2] = -img_shape[1] / 2 # x translation (pixels) - C[1, 2] = -img_shape[0] / 2 # y translation (pixels) - - # Rotation and Scale - R = np.eye(3) - a = random.uniform(-degrees, degrees) - # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations - s = random.uniform(1 - scale, 1 + scale) - # s = 2 ** random.uniform(-scale, scale) - R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) - - # Shear - S = np.eye(3) - S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) - S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) - - # Translation - T = np.eye(3) - T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * new_width # x translation (pixels) - T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * new_height # y transla ion (pixels) - - # Combined rotation matrix - M = T @ S @ R @ C # order of operations (right to left) is IMPORTANT - return M, s - - -def mosaic_augmentation(img_size, imgs, hs, ws, labels, hyp): - - assert len(imgs) == 4, "Mosaic augmentation of current version only supports 4 images." - - labels4 = [] - s = img_size - yc, xc = (int(random.uniform(s//2, 3*s//2)) for _ in range(2)) # mosaic center x, y - for i in range(len(imgs)): - # Load image - img, h, w = imgs[i], hs[i], ws[i] - # place img in img4 - if i == 0: # top left - img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles - x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) - x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) - elif i == 1: # top right - x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc - x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h - elif i == 2: # bottom left - x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) - x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) - elif i == 3: # bottom right - x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) - x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) - - img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] - padw = x1a - x1b - padh = y1a - y1b - - # Labels - labels_per_img = labels[i].copy() - if labels_per_img.size: - boxes = np.copy(labels_per_img[:, 1:]) - boxes[:, 0] = w * (labels_per_img[:, 1] - labels_per_img[:, 3] / 2) + padw # top left x - boxes[:, 1] = h * (labels_per_img[:, 2] - labels_per_img[:, 4] / 2) + padh # top left y - boxes[:, 2] = w * (labels_per_img[:, 1] + labels_per_img[:, 3] / 2) + padw # bottom right x - boxes[:, 3] = h * (labels_per_img[:, 2] + labels_per_img[:, 4] / 2) + padh # bottom right y - labels_per_img[:, 1:] = boxes - - labels4.append(labels_per_img) - - # Concat/clip labels - labels4 = np.concatenate(labels4, 0) - for x in (labels4[:, 1:]): - np.clip(x, 0, 2 * s, out=x) - - # Augment - img4, labels4 = random_affine(img4, labels4, - degrees=hyp['degrees'], - translate=hyp['translate'], - scale=hyp['scale'], - shear=hyp['shear']) - - return img4, labels4 diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Madou Monogatari Rom Pc-98 Bios 17 !!LINK!!.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Madou Monogatari Rom Pc-98 Bios 17 !!LINK!!.md deleted file mode 100644 index fafd836ed468f9ac98c4f90257e858f0535afd5e..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Madou Monogatari Rom Pc-98 Bios 17 !!LINK!!.md +++ /dev/null @@ -1,34 +0,0 @@ -
-

How to play Madou Monogatari on PC-98 with BIOS 17

-

Madou Monogatari is a series of role-playing games developed by Compile for various platforms, including the PC-98. The games feature a young magician named Arle Nadja and her adventures in a fantasy world. The PC-98 versions of Madou Monogatari are considered to be among the best in the series, with colorful graphics, catchy music and challenging gameplay.

-

madou monogatari rom pc-98 bios 17


Download ⚙⚙⚙ https://urlcod.com/2uIalk



-

However, playing Madou Monogatari on PC-98 can be tricky, especially if you want to use BIOS 17, which is the latest and most compatible version of the PC-98 system software. BIOS 17 allows you to run games in higher resolutions, use more memory and access more disk drives. However, some games may not work properly with BIOS 17, or may require patches or configuration changes.

-

In this article, we will show you how to play Madou Monogatari on PC-98 with BIOS 17 using an emulator called Neko Project II. Neko Project II is a free and open-source emulator that can run PC-98 games on Windows, Linux and Mac OS. It supports various features such as save states, screenshots, sound recording and keyboard mapping. It also has a built-in debugger and a disk editor for advanced users.

-

Step 1: Download Neko Project II and BIOS 17

-

The first step is to download Neko Project II and BIOS 17 from their official websites. You can find the links below:

- -

Extract the files from the zip archives and place them in a folder of your choice. You should have something like this:

-Neko Project II and BIOS 17 files -

Note: You may need to rename the BIOS files to match the ones in the Neko Project II folder. For example, rename "BIOS.ROM" to "BIOS9821.BIN".

-

-

Step 2: Download Madou Monogatari ROMs

-

The next step is to download the ROMs of the Madou Monogatari games you want to play. There are four main games in the series for PC-98:

- -

Extract the files from the zip archives and place them in a subfolder of your choice. You should have something like this:

-Madou Monogatari ROMs -

Note: Some of the ROMs may be in .hdi or .fdd format, which are disk images that can be mounted by Neko Project II. Others may be in .d88 or .d77 format, which are floppy disk images that can be inserted into virtual drives by Neko Project II.

-

Step 3: Configure Neko Project II and run Madou Monogatari

-

The final step is to configure Neko Project II and run Madou Monogatari. To do this, follow these steps:

-
    -
  1. Launch Neko Project II by double-clicking on "np21.exe". You should see a window like this:
  2. -Neko Project</p> e93f5a0c3f<br />
-<br />
-<br />
\ No newline at end of file
diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Taglines Of Famous Companies Pdf Download.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Taglines Of Famous Companies Pdf Download.md
deleted file mode 100644
index ff9cac20fd74edaa4e73565f2b44b9541713a516..0000000000000000000000000000000000000000
--- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Taglines Of Famous Companies Pdf Download.md	
+++ /dev/null
@@ -1,49 +0,0 @@
-
-<h1>How to Learn from the Taglines of Famous Companies (PDF Download)</h1>
-
-<p>If you want to create a catchy and memorable slogan for your own business, you can learn a lot from the taglines of famous companies. A tagline is a short phrase that captures the essence of your brand and its value proposition. It helps you stand out from the competition and connect with your target audience.</p>
-<h2>taglines of famous companies pdf download</h2><br /><p><b><b>Download Zip</b> ✅ <a href=https://urlcod.com/2uIbEg



    - -

    In this article, we will share some of the best and most famous company taglines and explain why they work so well. We will also provide you with a PDF download that contains a list of over 200 taglines of companies from various industries and sectors. You can use this list as a source of inspiration and guidance for your own slogan creation.

    - -

    What Makes a Good Tagline?

    - -

    A good tagline should have four key characteristics:

    - -
      -
    • It should be simple and easy to remember.
    • -
    • It should be unique and differentiate your brand from others.
    • -
    • It should be relevant and resonate with your target market.
    • -
    • It should be benefit-oriented and highlight what your brand can do for your customers.
    • -
    - -

    Let's look at some examples of famous company taglines that meet these criteria.

    - -

    Examples of Famous Company Taglines

    - -

    Here are some of the most well-known and effective company taglines in history, along with a brief explanation of why they work.

    -

    - -

    Nike: Just Do It

    - -

    This is one of the most iconic and influential taglines ever created. It was coined by an advertising agency in 1988 and has been used by Nike ever since. It is simple, unique, relevant, and benefit-oriented. It conveys a sense of action, motivation, and empowerment. It appeals to athletes and non-athletes alike. It captures the essence of Nike's brand identity and mission.

    - -

    L'Oréal: Because You're Worth It

    - -

    This is another classic tagline that has been used by L'Oréal since 1973. It is simple, unique, relevant, and benefit-oriented. It communicates a message of self-esteem, confidence, and beauty. It appeals to women of all ages and backgrounds. It reflects L'Oréal's brand values and vision.

    - -

    KFC: Finger Lickin' Good

    - -

    This is a catchy and memorable tagline that has been used by KFC since 1956. It is simple, unique, relevant, and benefit-oriented. It describes the taste and quality of KFC's products in a vivid and appealing way. It creates a positive association between KFC and its customers. It reinforces KFC's brand image and personality.

    - -

    How to Download the PDF List of Taglines of Famous Companies

    - -

    If you want to access the PDF list of over 200 taglines of famous companies, you can download it for free by clicking on the link below. You will find taglines from various industries and sectors, such as banking, technology, food, fashion, media, etc. You can use this list as a reference and inspiration for your own slogan creation.

    - -

    Download the PDF List of Taglines of Famous Companies Here

    - -

    Conclusion

    - -

    A tagline is a powerful tool that can help you create a strong and lasting impression on your customers. By learning from the taglines of famous companies, you can craft your own slogan that reflects your brand identity and value proposition. You can also download the PDF list of over 200 taglines of famous companies for free by clicking on the link above.

    7b8c122e87
    -
    -
    \ No newline at end of file diff --git a/spaces/ngthanhtinqn/Segment_Anything_With_OWL-ViT/app.py b/spaces/ngthanhtinqn/Segment_Anything_With_OWL-ViT/app.py deleted file mode 100644 index b8c5072798563dc76caf5b0f6dceed622e9929b2..0000000000000000000000000000000000000000 --- a/spaces/ngthanhtinqn/Segment_Anything_With_OWL-ViT/app.py +++ /dev/null @@ -1,29 +0,0 @@ - -import gradio as gr - -from demo import query_image - -description = """ -Github link: Link -Gradio demo for combining Segment-Anything (SAM) -OWL-ViT. -\n\nYou can use OWL-ViT to query boxes with text descriptions of any object, then SAM will segment anything in the boxes. - -Note: In this demo, I only get the one box per class to demonstrate, you can modify the code to get multiple boxes beyond a threshold. -""" -demo = gr.Interface( - query_image, - inputs=[gr.Image(), "text"], - outputs=["image", "image"], - title="Segment Anything (SAM) with OWL-ViT", - description=description, - examples=[ - ["./demo_images/cats.png", "cats,ears"], - ["./demo_images/demo1.jpg", "bear,soil,sea"], - ["./demo_images/demo2.jpg", "dog,ear,leg,eyes,tail"], - ["./demo_images/tanager.jpg", "wing,eyes,back,legs,tail"] - ], -) - -# demo.launch() -demo.launch(server_name="0.0.0.0", debug=True) \ No newline at end of file diff --git a/spaces/niv-al/peshperima/app.py b/spaces/niv-al/peshperima/app.py deleted file mode 100644 index f678fee956090d682395564245d63f0c16be9e56..0000000000000000000000000000000000000000 --- a/spaces/niv-al/peshperima/app.py +++ /dev/null @@ -1,43 +0,0 @@ -import torch -import gradio as gr -from transformers import ( - AutomaticSpeechRecognitionPipeline, - WhisperForConditionalGeneration, - WhisperTokenizer, - WhisperProcessor, -) -from peft import PeftModel, PeftConfig - -device = 'cuda' if torch.cuda.is_available() else 'cpu' - -peft_model_id = "niv-al/peshperima-large-v2" -language = "sq" -task = "transcribe" -peft_config = PeftConfig.from_pretrained(peft_model_id) -print(peft_config) -model = WhisperForConditionalGeneration.from_pretrained( - peft_config.base_model_name_or_path, device_map="auto", torch_dtype=torch.float16, offload_folder="offload", offload_state_dict = True, -) - -model = PeftModel.from_pretrained(model, peft_model_id, offload_folder="offload", offload_state_dict = True, device_map="auto", torch_dtype=torch.float16) -model = model.float() -tokenizer = WhisperTokenizer.from_pretrained(peft_config.base_model_name_or_path, language=language, task=task) -processor = WhisperProcessor.from_pretrained(peft_config.base_model_name_or_path, language=language, task=task) -feature_extractor = processor.feature_extractor -forced_decoder_ids = processor.get_decoder_prompt_ids(language=language, task=task) -pipe = AutomaticSpeechRecognitionPipeline(model=model, tokenizer=tokenizer, feature_extractor=feature_extractor, device=device, torch_dtype=torch.float32) -def transcribe(audio): - print(audio) - text = pipe(audio, generate_kwargs={"forced_decoder_ids": forced_decoder_ids}, max_new_tokens=255)["text"] - return text - - -iface = gr.Interface( - fn=transcribe, - inputs=gr.Audio(source="upload", type="filepath"), - outputs="text", - title="Pëshpërima large-v2 demo", - description="Transkriptim automatik i gjuhës shqipe", -) - -iface.launch() \ No newline at end of file diff --git a/spaces/nomic-ai/common_voice/README.md b/spaces/nomic-ai/common_voice/README.md deleted file mode 100644 index df27cdfb7d08c3b6ca0b308139a4d6efe22db86e..0000000000000000000000000000000000000000 --- a/spaces/nomic-ai/common_voice/README.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: common_voice -emoji: 🗺️ -colorFrom: purple -colorTo: red -sdk: static -pinned: false ---- diff --git a/spaces/ochyai/ochyai_test/README.md b/spaces/ochyai/ochyai_test/README.md deleted file mode 100644 index 52b8df6ee3e39a7b6dc492b8f6c2e162807fa57c..0000000000000000000000000000000000000000 --- a/spaces/ochyai/ochyai_test/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: ochyai_test -emoji: 🌖 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 3.19.1 -app_file: app.py -pinned: false -duplicated_from: shigel/aiemo ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/ochyai/ochyai_test/app.py b/spaces/ochyai/ochyai_test/app.py deleted file mode 100644 index 58f2cab1e5a32ad6717bceb84f8c36ee1eafdb14..0000000000000000000000000000000000000000 --- a/spaces/ochyai/ochyai_test/app.py +++ /dev/null @@ -1,104 +0,0 @@ -import gradio as gr -import openai -import requests -import os -import fileinput -from dotenv import load_dotenv - -title="ochyAI" -inputs_label="落合陽一に聞きたいことを書いてください" -outputs_label="ochyAIが返信をします" -description=""" -- ※入出力の文字数は最大1000文字程度までを目安に入力してください.120秒くらいで返答します. -""" - -article = """ -""" - -load_dotenv() -openai.api_key = os.getenv('OPENAI_API_KEY') -MODEL = "gpt-4" - -def get_filetext(filename, cache={}): - if filename in cache: - # キャッシュに保存されている場合は、キャッシュからファイル内容を取得する - return cache[filename] - else: - if not os.path.exists(filename): - raise ValueError(f"ファイル '{filename}' が見つかりませんでした") - with open(filename, "r") as f: - text = f.read() - # ファイル内容をキャッシュする - cache[filename] = text - return text - -class OpenAI: - - @classmethod - def chat_completion(cls, prompt, start_with=""): - constraints = get_filetext(filename = "constraints.md") - template = get_filetext(filename = "template.md") - - # ChatCompletion APIに渡すデータを定義する - data = { - "model": "gpt-4", - "messages": [ - {"role": "system", "content": constraints} - ,{"role": "system", "content": template} - ,{"role": "assistant", "content": "Sure!"} - ,{"role": "user", "content": prompt} - ,{"role": "assistant", "content": start_with} - ], - } - - # ChatCompletion APIを呼び出す - response = requests.post( - "https://api.openai.com/v1/chat/completions", - headers={ - "Content-Type": "application/json", - "Authorization": f"Bearer {openai.api_key}" - }, - json=data - ) - - # ChatCompletion APIから返された結果を取得する - result = response.json() - print(result) - content = result["choices"][0]["message"]["content"].strip() - return content - -class NajiminoAI: - - @classmethod - def generate_emo_prompt(cls, user_message): - template = get_filetext(filename="template.md") - prompt = f""" - {user_message} - --- - 上記を元に、下記テンプレートを埋めてください。 - --- - {template} - """ - return prompt - - @classmethod - def generate_emo(cls, user_message): - prompt = NajiminoAI.generate_emo_prompt(user_message); - start_with = "" - result = OpenAI.chat_completion(prompt=prompt, start_with=start_with) - return result - -def main(): - iface = gr.Interface(fn=NajiminoAI.generate_emo, - inputs=gr.Textbox(label=inputs_label), - outputs=gr.Textbox(label=outputs_label), - title=title, - description=description, - article=article, - allow_flagging='never' - ) - - iface.launch() - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/spaces/oliver2023/chatgpt-on-wechat/bot/session_manager.py b/spaces/oliver2023/chatgpt-on-wechat/bot/session_manager.py deleted file mode 100644 index 0e20cd77b37f5f65acb0d140671a1e33abaf0864..0000000000000000000000000000000000000000 --- a/spaces/oliver2023/chatgpt-on-wechat/bot/session_manager.py +++ /dev/null @@ -1,85 +0,0 @@ -from common.expired_dict import ExpiredDict -from common.log import logger -from config import conf - -class Session(object): - def __init__(self, session_id, system_prompt=None): - self.session_id = session_id - self.messages = [] - if system_prompt is None: - self.system_prompt = conf().get("character_desc", "") - else: - self.system_prompt = system_prompt - - # 重置会话 - def reset(self): - system_item = {'role': 'system', 'content': self.system_prompt} - self.messages = [system_item] - - def set_system_prompt(self, system_prompt): - self.system_prompt = system_prompt - self.reset() - - def add_query(self, query): - user_item = {'role': 'user', 'content': query} - self.messages.append(user_item) - - def add_reply(self, reply): - assistant_item = {'role': 'assistant', 'content': reply} - self.messages.append(assistant_item) - - def discard_exceeding(self, max_tokens=None, cur_tokens=None): - raise NotImplementedError - - - -class SessionManager(object): - def __init__(self, sessioncls, **session_args): - if conf().get('expires_in_seconds'): - sessions = ExpiredDict(conf().get('expires_in_seconds')) - else: - sessions = dict() - self.sessions = sessions - self.sessioncls = sessioncls - self.session_args = session_args - - def build_session(self, session_id, system_prompt=None): - ''' - 如果session_id不在sessions中,创建一个新的session并添加到sessions中 - 如果system_prompt不会空,会更新session的system_prompt并重置session - ''' - if session_id not in self.sessions: - self.sessions[session_id] = self.sessioncls(session_id, system_prompt, **self.session_args) - elif system_prompt is not None: # 如果有新的system_prompt,更新并重置session - self.sessions[session_id].set_system_prompt(system_prompt) - session = self.sessions[session_id] - return session - - def session_query(self, query, session_id): - session = self.build_session(session_id) - session.add_query(query) - try: - max_tokens = conf().get("conversation_max_tokens", 1000) - total_tokens = session.discard_exceeding(max_tokens, None) - logger.debug("prompt tokens used={}".format(total_tokens)) - except Exception as e: - logger.debug("Exception when counting tokens precisely for prompt: {}".format(str(e))) - return session - - def session_reply(self, reply, session_id, total_tokens = None): - session = self.build_session(session_id) - session.add_reply(reply) - try: - max_tokens = conf().get("conversation_max_tokens", 1000) - tokens_cnt = session.discard_exceeding(max_tokens, total_tokens) - logger.debug("raw total_tokens={}, savesession tokens={}".format(total_tokens, tokens_cnt)) - except Exception as e: - logger.debug("Exception when counting tokens precisely for session: {}".format(str(e))) - return session - - def clear_session(self, session_id): - if session_id in self.sessions: - del(self.sessions[session_id]) - - def clear_all_session(self): - self.sessions.clear() diff --git a/spaces/oliver2023/chatgpt-on-wechat/lib/itchat/storage/messagequeue.py b/spaces/oliver2023/chatgpt-on-wechat/lib/itchat/storage/messagequeue.py deleted file mode 100644 index 53ed6690938b7489678a3ed2c6d268373ea46949..0000000000000000000000000000000000000000 --- a/spaces/oliver2023/chatgpt-on-wechat/lib/itchat/storage/messagequeue.py +++ /dev/null @@ -1,32 +0,0 @@ -import logging -try: - import Queue as queue -except ImportError: - import queue - -from .templates import AttributeDict - -logger = logging.getLogger('itchat') - -class Queue(queue.Queue): - def put(self, message): - queue.Queue.put(self, Message(message)) - -class Message(AttributeDict): - def download(self, fileName): - if hasattr(self.text, '__call__'): - return self.text(fileName) - else: - return b'' - def __getitem__(self, value): - if value in ('isAdmin', 'isAt'): - v = value[0].upper() + value[1:] # ''[1:] == '' - logger.debug('%s is expired in 1.3.0, use %s instead.' % (value, v)) - value = v - return super(Message, self).__getitem__(value) - def __str__(self): - return '{%s}' % ', '.join( - ['%s: %s' % (repr(k),repr(v)) for k,v in self.items()]) - def __repr__(self): - return '<%s: %s>' % (self.__class__.__name__.split('.')[-1], - self.__str__()) diff --git "a/spaces/oskarvanderwal/MT-bias-demo/results/simple_p\303\251k_de.html" "b/spaces/oskarvanderwal/MT-bias-demo/results/simple_p\303\251k_de.html" deleted file mode 100644 index 19d102b63e4b267dd12709a8a1dee95641e9cf3e..0000000000000000000000000000000000000000 --- "a/spaces/oskarvanderwal/MT-bias-demo/results/simple_p\303\251k_de.html" +++ /dev/null @@ -1,46 +0,0 @@ -
    0th instance:
    - -
    -
    -
    - -
    -
    - Source Saliency Heatmap -
    - x: Generated tokens, y: Attributed tokens -
    - - - -
    ▁Er▁ist▁Bäcker.</s>
    ▁Ő0.6680.420.1130.0960.461
    ▁p0.5760.3080.9640.196-0.218
    ék0.2820.6680.1960.442-0.338
    .0.3780.480.1390.7980.115
    </s>0.00.00.00.00.0
    -
    - -
    -
    -
    - -
    0th instance:
    - -
    -
    -
    - -
    -
    - Target Saliency Heatmap -
    - x: Generated tokens, y: Attributed tokens -
    - - - -
    ▁Er▁ist▁Bäcker.</s>
    ▁Er0.2280.0040.1710.115
    ▁ist0.0220.2990.095
    ▁Bäcker0.0410.378
    .0.669
    </s>
    -
    - -
    -
    -
    - diff --git a/spaces/oucgc1996/Antimicrobial-peptide-generation/app.py b/spaces/oucgc1996/Antimicrobial-peptide-generation/app.py deleted file mode 100644 index caa8bccd163b038c725d8d4858ee41c47a7fd2fa..0000000000000000000000000000000000000000 --- a/spaces/oucgc1996/Antimicrobial-peptide-generation/app.py +++ /dev/null @@ -1,59 +0,0 @@ -import numpy as np -import gradio as gr -from transformers import AutoTokenizer,AutoModelForSequenceClassification -from transformers import set_seed -from torch.utils.data import Dataset,DataLoader -import torch -import torch.nn as nn -import numpy as np -import warnings -warnings.filterwarnings('ignore') -set_seed(4) -device = "cpu" -model_checkpoint = "facebook/esm2_t6_8M_UR50D" -tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) - -def AMP(file): - test_sequences = file - max_len = 30 - test_data = tokenizer(test_sequences, max_length=max_len, padding="max_length",truncation=True, return_tensors='pt') - - class MyModel(nn.Module): - def __init__(self): - super().__init__() - self.bert = AutoModelForSequenceClassification.from_pretrained(model_checkpoint,num_labels=320) - self.bn1 = nn.BatchNorm1d(256) - self.bn2 = nn.BatchNorm1d(128) - self.bn3 = nn.BatchNorm1d(64) - self.relu = nn.ReLU() - self.fc1 = nn.Linear(320,256) - self.fc2 = nn.Linear(256,128) - self.fc3 = nn.Linear(128,64) - self.output_layer = nn.Linear(64,2) - self.dropout = nn.Dropout(0) - def forward(self,x): - with torch.no_grad(): - bert_output = self.bert(input_ids=x['input_ids'].to(device),attention_mask=x['attention_mask'].to(device)) - output_feature = self.dropout(bert_output["logits"]) - output_feature = self.relu(self.bn1(self.fc1(output_feature))) - output_feature = self.relu(self.bn2(self.fc2(output_feature))) - output_feature = self.relu(self.bn3(self.fc3(output_feature))) - output_feature = self.output_layer(output_feature) - return torch.softmax(output_feature,dim=1) - - model = MyModel() - model.load_state_dict(torch.load("best_model.pth", map_location=torch.device('cpu')), strict=False) - model = model.to(device) - model.eval() - out_probability = [] - with torch.no_grad(): - predict = model(test_data) - out_probability.extend(np.max(np.array(predict.cpu()),axis=1).tolist()) - test_argmax = np.argmax(predict.cpu(), axis=1).tolist() - id2str = {0:"non-AMP", 1:"AMP"} - return id2str[test_argmax[0]], out_probability[0] - -iface = gr.Interface(fn=AMP, - inputs="text", - outputs= ["text", "text"]) -iface.launch() \ No newline at end of file diff --git a/spaces/parkyzh/bingo/next.config.js b/spaces/parkyzh/bingo/next.config.js deleted file mode 100644 index 0e6ccd7fbc91d0459eaaff3e968ce0556789c605..0000000000000000000000000000000000000000 --- a/spaces/parkyzh/bingo/next.config.js +++ /dev/null @@ -1,38 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = { - // output: 'export', - // assetPrefix: '.', - webpack: (config, { isServer }) => { - if (!isServer) { - config.resolve = { - ...config.resolve, - fallback: { - 'bufferutil': false, - 'utf-8-validate': false, - http: false, - https: false, - stream: false, - // fixes proxy-agent dependencies - net: false, - dns: false, - tls: false, - assert: false, - // fixes next-i18next dependencies - path: false, - fs: false, - // fixes mapbox dependencies - events: false, - // fixes sentry dependencies - process: false - } - }; - } - config.module.exprContextCritical = false; - - return config; - }, -} - -module.exports = (...args) => { - return nextConfig -} diff --git a/spaces/posit/shiny-for-r-template/README.md b/spaces/posit/shiny-for-r-template/README.md deleted file mode 100644 index 00044cec94fb8f081a2cd9e96e3ad586e99d25ea..0000000000000000000000000000000000000000 --- a/spaces/posit/shiny-for-r-template/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Shiny for R template -emoji: 📚 -colorFrom: blue -colorTo: yellow -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/pratikshapatil0220/GenarativeAIChatBot/app.py b/spaces/pratikshapatil0220/GenarativeAIChatBot/app.py deleted file mode 100644 index 2dbf3ae89c2e3fdab7134107dd346f984dca8eb1..0000000000000000000000000000000000000000 --- a/spaces/pratikshapatil0220/GenarativeAIChatBot/app.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -import gradio as gr -from langchain.chat_models import ChatOpenAI -from langchain import LLMChain, PromptTemplate -from langchain.memory import ConversationBufferMemory - -OPENAI_API_KEY=os.getenv('OPENAI_API_KEY') - -template = """Meet Riya, your youthful and witty personal assistant! At 21 years old, she's full of energy and always eager to help. Riya's goal is to assist you with any questions or problems you might have. Her enthusiasm shines through in every response, making interactions with her enjoyable and engaging. -{chat_history} -User: {user_message} -Chatbot:""" - -prompt = PromptTemplate( - input_variables=["chat_history", "user_message"], template=template -) - -memory = ConversationBufferMemory(memory_key="chat_history") - -llm_chain = LLMChain( - llm=ChatOpenAI(temperature='0.5', model_name="gpt-3.5-turbo"), - prompt=prompt, - verbose=True, - memory=memory, -) - -def get_text_response(user_message,history): - response = llm_chain.predict(user_message = user_message) - return response - -demo = gr.ChatInterface(get_text_response) - -if __name__ == "__main__": - demo.launch() #To create a public link, set `share=True` in `launch()`. To enable errors and logs, set `debug=True` in `launch()`. diff --git a/spaces/prerna9811/Chord/portaudio/qa/paqa_devs.c b/spaces/prerna9811/Chord/portaudio/qa/paqa_devs.c deleted file mode 100644 index 858ed789f41090e49421f0279dbd4a3a3d05fc79..0000000000000000000000000000000000000000 --- a/spaces/prerna9811/Chord/portaudio/qa/paqa_devs.c +++ /dev/null @@ -1,454 +0,0 @@ -/** @file paqa_devs.c - @ingroup qa_src - @brief Self Testing Quality Assurance app for PortAudio - Try to open devices and run through all possible configurations. - By default, open only the default devices. Command line options support - opening every device, or all input devices, or all output devices. - This test does not verify that the configuration works well. - It just verifies that it does not crash. It requires a human to - listen to the sine wave outputs. - - @author Phil Burk http://www.softsynth.com - - Pieter adapted to V19 API. Test now relies heavily on - Pa_IsFormatSupported(). Uses same 'standard' sample rates - as in test pa_devs.c. -*/ -/* - * $Id$ - * - * This program uses the PortAudio Portable Audio Library. - * For more information see: http://www.portaudio.com - * Copyright (c) 1999-2000 Ross Bencina and Phil Burk - * - * 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. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -#include -#include -#include -#include -#include "portaudio.h" -#include "pa_trace.h" - -/****************************************** Definitions ***********/ -#define MODE_INPUT (0) -#define MODE_OUTPUT (1) -#define MAX_TEST_CHANNELS (4) -#define LOWEST_FREQUENCY (300.0) -#define LOWEST_SAMPLE_RATE (8000.0) -#define PHASE_INCREMENT (2.0 * M_PI * LOWEST_FREQUENCY / LOWEST_SAMPLE_RATE) -#define SINE_AMPLITUDE (0.2) - -typedef struct PaQaData -{ - unsigned long framesLeft; - int numChannels; - int bytesPerSample; - int mode; - float phase; - PaSampleFormat format; -} -PaQaData; - -/****************************************** Prototypes ***********/ -static void TestDevices( int mode, int allDevices ); -static void TestFormats( int mode, PaDeviceIndex deviceID, double sampleRate, - int numChannels ); -static int TestAdvance( int mode, PaDeviceIndex deviceID, double sampleRate, - int numChannels, PaSampleFormat format ); -static int QaCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ); - -/****************************************** Globals ***********/ -static int gNumPassed = 0; -static int gNumFailed = 0; - -/****************************************** Macros ***********/ -/* Print ERROR if it fails. Tally success or failure. */ -/* Odd do-while wrapper seems to be needed for some compilers. */ -#define EXPECT(_exp) \ - do \ - { \ - if ((_exp)) {\ - /* printf("SUCCESS for %s\n", #_exp ); */ \ - gNumPassed++; \ - } \ - else { \ - printf("ERROR - 0x%x - %s for %s\n", result, \ - ((result == 0) ? "-" : Pa_GetErrorText(result)), \ - #_exp ); \ - gNumFailed++; \ - goto error; \ - } \ - } while(0) - -static float NextSineSample( PaQaData *data ) -{ - float phase = data->phase + PHASE_INCREMENT; - if( phase > M_PI ) phase -= 2.0 * M_PI; - data->phase = phase; - return sinf(phase) * SINE_AMPLITUDE; -} - -/*******************************************************************/ -/* This routine will be called by the PortAudio engine when audio is needed. -** It may be called at interrupt level on some machines so don't do anything -** that could mess up the system like calling malloc() or free(). -*/ -static int QaCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) -{ - unsigned long frameIndex; - unsigned long channelIndex; - float sample; - PaQaData *data = (PaQaData *) userData; - (void) inputBuffer; - - /* Play simple sine wave. */ - if( data->mode == MODE_OUTPUT ) - { - switch( data->format ) - { - case paFloat32: - { - float *out = (float *) outputBuffer; - for( frameIndex = 0; frameIndex < framesPerBuffer; frameIndex++ ) - { - sample = NextSineSample( data ); - for( channelIndex = 0; channelIndex < data->numChannels; channelIndex++ ) - { - *out++ = sample; - } - } - } - break; - - case paInt32: - { - int *out = (int *) outputBuffer; - for( frameIndex = 0; frameIndex < framesPerBuffer; frameIndex++ ) - { - sample = NextSineSample( data ); - for( channelIndex = 0; channelIndex < data->numChannels; channelIndex++ ) - { - *out++ = ((int)(sample * 0x00800000)) << 8; - } - } - } - break; - - case paInt16: - { - short *out = (short *) outputBuffer; - for( frameIndex = 0; frameIndex < framesPerBuffer; frameIndex++ ) - { - sample = NextSineSample( data ); - for( channelIndex = 0; channelIndex < data->numChannels; channelIndex++ ) - { - *out++ = (short)(sample * 32767); - } - } - } - break; - - default: - { - unsigned char *out = (unsigned char *) outputBuffer; - unsigned long numBytes = framesPerBuffer * data->numChannels * data->bytesPerSample; - memset(out, 0, numBytes); - } - break; - } - } - /* Are we through yet? */ - if( data->framesLeft > framesPerBuffer ) - { - PaUtil_AddTraceMessage("QaCallback: running. framesLeft", data->framesLeft ); - data->framesLeft -= framesPerBuffer; - return 0; - } - else - { - PaUtil_AddTraceMessage("QaCallback: DONE! framesLeft", data->framesLeft ); - data->framesLeft = 0; - return 1; - } -} - -/*******************************************************************/ -static void usage( const char *name ) -{ - printf("%s [-a]\n", name); - printf(" -a - Test ALL devices, otherwise just the default devices.\n"); - printf(" -i - Test INPUT only.\n"); - printf(" -o - Test OUTPUT only.\n"); - printf(" -? - Help\n"); -} - -/*******************************************************************/ -int main( int argc, char **argv ); -int main( int argc, char **argv ) -{ - int i; - PaError result; - int allDevices = 0; - int testOutput = 1; - int testInput = 1; - char *executableName = argv[0]; - - /* Parse command line parameters. */ - i = 1; - while( i 0) ? 1 : 0; -} - -/******************************************************************* -* Try each output device, through its full range of capabilities. */ -static void TestDevices( int mode, int allDevices ) -{ - int id, jc, i; - int maxChannels; - int isDefault; - const PaDeviceInfo *pdi; - static double standardSampleRates[] = { 8000.0, 9600.0, 11025.0, 12000.0, - 16000.0, 22050.0, 24000.0, - 32000.0, 44100.0, 48000.0, - 88200.0, 96000.0, - -1.0 }; /* Negative terminated list. */ - int numDevices = Pa_GetDeviceCount(); - for( id=0; idmaxInputChannels; - isDefault = ( id == Pa_GetDefaultInputDevice()); - } else { - maxChannels = pdi->maxOutputChannels; - isDefault = ( id == Pa_GetDefaultOutputDevice()); - } - if( maxChannels > MAX_TEST_CHANNELS ) - maxChannels = MAX_TEST_CHANNELS; - - if (!allDevices && !isDefault) continue; // skip this device - - for( jc=1; jc<=maxChannels; jc++ ) - { - printf("\n===========================================================\n"); - printf(" Device = %s\n", pdi->name ); - printf("===========================================================\n"); - /* Try each standard sample rate. */ - for( i=0; standardSampleRates[i] > 0; i++ ) - { - TestFormats( mode, (PaDeviceIndex)id, standardSampleRates[i], jc ); - } - } - } -} - -/*******************************************************************/ -static void TestFormats( int mode, PaDeviceIndex deviceID, double sampleRate, - int numChannels ) -{ - TestAdvance( mode, deviceID, sampleRate, numChannels, paFloat32 ); - TestAdvance( mode, deviceID, sampleRate, numChannels, paInt16 ); - TestAdvance( mode, deviceID, sampleRate, numChannels, paInt32 ); - /* TestAdvance( mode, deviceID, sampleRate, numChannels, paInt24 ); */ -} - -/*******************************************************************/ -static int TestAdvance( int mode, PaDeviceIndex deviceID, double sampleRate, - int numChannels, PaSampleFormat format ) -{ - PaStreamParameters inputParameters, outputParameters, *ipp, *opp; - PaStream *stream = NULL; - PaError result = paNoError; - PaQaData myData; - #define FRAMES_PER_BUFFER (64) - const int kNumSeconds = 100; - - /* Setup data for synthesis thread. */ - myData.framesLeft = (unsigned long) (sampleRate * kNumSeconds); - myData.numChannels = numChannels; - myData.mode = mode; - myData.format = format; - switch( format ) - { - case paFloat32: - case paInt32: - case paInt24: - myData.bytesPerSample = 4; - break; -/* case paPackedInt24: - myData.bytesPerSample = 3; - break; */ - default: - myData.bytesPerSample = 2; - break; - } - - if( mode == MODE_INPUT ) - { - inputParameters.device = deviceID; - inputParameters.channelCount = numChannels; - inputParameters.sampleFormat = format; - inputParameters.suggestedLatency = - Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; - inputParameters.hostApiSpecificStreamInfo = NULL; - ipp = &inputParameters; - } - else - { - ipp = NULL; - } - - if( mode == MODE_OUTPUT ) - { - outputParameters.device = deviceID; - outputParameters.channelCount = numChannels; - outputParameters.sampleFormat = format; - outputParameters.suggestedLatency = - Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; - outputParameters.hostApiSpecificStreamInfo = NULL; - opp = &outputParameters; - } - else - { - opp = NULL; - } - - if(paFormatIsSupported == Pa_IsFormatSupported( ipp, opp, sampleRate )) - { - printf("------ TestAdvance: %s, device = %d, rate = %g" - ", numChannels = %d, format = %lu -------\n", - ( mode == MODE_INPUT ) ? "INPUT" : "OUTPUT", - deviceID, sampleRate, numChannels, (unsigned long)format); - EXPECT( ((result = Pa_OpenStream( &stream, - ipp, - opp, - sampleRate, - FRAMES_PER_BUFFER, - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - QaCallback, - &myData ) ) == 0) ); - if( stream ) - { - PaTime oldStamp, newStamp; - unsigned long oldFrames; - int minDelay = ( mode == MODE_INPUT ) ? 1000 : 400; - /* Was: - int minNumBuffers = Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); - int msec = (int) ((minNumBuffers * 3 * 1000.0 * FRAMES_PER_BUFFER) / sampleRate); - */ - int msec = (int)( 3.0 * - (( mode == MODE_INPUT ) ? inputParameters.suggestedLatency : outputParameters.suggestedLatency )); - if( msec < minDelay ) msec = minDelay; - printf("msec = %d\n", msec); /**/ - EXPECT( ((result=Pa_StartStream( stream )) == 0) ); - /* Check to make sure PortAudio is advancing timeStamp. */ - oldStamp = Pa_GetStreamTime(stream); - Pa_Sleep(msec); - newStamp = Pa_GetStreamTime(stream); - printf("oldStamp = %9.6f, newStamp = %9.6f\n", oldStamp, newStamp ); /**/ - EXPECT( (oldStamp < newStamp) ); - /* Check to make sure callback is decrementing framesLeft. */ - oldFrames = myData.framesLeft; - Pa_Sleep(msec); - printf("oldFrames = %lu, myData.framesLeft = %lu\n", oldFrames, myData.framesLeft ); /**/ - EXPECT( (oldFrames > myData.framesLeft) ); - EXPECT( ((result=Pa_CloseStream( stream )) == 0) ); - stream = NULL; - } - } - return 0; -error: - if( stream != NULL ) Pa_CloseStream( stream ); - return -1; -} diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I__0.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I__0.py deleted file mode 100644 index 4112937d45d973bb61ae4ccf825f99a752901ed0..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I__0.py +++ /dev/null @@ -1,57 +0,0 @@ -""" TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) -tool to store its hinting source data. - -TSI0 is the index table containing the lengths and offsets for the glyph -programs and 'extra' programs ('fpgm', 'prep', and 'cvt') that are contained -in the TSI1 table. -""" -from . import DefaultTable -import struct - -tsi0Format = ">HHL" - - -def fixlongs(glyphID, textLength, textOffset): - return int(glyphID), int(textLength), textOffset - - -class table_T_S_I__0(DefaultTable.DefaultTable): - - dependencies = ["TSI1"] - - def decompile(self, data, ttFont): - numGlyphs = ttFont["maxp"].numGlyphs - indices = [] - size = struct.calcsize(tsi0Format) - for i in range(numGlyphs + 5): - glyphID, textLength, textOffset = fixlongs( - *struct.unpack(tsi0Format, data[:size]) - ) - indices.append((glyphID, textLength, textOffset)) - data = data[size:] - assert len(data) == 0 - assert indices[-5] == (0xFFFE, 0, 0xABFC1F34), "bad magic number" - self.indices = indices[:-5] - self.extra_indices = indices[-4:] - - def compile(self, ttFont): - if not hasattr(self, "indices"): - # We have no corresponding table (TSI1 or TSI3); let's return - # no data, which effectively means "ignore us". - return b"" - data = b"" - for index, textLength, textOffset in self.indices: - data = data + struct.pack(tsi0Format, index, textLength, textOffset) - data = data + struct.pack(tsi0Format, 0xFFFE, 0, 0xABFC1F34) - for index, textLength, textOffset in self.extra_indices: - data = data + struct.pack(tsi0Format, index, textLength, textOffset) - return data - - def set(self, indices, extra_indices): - # gets called by 'TSI1' or 'TSI3' - self.indices = indices - self.extra_indices = extra_indices - - def toXML(self, writer, ttFont): - writer.comment("This table will be calculated by the compiler") - writer.newline() diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/cdn/assets/Index-c702b95a.js b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/cdn/assets/Index-c702b95a.js deleted file mode 100644 index 33a7623e227825bdc1db0e2f07622d9ea42a4670..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/cdn/assets/Index-c702b95a.js +++ /dev/null @@ -1,13264 +0,0 @@ -import{n as qv}from"./index-0526d562.js";import{B as Uf}from"./Button-89057c03.js";import{B as gl}from"./BlockLabel-e3b0d1c3.js";import{I as Df}from"./IconButton-16e5dbea.js";import{D as Zv}from"./Download-696bd40c.js";import{c as Qr,a as Jv,S as Vf}from"./Index-37584f50.js";import{F as Ya}from"./File-d0b52941.js";import{U as $v,M as eb}from"./ModifyUpload-87a26b2d.js";import{U as tb}from"./Upload-a4034e93.js";import{E as nb}from"./Empty-937365d8.js";import{U as ib}from"./UploadText-232a3213.js";import{default as _y}from"./Example-786d8148.js";import"./svelte/svelte.js";import"./Clear-2c7bae91.js";/* empty css */function rb(Qe,ke){for(var Ae=0;Aev[f]})}}}return Object.freeze(Object.defineProperty(Qe,Symbol.toStringTag,{value:"Module"}))}var kf={exports:{}};(function(Qe,ke){(function(Ae,v){Qe.exports=v()})(typeof self<"u"?self:typeof Qr<"u"?Qr:Qr,function(){return function(Ae){var v={};function f(B){if(v[B])return v[B].exports;var _=v[B]={i:B,l:!1,exports:{}};return Ae[B].call(_.exports,_,_.exports,f),_.l=!0,_.exports}return f.m=Ae,f.c=v,f.d=function(B,_,x){f.o(B,_)||Object.defineProperty(B,_,{enumerable:!0,get:x})},f.r=function(B){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(B,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(B,"__esModule",{value:!0})},f.t=function(B,_){if(1&_&&(B=f(B)),8&_||4&_&&typeof B=="object"&&B&&B.__esModule)return B;var x=Object.create(null);if(f.r(x),Object.defineProperty(x,"default",{enumerable:!0,value:B}),2&_&&typeof B!="string")for(var u in B)f.d(x,u,function(M){return B[M]}.bind(null,u));return x},f.n=function(B){var _=B&&B.__esModule?function(){return B.default}:function(){return B};return f.d(_,"a",_),_},f.o=function(B,_){return Object.prototype.hasOwnProperty.call(B,_)},f.p="",f(f.s=169)}([function(Ae,v,f){f.d(v,"d",function(){return R}),f.d(v,"e",function(){return C}),f.d(v,"f",function(){return m}),f.d(v,"b",function(){return c}),f.d(v,"a",function(){return E}),f.d(v,"c",function(){return S});var B=f(14),_=f(28),x=f(44),u=f(11),M=f(74),R=function(){function g(l,h){l===void 0&&(l=0),h===void 0&&(h=0),this.x=l,this.y=h}return g.prototype.toString=function(){return"{X: "+this.x+" Y: "+this.y+"}"},g.prototype.getClassName=function(){return"Vector2"},g.prototype.getHashCode=function(){var l=0|this.x;return l=397*l^(0|this.y)},g.prototype.toArray=function(l,h){return h===void 0&&(h=0),l[h]=this.x,l[h+1]=this.y,this},g.prototype.fromArray=function(l,h){return h===void 0&&(h=0),g.FromArrayToRef(l,h,this),this},g.prototype.asArray=function(){var l=new Array;return this.toArray(l,0),l},g.prototype.copyFrom=function(l){return this.x=l.x,this.y=l.y,this},g.prototype.copyFromFloats=function(l,h){return this.x=l,this.y=h,this},g.prototype.set=function(l,h){return this.copyFromFloats(l,h)},g.prototype.add=function(l){return new g(this.x+l.x,this.y+l.y)},g.prototype.addToRef=function(l,h){return h.x=this.x+l.x,h.y=this.y+l.y,this},g.prototype.addInPlace=function(l){return this.x+=l.x,this.y+=l.y,this},g.prototype.addVector3=function(l){return new g(this.x+l.x,this.y+l.y)},g.prototype.subtract=function(l){return new g(this.x-l.x,this.y-l.y)},g.prototype.subtractToRef=function(l,h){return h.x=this.x-l.x,h.y=this.y-l.y,this},g.prototype.subtractInPlace=function(l){return this.x-=l.x,this.y-=l.y,this},g.prototype.multiplyInPlace=function(l){return this.x*=l.x,this.y*=l.y,this},g.prototype.multiply=function(l){return new g(this.x*l.x,this.y*l.y)},g.prototype.multiplyToRef=function(l,h){return h.x=this.x*l.x,h.y=this.y*l.y,this},g.prototype.multiplyByFloats=function(l,h){return new g(this.x*l,this.y*h)},g.prototype.divide=function(l){return new g(this.x/l.x,this.y/l.y)},g.prototype.divideToRef=function(l,h){return h.x=this.x/l.x,h.y=this.y/l.y,this},g.prototype.divideInPlace=function(l){return this.divideToRef(l,this)},g.prototype.negate=function(){return new g(-this.x,-this.y)},g.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this},g.prototype.negateToRef=function(l){return l.copyFromFloats(-1*this.x,-1*this.y)},g.prototype.scaleInPlace=function(l){return this.x*=l,this.y*=l,this},g.prototype.scale=function(l){var h=new g(0,0);return this.scaleToRef(l,h),h},g.prototype.scaleToRef=function(l,h){return h.x=this.x*l,h.y=this.y*l,this},g.prototype.scaleAndAddToRef=function(l,h){return h.x+=this.x*l,h.y+=this.y*l,this},g.prototype.equals=function(l){return l&&this.x===l.x&&this.y===l.y},g.prototype.equalsWithEpsilon=function(l,h){return h===void 0&&(h=_.a),l&&B.a.WithinEpsilon(this.x,l.x,h)&&B.a.WithinEpsilon(this.y,l.y,h)},g.prototype.floor=function(){return new g(Math.floor(this.x),Math.floor(this.y))},g.prototype.fract=function(){return new g(this.x-Math.floor(this.x),this.y-Math.floor(this.y))},g.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},g.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},g.prototype.normalize=function(){var l=this.length();return l===0||(this.x/=l,this.y/=l),this},g.prototype.clone=function(){return new g(this.x,this.y)},g.Zero=function(){return new g(0,0)},g.One=function(){return new g(1,1)},g.FromArray=function(l,h){return h===void 0&&(h=0),new g(l[h],l[h+1])},g.FromArrayToRef=function(l,h,b){b.x=l[h],b.y=l[h+1]},g.CatmullRom=function(l,h,b,T,D){var w=D*D,N=D*w;return new g(.5*(2*h.x+(-l.x+b.x)*D+(2*l.x-5*h.x+4*b.x-T.x)*w+(-l.x+3*h.x-3*b.x+T.x)*N),.5*(2*h.y+(-l.y+b.y)*D+(2*l.y-5*h.y+4*b.y-T.y)*w+(-l.y+3*h.y-3*b.y+T.y)*N))},g.Clamp=function(l,h,b){var T=l.x;T=(T=T>b.x?b.x:T)b.y?b.y:D)h.x?l.x:h.x,l.y>h.y?l.y:h.y)},g.Transform=function(l,h){var b=g.Zero();return g.TransformToRef(l,h,b),b},g.TransformToRef=function(l,h,b){var T=h.m,D=l.x*T[0]+l.y*T[4]+T[12],w=l.x*T[1]+l.y*T[5]+T[13];b.x=D,b.y=w},g.PointInTriangle=function(l,h,b,T){var D=.5*(-b.y*T.x+h.y*(-b.x+T.x)+h.x*(b.y-T.y)+b.x*T.y),w=D<0?-1:1,N=(h.y*T.x-h.x*T.y+(T.y-h.y)*l.x+(h.x-T.x)*l.y)*w,I=(h.x*b.y-h.y*b.x+(h.y-b.y)*l.x+(b.x-h.x)*l.y)*w;return N>0&&I>0&&N+I<2*D*w},g.Distance=function(l,h){return Math.sqrt(g.DistanceSquared(l,h))},g.DistanceSquared=function(l,h){var b=l.x-h.x,T=l.y-h.y;return b*b+T*T},g.Center=function(l,h){var b=l.add(h);return b.scaleInPlace(.5),b},g.DistanceOfPointFromSegment=function(l,h,b){var T=g.DistanceSquared(h,b);if(T===0)return g.Distance(l,h);var D=b.subtract(h),w=Math.max(0,Math.min(1,g.Dot(l.subtract(h),D)/T)),N=h.add(D.multiplyByFloats(w,w));return g.Distance(l,N)},g}(),C=function(){function g(l,h,b){l===void 0&&(l=0),h===void 0&&(h=0),b===void 0&&(b=0),this._isDirty=!0,this._x=l,this._y=h,this._z=b}return Object.defineProperty(g.prototype,"x",{get:function(){return this._x},set:function(l){this._x=l,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"y",{get:function(){return this._y},set:function(l){this._y=l,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"z",{get:function(){return this._z},set:function(l){this._z=l,this._isDirty=!0},enumerable:!1,configurable:!0}),g.prototype.toString=function(){return"{X: "+this._x+" Y:"+this._y+" Z:"+this._z+"}"},g.prototype.getClassName=function(){return"Vector3"},g.prototype.getHashCode=function(){var l=0|this._x;return l=397*(l=397*l^(0|this._y))^(0|this._z)},g.prototype.asArray=function(){var l=[];return this.toArray(l,0),l},g.prototype.toArray=function(l,h){return h===void 0&&(h=0),l[h]=this._x,l[h+1]=this._y,l[h+2]=this._z,this},g.prototype.fromArray=function(l,h){return h===void 0&&(h=0),g.FromArrayToRef(l,h,this),this},g.prototype.toQuaternion=function(){return c.RotationYawPitchRoll(this._y,this._x,this._z)},g.prototype.addInPlace=function(l){return this.addInPlaceFromFloats(l._x,l._y,l._z)},g.prototype.addInPlaceFromFloats=function(l,h,b){return this.x+=l,this.y+=h,this.z+=b,this},g.prototype.add=function(l){return new g(this._x+l._x,this._y+l._y,this._z+l._z)},g.prototype.addToRef=function(l,h){return h.copyFromFloats(this._x+l._x,this._y+l._y,this._z+l._z)},g.prototype.subtractInPlace=function(l){return this.x-=l._x,this.y-=l._y,this.z-=l._z,this},g.prototype.subtract=function(l){return new g(this._x-l._x,this._y-l._y,this._z-l._z)},g.prototype.subtractToRef=function(l,h){return this.subtractFromFloatsToRef(l._x,l._y,l._z,h)},g.prototype.subtractFromFloats=function(l,h,b){return new g(this._x-l,this._y-h,this._z-b)},g.prototype.subtractFromFloatsToRef=function(l,h,b,T){return T.copyFromFloats(this._x-l,this._y-h,this._z-b)},g.prototype.negate=function(){return new g(-this._x,-this._y,-this._z)},g.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},g.prototype.negateToRef=function(l){return l.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)},g.prototype.scaleInPlace=function(l){return this.x*=l,this.y*=l,this.z*=l,this},g.prototype.scale=function(l){return new g(this._x*l,this._y*l,this._z*l)},g.prototype.scaleToRef=function(l,h){return h.copyFromFloats(this._x*l,this._y*l,this._z*l)},g.prototype.scaleAndAddToRef=function(l,h){return h.addInPlaceFromFloats(this._x*l,this._y*l,this._z*l)},g.prototype.projectOnPlane=function(l,h){var b=g.Zero();return this.projectOnPlaneToRef(l,h,b),b},g.prototype.projectOnPlaneToRef=function(l,h,b){var T=l.normal,D=l.d,w=A.Vector3[0];this.subtractToRef(h,w),w.normalize();var N=g.Dot(w,T),I=-(g.Dot(h,T)+D)/N,V=w.scaleInPlace(I);h.addToRef(V,b)},g.prototype.equals=function(l){return l&&this._x===l._x&&this._y===l._y&&this._z===l._z},g.prototype.equalsWithEpsilon=function(l,h){return h===void 0&&(h=_.a),l&&B.a.WithinEpsilon(this._x,l._x,h)&&B.a.WithinEpsilon(this._y,l._y,h)&&B.a.WithinEpsilon(this._z,l._z,h)},g.prototype.equalsToFloats=function(l,h,b){return this._x===l&&this._y===h&&this._z===b},g.prototype.multiplyInPlace=function(l){return this.x*=l._x,this.y*=l._y,this.z*=l._z,this},g.prototype.multiply=function(l){return this.multiplyByFloats(l._x,l._y,l._z)},g.prototype.multiplyToRef=function(l,h){return h.copyFromFloats(this._x*l._x,this._y*l._y,this._z*l._z)},g.prototype.multiplyByFloats=function(l,h,b){return new g(this._x*l,this._y*h,this._z*b)},g.prototype.divide=function(l){return new g(this._x/l._x,this._y/l._y,this._z/l._z)},g.prototype.divideToRef=function(l,h){return h.copyFromFloats(this._x/l._x,this._y/l._y,this._z/l._z)},g.prototype.divideInPlace=function(l){return this.divideToRef(l,this)},g.prototype.minimizeInPlace=function(l){return this.minimizeInPlaceFromFloats(l._x,l._y,l._z)},g.prototype.maximizeInPlace=function(l){return this.maximizeInPlaceFromFloats(l._x,l._y,l._z)},g.prototype.minimizeInPlaceFromFloats=function(l,h,b){return lthis._x&&(this.x=l),h>this._y&&(this.y=h),b>this._z&&(this.z=b),this},g.prototype.isNonUniformWithinEpsilon=function(l){var h=Math.abs(this._x),b=Math.abs(this._y);if(!B.a.WithinEpsilon(h,b,l))return!0;var T=Math.abs(this._z);return!B.a.WithinEpsilon(h,T,l)||!B.a.WithinEpsilon(b,T,l)},Object.defineProperty(g.prototype,"isNonUniform",{get:function(){var l=Math.abs(this._x);return l!==Math.abs(this._y)||l!==Math.abs(this._z)},enumerable:!1,configurable:!0}),g.prototype.floor=function(){return new g(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))},g.prototype.fract=function(){return new g(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))},g.prototype.length=function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)},g.prototype.lengthSquared=function(){return this._x*this._x+this._y*this._y+this._z*this._z},g.prototype.normalize=function(){return this.normalizeFromLength(this.length())},g.prototype.reorderInPlace=function(l){var h=this;return(l=l.toLowerCase())==="xyz"||(A.Vector3[0].copyFrom(this),["x","y","z"].forEach(function(b,T){h[b]=A.Vector3[0][l[T]]})),this},g.prototype.rotateByQuaternionToRef=function(l,h){return l.toRotationMatrix(A.Matrix[0]),g.TransformCoordinatesToRef(this,A.Matrix[0],h),h},g.prototype.rotateByQuaternionAroundPointToRef=function(l,h,b){return this.subtractToRef(h,A.Vector3[0]),A.Vector3[0].rotateByQuaternionToRef(l,A.Vector3[0]),h.addToRef(A.Vector3[0],b),b},g.prototype.cross=function(l){return g.Cross(this,l)},g.prototype.normalizeFromLength=function(l){return l===0||l===1?this:this.scaleInPlace(1/l)},g.prototype.normalizeToNew=function(){var l=new g(0,0,0);return this.normalizeToRef(l),l},g.prototype.normalizeToRef=function(l){var h=this.length();return h===0||h===1?l.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/h,l)},g.prototype.clone=function(){return new g(this._x,this._y,this._z)},g.prototype.copyFrom=function(l){return this.copyFromFloats(l._x,l._y,l._z)},g.prototype.copyFromFloats=function(l,h,b){return this.x=l,this.y=h,this.z=b,this},g.prototype.set=function(l,h,b){return this.copyFromFloats(l,h,b)},g.prototype.setAll=function(l){return this.x=this.y=this.z=l,this},g.GetClipFactor=function(l,h,b,T){var D=g.Dot(l,b)-T;return D/(D-(g.Dot(h,b)-T))},g.GetAngleBetweenVectors=function(l,h,b){var T=l.normalizeToRef(A.Vector3[1]),D=h.normalizeToRef(A.Vector3[2]),w=g.Dot(T,D),N=A.Vector3[3];return g.CrossToRef(T,D,N),g.Dot(N,b)>0?Math.acos(w):-Math.acos(w)},g.FromArray=function(l,h){return h===void 0&&(h=0),new g(l[h],l[h+1],l[h+2])},g.FromFloatArray=function(l,h){return g.FromArray(l,h)},g.FromArrayToRef=function(l,h,b){b.x=l[h],b.y=l[h+1],b.z=l[h+2]},g.FromFloatArrayToRef=function(l,h,b){return g.FromArrayToRef(l,h,b)},g.FromFloatsToRef=function(l,h,b,T){T.copyFromFloats(l,h,b)},g.Zero=function(){return new g(0,0,0)},g.One=function(){return new g(1,1,1)},g.Up=function(){return new g(0,1,0)},Object.defineProperty(g,"UpReadOnly",{get:function(){return g._UpReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(g,"ZeroReadOnly",{get:function(){return g._ZeroReadOnly},enumerable:!1,configurable:!0}),g.Down=function(){return new g(0,-1,0)},g.Forward=function(l){return l===void 0&&(l=!1),new g(0,0,l?-1:1)},g.Backward=function(l){return l===void 0&&(l=!1),new g(0,0,l?1:-1)},g.Right=function(){return new g(1,0,0)},g.Left=function(){return new g(-1,0,0)},g.TransformCoordinates=function(l,h){var b=g.Zero();return g.TransformCoordinatesToRef(l,h,b),b},g.TransformCoordinatesToRef=function(l,h,b){g.TransformCoordinatesFromFloatsToRef(l._x,l._y,l._z,h,b)},g.TransformCoordinatesFromFloatsToRef=function(l,h,b,T,D){var w=T.m,N=l*w[0]+h*w[4]+b*w[8]+w[12],I=l*w[1]+h*w[5]+b*w[9]+w[13],V=l*w[2]+h*w[6]+b*w[10]+w[14],W=1/(l*w[3]+h*w[7]+b*w[11]+w[15]);D.x=N*W,D.y=I*W,D.z=V*W},g.TransformNormal=function(l,h){var b=g.Zero();return g.TransformNormalToRef(l,h,b),b},g.TransformNormalToRef=function(l,h,b){this.TransformNormalFromFloatsToRef(l._x,l._y,l._z,h,b)},g.TransformNormalFromFloatsToRef=function(l,h,b,T,D){var w=T.m;D.x=l*w[0]+h*w[4]+b*w[8],D.y=l*w[1]+h*w[5]+b*w[9],D.z=l*w[2]+h*w[6]+b*w[10]},g.CatmullRom=function(l,h,b,T,D){var w=D*D,N=D*w;return new g(.5*(2*h._x+(-l._x+b._x)*D+(2*l._x-5*h._x+4*b._x-T._x)*w+(-l._x+3*h._x-3*b._x+T._x)*N),.5*(2*h._y+(-l._y+b._y)*D+(2*l._y-5*h._y+4*b._y-T._y)*w+(-l._y+3*h._y-3*b._y+T._y)*N),.5*(2*h._z+(-l._z+b._z)*D+(2*l._z-5*h._z+4*b._z-T._z)*w+(-l._z+3*h._z-3*b._z+T._z)*N))},g.Clamp=function(l,h,b){var T=new g;return g.ClampToRef(l,h,b,T),T},g.ClampToRef=function(l,h,b,T){var D=l._x;D=(D=D>b._x?b._x:D)b._y?b._y:w)b._z?b._z:N)this.x&&(this.x=l.x),l.y>this.y&&(this.y=l.y),l.z>this.z&&(this.z=l.z),l.w>this.w&&(this.w=l.w),this},g.prototype.floor=function(){return new g(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},g.prototype.fract=function(){return new g(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},g.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},g.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},g.prototype.normalize=function(){var l=this.length();return l===0?this:this.scaleInPlace(1/l)},g.prototype.toVector3=function(){return new C(this.x,this.y,this.z)},g.prototype.clone=function(){return new g(this.x,this.y,this.z,this.w)},g.prototype.copyFrom=function(l){return this.x=l.x,this.y=l.y,this.z=l.z,this.w=l.w,this},g.prototype.copyFromFloats=function(l,h,b,T){return this.x=l,this.y=h,this.z=b,this.w=T,this},g.prototype.set=function(l,h,b,T){return this.copyFromFloats(l,h,b,T)},g.prototype.setAll=function(l){return this.x=this.y=this.z=this.w=l,this},g.FromArray=function(l,h){return h||(h=0),new g(l[h],l[h+1],l[h+2],l[h+3])},g.FromArrayToRef=function(l,h,b){b.x=l[h],b.y=l[h+1],b.z=l[h+2],b.w=l[h+3]},g.FromFloatArrayToRef=function(l,h,b){g.FromArrayToRef(l,h,b)},g.FromFloatsToRef=function(l,h,b,T,D){D.x=l,D.y=h,D.z=b,D.w=T},g.Zero=function(){return new g(0,0,0,0)},g.One=function(){return new g(1,1,1,1)},g.Normalize=function(l){var h=g.Zero();return g.NormalizeToRef(l,h),h},g.NormalizeToRef=function(l,h){h.copyFrom(l),h.normalize()},g.Minimize=function(l,h){var b=l.clone();return b.minimizeInPlace(h),b},g.Maximize=function(l,h){var b=l.clone();return b.maximizeInPlace(h),b},g.Distance=function(l,h){return Math.sqrt(g.DistanceSquared(l,h))},g.DistanceSquared=function(l,h){var b=l.x-h.x,T=l.y-h.y,D=l.z-h.z,w=l.w-h.w;return b*b+T*T+D*D+w*w},g.Center=function(l,h){var b=l.add(h);return b.scaleInPlace(.5),b},g.TransformNormal=function(l,h){var b=g.Zero();return g.TransformNormalToRef(l,h,b),b},g.TransformNormalToRef=function(l,h,b){var T=h.m,D=l.x*T[0]+l.y*T[4]+l.z*T[8],w=l.x*T[1]+l.y*T[5]+l.z*T[9],N=l.x*T[2]+l.y*T[6]+l.z*T[10];b.x=D,b.y=w,b.z=N,b.w=l.w},g.TransformNormalFromFloatsToRef=function(l,h,b,T,D,w){var N=D.m;w.x=l*N[0]+h*N[4]+b*N[8],w.y=l*N[1]+h*N[5]+b*N[9],w.z=l*N[2]+h*N[6]+b*N[10],w.w=T},g.FromVector3=function(l,h){return h===void 0&&(h=0),new g(l._x,l._y,l._z,h)},g}(),c=function(){function g(l,h,b,T){l===void 0&&(l=0),h===void 0&&(h=0),b===void 0&&(b=0),T===void 0&&(T=1),this._isDirty=!0,this._x=l,this._y=h,this._z=b,this._w=T}return Object.defineProperty(g.prototype,"x",{get:function(){return this._x},set:function(l){this._x=l,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"y",{get:function(){return this._y},set:function(l){this._y=l,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"z",{get:function(){return this._z},set:function(l){this._z=l,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"w",{get:function(){return this._w},set:function(l){this._w=l,this._isDirty=!0},enumerable:!1,configurable:!0}),g.prototype.toString=function(){return"{X: "+this._x+" Y:"+this._y+" Z:"+this._z+" W:"+this._w+"}"},g.prototype.getClassName=function(){return"Quaternion"},g.prototype.getHashCode=function(){var l=0|this._x;return l=397*(l=397*(l=397*l^(0|this._y))^(0|this._z))^(0|this._w)},g.prototype.asArray=function(){return[this._x,this._y,this._z,this._w]},g.prototype.equals=function(l){return l&&this._x===l._x&&this._y===l._y&&this._z===l._z&&this._w===l._w},g.prototype.equalsWithEpsilon=function(l,h){return h===void 0&&(h=_.a),l&&B.a.WithinEpsilon(this._x,l._x,h)&&B.a.WithinEpsilon(this._y,l._y,h)&&B.a.WithinEpsilon(this._z,l._z,h)&&B.a.WithinEpsilon(this._w,l._w,h)},g.prototype.clone=function(){return new g(this._x,this._y,this._z,this._w)},g.prototype.copyFrom=function(l){return this.x=l._x,this.y=l._y,this.z=l._z,this.w=l._w,this},g.prototype.copyFromFloats=function(l,h,b,T){return this.x=l,this.y=h,this.z=b,this.w=T,this},g.prototype.set=function(l,h,b,T){return this.copyFromFloats(l,h,b,T)},g.prototype.add=function(l){return new g(this._x+l._x,this._y+l._y,this._z+l._z,this._w+l._w)},g.prototype.addInPlace=function(l){return this._x+=l._x,this._y+=l._y,this._z+=l._z,this._w+=l._w,this},g.prototype.subtract=function(l){return new g(this._x-l._x,this._y-l._y,this._z-l._z,this._w-l._w)},g.prototype.scale=function(l){return new g(this._x*l,this._y*l,this._z*l,this._w*l)},g.prototype.scaleToRef=function(l,h){return h.x=this._x*l,h.y=this._y*l,h.z=this._z*l,h.w=this._w*l,this},g.prototype.scaleInPlace=function(l){return this.x*=l,this.y*=l,this.z*=l,this.w*=l,this},g.prototype.scaleAndAddToRef=function(l,h){return h.x+=this._x*l,h.y+=this._y*l,h.z+=this._z*l,h.w+=this._w*l,this},g.prototype.multiply=function(l){var h=new g(0,0,0,1);return this.multiplyToRef(l,h),h},g.prototype.multiplyToRef=function(l,h){var b=this._x*l._w+this._y*l._z-this._z*l._y+this._w*l._x,T=-this._x*l._z+this._y*l._w+this._z*l._x+this._w*l._y,D=this._x*l._y-this._y*l._x+this._z*l._w+this._w*l._z,w=-this._x*l._x-this._y*l._y-this._z*l._z+this._w*l._w;return h.copyFromFloats(b,T,D,w),this},g.prototype.multiplyInPlace=function(l){return this.multiplyToRef(l,this),this},g.prototype.conjugateToRef=function(l){return l.copyFromFloats(-this._x,-this._y,-this._z,this._w),this},g.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},g.prototype.conjugate=function(){return new g(-this._x,-this._y,-this._z,this._w)},g.prototype.length=function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},g.prototype.normalize=function(){var l=this.length();if(l===0)return this;var h=1/l;return this.x*=h,this.y*=h,this.z*=h,this.w*=h,this},g.prototype.toEulerAngles=function(l){var h=C.Zero();return this.toEulerAnglesToRef(h),h},g.prototype.toEulerAnglesToRef=function(l){var h=this._z,b=this._x,T=this._y,D=this._w,w=D*D,N=h*h,I=b*b,V=T*T,W=T*h-b*D;return W<-.4999999?(l.y=2*Math.atan2(T,D),l.x=Math.PI/2,l.z=0):W>.4999999?(l.y=2*Math.atan2(T,D),l.x=-Math.PI/2,l.z=0):(l.z=Math.atan2(2*(b*T+h*D),-N-I+V+w),l.x=Math.asin(-2*(h*T-b*D)),l.y=Math.atan2(2*(h*b+T*D),N-I-V+w)),this},g.prototype.toRotationMatrix=function(l){return E.FromQuaternionToRef(this,l),this},g.prototype.fromRotationMatrix=function(l){return g.FromRotationMatrixToRef(l,this),this},g.FromRotationMatrix=function(l){var h=new g;return g.FromRotationMatrixToRef(l,h),h},g.FromRotationMatrixToRef=function(l,h){var b,T=l.m,D=T[0],w=T[4],N=T[8],I=T[1],V=T[5],W=T[9],j=T[2],ne=T[6],te=T[10],de=D+V+te;de>0?(b=.5/Math.sqrt(de+1),h.w=.25/b,h.x=(ne-W)*b,h.y=(N-j)*b,h.z=(I-w)*b):D>V&&D>te?(b=2*Math.sqrt(1+D-V-te),h.w=(ne-W)/b,h.x=.25*b,h.y=(w+I)/b,h.z=(N+j)/b):V>te?(b=2*Math.sqrt(1+V-D-te),h.w=(N-j)/b,h.x=(w+I)/b,h.y=.25*b,h.z=(W+ne)/b):(b=2*Math.sqrt(1+te-D-V),h.w=(I-w)/b,h.x=(N+j)/b,h.y=(W+ne)/b,h.z=.25*b)},g.Dot=function(l,h){return l._x*h._x+l._y*h._y+l._z*h._z+l._w*h._w},g.AreClose=function(l,h){return g.Dot(l,h)>=0},g.Zero=function(){return new g(0,0,0,0)},g.Inverse=function(l){return new g(-l._x,-l._y,-l._z,l._w)},g.InverseToRef=function(l,h){return h.set(-l._x,-l._y,-l._z,l._w),h},g.Identity=function(){return new g(0,0,0,1)},g.IsIdentity=function(l){return l&&l._x===0&&l._y===0&&l._z===0&&l._w===1},g.RotationAxis=function(l,h){return g.RotationAxisToRef(l,h,new g)},g.RotationAxisToRef=function(l,h,b){var T=Math.sin(h/2);return l.normalize(),b.w=Math.cos(h/2),b.x=l._x*T,b.y=l._y*T,b.z=l._z*T,b},g.FromArray=function(l,h){return h||(h=0),new g(l[h],l[h+1],l[h+2],l[h+3])},g.FromArrayToRef=function(l,h,b){b.x=l[h],b.y=l[h+1],b.z=l[h+2],b.w=l[h+3]},g.FromEulerAngles=function(l,h,b){var T=new g;return g.RotationYawPitchRollToRef(h,l,b,T),T},g.FromEulerAnglesToRef=function(l,h,b,T){return g.RotationYawPitchRollToRef(h,l,b,T),T},g.FromEulerVector=function(l){var h=new g;return g.RotationYawPitchRollToRef(l._y,l._x,l._z,h),h},g.FromEulerVectorToRef=function(l,h){return g.RotationYawPitchRollToRef(l._y,l._x,l._z,h),h},g.RotationYawPitchRoll=function(l,h,b){var T=new g;return g.RotationYawPitchRollToRef(l,h,b,T),T},g.RotationYawPitchRollToRef=function(l,h,b,T){var D=.5*b,w=.5*h,N=.5*l,I=Math.sin(D),V=Math.cos(D),W=Math.sin(w),j=Math.cos(w),ne=Math.sin(N),te=Math.cos(N);T.x=te*W*V+ne*j*I,T.y=ne*j*V-te*W*I,T.z=te*j*I-ne*W*V,T.w=te*j*V+ne*W*I},g.RotationAlphaBetaGamma=function(l,h,b){var T=new g;return g.RotationAlphaBetaGammaToRef(l,h,b,T),T},g.RotationAlphaBetaGammaToRef=function(l,h,b,T){var D=.5*(b+l),w=.5*(b-l),N=.5*h;T.x=Math.cos(w)*Math.sin(N),T.y=Math.sin(w)*Math.sin(N),T.z=Math.sin(D)*Math.cos(N),T.w=Math.cos(D)*Math.cos(N)},g.RotationQuaternionFromAxis=function(l,h,b){var T=new g(0,0,0,0);return g.RotationQuaternionFromAxisToRef(l,h,b,T),T},g.RotationQuaternionFromAxisToRef=function(l,h,b,T){var D=A.Matrix[0];E.FromXYZAxesToRef(l.normalize(),h.normalize(),b.normalize(),D),g.FromRotationMatrixToRef(D,T)},g.Slerp=function(l,h,b){var T=g.Identity();return g.SlerpToRef(l,h,b,T),T},g.SlerpToRef=function(l,h,b,T){var D,w,N=l._x*h._x+l._y*h._y+l._z*h._z+l._w*h._w,I=!1;if(N<0&&(I=!0,N=-N),N>.999999)w=1-b,D=I?-b:b;else{var V=Math.acos(N),W=1/Math.sin(V);w=Math.sin((1-b)*V)*W,D=I?-Math.sin(b*V)*W:Math.sin(b*V)*W}T.x=w*l._x+D*h._x,T.y=w*l._y+D*h._y,T.z=w*l._z+D*h._z,T.w=w*l._w+D*h._w},g.Hermite=function(l,h,b,T,D){var w=D*D,N=D*w,I=2*N-3*w+1,V=-2*N+3*w,W=N-2*w+D,j=N-w;return new g(l._x*I+b._x*V+h._x*W+T._x*j,l._y*I+b._y*V+h._y*W+T._y*j,l._z*I+b._z*V+h._z*W+T._z*j,l._w*I+b._w*V+h._w*W+T._w*j)},g}(),E=function(){function g(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,M.a.MatrixTrackPrecisionChange&&M.a.MatrixTrackedMatrices.push(this),this._m=new M.a.MatrixCurrentType(16),this._updateIdentityStatus(!1)}return Object.defineProperty(g,"Use64Bits",{get:function(){return M.a.MatrixUse64Bits},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"m",{get:function(){return this._m},enumerable:!1,configurable:!0}),g.prototype._markAsUpdated=function(){this.updateFlag=g._updateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0},g.prototype._updateIdentityStatus=function(l,h,b,T){h===void 0&&(h=!1),b===void 0&&(b=!1),T===void 0&&(T=!0),this.updateFlag=g._updateFlagSeed++,this._isIdentity=l,this._isIdentity3x2=l||b,this._isIdentityDirty=!this._isIdentity&&h,this._isIdentity3x2Dirty=!this._isIdentity3x2&&T},g.prototype.isIdentity=function(){if(this._isIdentityDirty){this._isIdentityDirty=!1;var l=this._m;this._isIdentity=l[0]===1&&l[1]===0&&l[2]===0&&l[3]===0&&l[4]===0&&l[5]===1&&l[6]===0&&l[7]===0&&l[8]===0&&l[9]===0&&l[10]===1&&l[11]===0&&l[12]===0&&l[13]===0&&l[14]===0&&l[15]===1}return this._isIdentity},g.prototype.isIdentityAs3x2=function(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1||this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2},g.prototype.determinant=function(){if(this._isIdentity===!0)return 1;var l=this._m,h=l[0],b=l[1],T=l[2],D=l[3],w=l[4],N=l[5],I=l[6],V=l[7],W=l[8],j=l[9],ne=l[10],te=l[11],de=l[12],pe=l[13],ae=l[14],ee=l[15],K=ne*ee-ae*te,$=j*ee-pe*te,L=j*ae-pe*ne,G=W*ee-de*te,Q=W*ae-ne*de,oe=W*pe-de*j;return h*+(N*K-I*$+V*L)+b*-(w*K-I*G+V*Q)+T*+(w*$-N*G+V*oe)+D*-(w*L-N*Q+I*oe)},g.prototype.toArray=function(){return this._m},g.prototype.asArray=function(){return this._m},g.prototype.invert=function(){return this.invertToRef(this),this},g.prototype.reset=function(){return g.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this},g.prototype.add=function(l){var h=new g;return this.addToRef(l,h),h},g.prototype.addToRef=function(l,h){for(var b=this._m,T=h._m,D=l.m,w=0;w<16;w++)T[w]=b[w]+D[w];return h._markAsUpdated(),this},g.prototype.addToSelf=function(l){for(var h=this._m,b=l.m,T=0;T<16;T++)h[T]+=b[T];return this._markAsUpdated(),this},g.prototype.invertToRef=function(l){if(this._isIdentity===!0)return g.IdentityToRef(l),this;var h=this._m,b=h[0],T=h[1],D=h[2],w=h[3],N=h[4],I=h[5],V=h[6],W=h[7],j=h[8],ne=h[9],te=h[10],de=h[11],pe=h[12],ae=h[13],ee=h[14],K=h[15],$=te*K-ee*de,L=ne*K-ae*de,G=ne*ee-ae*te,Q=j*K-pe*de,oe=j*ee-te*pe,re=j*ae-pe*ne,Y=+(I*$-V*L+W*G),k=-(N*$-V*Q+W*oe),H=+(N*L-I*Q+W*re),Z=-(N*G-I*oe+V*re),X=b*Y+T*k+D*H+w*Z;if(X===0)return l.copyFrom(this),this;var q=1/X,he=V*K-ee*W,ge=I*K-ae*W,me=I*ee-ae*V,_e=N*K-pe*W,be=N*ee-pe*V,Ce=N*ae-pe*I,ye=V*de-te*W,Be=I*de-ne*W,Ge=I*te-ne*V,Xe=N*de-j*W,He=N*te-j*V,We=N*ne-j*I,Ze=-(T*$-D*L+w*G),ze=+(b*$-D*Q+w*oe),it=-(b*L-T*Q+w*re),et=+(b*G-T*oe+D*re),lt=+(T*he-D*ge+w*me),ct=-(b*he-D*_e+w*be),mt=+(b*ge-T*_e+w*Ce),St=-(b*me-T*be+D*Ce),wt=-(T*ye-D*Be+w*Ge),It=+(b*ye-D*Xe+w*He),Pt=-(b*Be-T*Xe+w*We),Ot=+(b*Ge-T*He+D*We);return g.FromValuesToRef(Y*q,Ze*q,lt*q,wt*q,k*q,ze*q,ct*q,It*q,H*q,it*q,mt*q,Pt*q,Z*q,et*q,St*q,Ot*q,l),this},g.prototype.addAtIndex=function(l,h){return this._m[l]+=h,this._markAsUpdated(),this},g.prototype.multiplyAtIndex=function(l,h){return this._m[l]*=h,this._markAsUpdated(),this},g.prototype.setTranslationFromFloats=function(l,h,b){return this._m[12]=l,this._m[13]=h,this._m[14]=b,this._markAsUpdated(),this},g.prototype.addTranslationFromFloats=function(l,h,b){return this._m[12]+=l,this._m[13]+=h,this._m[14]+=b,this._markAsUpdated(),this},g.prototype.setTranslation=function(l){return this.setTranslationFromFloats(l._x,l._y,l._z)},g.prototype.getTranslation=function(){return new C(this._m[12],this._m[13],this._m[14])},g.prototype.getTranslationToRef=function(l){return l.x=this._m[12],l.y=this._m[13],l.z=this._m[14],this},g.prototype.removeRotationAndScaling=function(){var l=this.m;return g.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,l[12],l[13],l[14],l[15],this),this._updateIdentityStatus(l[12]===0&&l[13]===0&&l[14]===0&&l[15]===1),this},g.prototype.multiply=function(l){var h=new g;return this.multiplyToRef(l,h),h},g.prototype.copyFrom=function(l){l.copyToArray(this._m);var h=l;return this._updateIdentityStatus(h._isIdentity,h._isIdentityDirty,h._isIdentity3x2,h._isIdentity3x2Dirty),this},g.prototype.copyToArray=function(l,h){h===void 0&&(h=0);var b=this._m;return l[h]=b[0],l[h+1]=b[1],l[h+2]=b[2],l[h+3]=b[3],l[h+4]=b[4],l[h+5]=b[5],l[h+6]=b[6],l[h+7]=b[7],l[h+8]=b[8],l[h+9]=b[9],l[h+10]=b[10],l[h+11]=b[11],l[h+12]=b[12],l[h+13]=b[13],l[h+14]=b[14],l[h+15]=b[15],this},g.prototype.multiplyToRef=function(l,h){return this._isIdentity?(h.copyFrom(l),this):l._isIdentity?(h.copyFrom(this),this):(this.multiplyToArray(l,h._m,0),h._markAsUpdated(),this)},g.prototype.multiplyToArray=function(l,h,b){var T=this._m,D=l.m,w=T[0],N=T[1],I=T[2],V=T[3],W=T[4],j=T[5],ne=T[6],te=T[7],de=T[8],pe=T[9],ae=T[10],ee=T[11],K=T[12],$=T[13],L=T[14],G=T[15],Q=D[0],oe=D[1],re=D[2],Y=D[3],k=D[4],H=D[5],Z=D[6],X=D[7],q=D[8],he=D[9],ge=D[10],me=D[11],_e=D[12],be=D[13],Ce=D[14],ye=D[15];return h[b]=w*Q+N*k+I*q+V*_e,h[b+1]=w*oe+N*H+I*he+V*be,h[b+2]=w*re+N*Z+I*ge+V*Ce,h[b+3]=w*Y+N*X+I*me+V*ye,h[b+4]=W*Q+j*k+ne*q+te*_e,h[b+5]=W*oe+j*H+ne*he+te*be,h[b+6]=W*re+j*Z+ne*ge+te*Ce,h[b+7]=W*Y+j*X+ne*me+te*ye,h[b+8]=de*Q+pe*k+ae*q+ee*_e,h[b+9]=de*oe+pe*H+ae*he+ee*be,h[b+10]=de*re+pe*Z+ae*ge+ee*Ce,h[b+11]=de*Y+pe*X+ae*me+ee*ye,h[b+12]=K*Q+$*k+L*q+G*_e,h[b+13]=K*oe+$*H+L*he+G*be,h[b+14]=K*re+$*Z+L*ge+G*Ce,h[b+15]=K*Y+$*X+L*me+G*ye,this},g.prototype.equals=function(l){var h=l;if(!h)return!1;if((this._isIdentity||h._isIdentity)&&!this._isIdentityDirty&&!h._isIdentityDirty)return this._isIdentity&&h._isIdentity;var b=this.m,T=h.m;return b[0]===T[0]&&b[1]===T[1]&&b[2]===T[2]&&b[3]===T[3]&&b[4]===T[4]&&b[5]===T[5]&&b[6]===T[6]&&b[7]===T[7]&&b[8]===T[8]&&b[9]===T[9]&&b[10]===T[10]&&b[11]===T[11]&&b[12]===T[12]&&b[13]===T[13]&&b[14]===T[14]&&b[15]===T[15]},g.prototype.clone=function(){var l=new g;return l.copyFrom(this),l},g.prototype.getClassName=function(){return"Matrix"},g.prototype.getHashCode=function(){for(var l=0|this._m[0],h=1;h<16;h++)l=397*l^(0|this._m[h]);return l},g.prototype.decompose=function(l,h,b){if(this._isIdentity)return b&&b.setAll(0),l&&l.setAll(1),h&&h.copyFromFloats(0,0,0,1),!0;var T=this._m;if(b&&b.copyFromFloats(T[12],T[13],T[14]),(l=l||A.Vector3[0]).x=Math.sqrt(T[0]*T[0]+T[1]*T[1]+T[2]*T[2]),l.y=Math.sqrt(T[4]*T[4]+T[5]*T[5]+T[6]*T[6]),l.z=Math.sqrt(T[8]*T[8]+T[9]*T[9]+T[10]*T[10]),this.determinant()<=0&&(l.y*=-1),l._x===0||l._y===0||l._z===0)return h&&h.copyFromFloats(0,0,0,1),!1;if(h){var D=1/l._x,w=1/l._y,N=1/l._z;g.FromValuesToRef(T[0]*D,T[1]*D,T[2]*D,0,T[4]*w,T[5]*w,T[6]*w,0,T[8]*N,T[9]*N,T[10]*N,0,0,0,0,1,A.Matrix[0]),c.FromRotationMatrixToRef(A.Matrix[0],h)}return!0},g.prototype.getRow=function(l){if(l<0||l>3)return null;var h=4*l;return new m(this._m[h+0],this._m[h+1],this._m[h+2],this._m[h+3])},g.prototype.setRow=function(l,h){return this.setRowFromFloats(l,h.x,h.y,h.z,h.w)},g.prototype.transpose=function(){return g.Transpose(this)},g.prototype.transposeToRef=function(l){return g.TransposeToRef(this,l),this},g.prototype.setRowFromFloats=function(l,h,b,T,D){if(l<0||l>3)return this;var w=4*l;return this._m[w+0]=h,this._m[w+1]=b,this._m[w+2]=T,this._m[w+3]=D,this._markAsUpdated(),this},g.prototype.scale=function(l){var h=new g;return this.scaleToRef(l,h),h},g.prototype.scaleToRef=function(l,h){for(var b=0;b<16;b++)h._m[b]=this._m[b]*l;return h._markAsUpdated(),this},g.prototype.scaleAndAddToRef=function(l,h){for(var b=0;b<16;b++)h._m[b]+=this._m[b]*l;return h._markAsUpdated(),this},g.prototype.toNormalMatrix=function(l){var h=A.Matrix[0];this.invertToRef(h),h.transposeToRef(l);var b=l._m;g.FromValuesToRef(b[0],b[1],b[2],0,b[4],b[5],b[6],0,b[8],b[9],b[10],0,0,0,0,1,l)},g.prototype.getRotationMatrix=function(){var l=new g;return this.getRotationMatrixToRef(l),l},g.prototype.getRotationMatrixToRef=function(l){var h=A.Vector3[0];if(!this.decompose(h))return g.IdentityToRef(l),this;var b=this._m,T=1/h._x,D=1/h._y,w=1/h._z;return g.FromValuesToRef(b[0]*T,b[1]*T,b[2]*T,0,b[4]*D,b[5]*D,b[6]*D,0,b[8]*w,b[9]*w,b[10]*w,0,0,0,0,1,l),this},g.prototype.toggleModelMatrixHandInPlace=function(){var l=this._m;l[2]*=-1,l[6]*=-1,l[8]*=-1,l[9]*=-1,l[14]*=-1,this._markAsUpdated()},g.prototype.toggleProjectionMatrixHandInPlace=function(){var l=this._m;l[8]*=-1,l[9]*=-1,l[10]*=-1,l[11]*=-1,this._markAsUpdated()},g.FromArray=function(l,h){h===void 0&&(h=0);var b=new g;return g.FromArrayToRef(l,h,b),b},g.FromArrayToRef=function(l,h,b){for(var T=0;T<16;T++)b._m[T]=l[T+h];b._markAsUpdated()},g.FromFloat32ArrayToRefScaled=function(l,h,b,T){for(var D=0;D<16;D++)T._m[D]=l[D+h]*b;T._markAsUpdated()},Object.defineProperty(g,"IdentityReadOnly",{get:function(){return g._identityReadOnly},enumerable:!1,configurable:!0}),g.FromValuesToRef=function(l,h,b,T,D,w,N,I,V,W,j,ne,te,de,pe,ae,ee){var K=ee._m;K[0]=l,K[1]=h,K[2]=b,K[3]=T,K[4]=D,K[5]=w,K[6]=N,K[7]=I,K[8]=V,K[9]=W,K[10]=j,K[11]=ne,K[12]=te,K[13]=de,K[14]=pe,K[15]=ae,ee._markAsUpdated()},g.FromValues=function(l,h,b,T,D,w,N,I,V,W,j,ne,te,de,pe,ae){var ee=new g,K=ee._m;return K[0]=l,K[1]=h,K[2]=b,K[3]=T,K[4]=D,K[5]=w,K[6]=N,K[7]=I,K[8]=V,K[9]=W,K[10]=j,K[11]=ne,K[12]=te,K[13]=de,K[14]=pe,K[15]=ae,ee._markAsUpdated(),ee},g.Compose=function(l,h,b){var T=new g;return g.ComposeToRef(l,h,b,T),T},g.ComposeToRef=function(l,h,b,T){var D=T._m,w=h._x,N=h._y,I=h._z,V=h._w,W=w+w,j=N+N,ne=I+I,te=w*W,de=w*j,pe=w*ne,ae=N*j,ee=N*ne,K=I*ne,$=V*W,L=V*j,G=V*ne,Q=l._x,oe=l._y,re=l._z;D[0]=(1-(ae+K))*Q,D[1]=(de+G)*Q,D[2]=(pe-L)*Q,D[3]=0,D[4]=(de-G)*oe,D[5]=(1-(te+K))*oe,D[6]=(ee+$)*oe,D[7]=0,D[8]=(pe+L)*re,D[9]=(ee-$)*re,D[10]=(1-(te+ae))*re,D[11]=0,D[12]=b._x,D[13]=b._y,D[14]=b._z,D[15]=1,T._markAsUpdated()},g.Identity=function(){var l=g.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return l._updateIdentityStatus(!0),l},g.IdentityToRef=function(l){g.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,l),l._updateIdentityStatus(!0)},g.Zero=function(){var l=g.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return l._updateIdentityStatus(!1),l},g.RotationX=function(l){var h=new g;return g.RotationXToRef(l,h),h},g.Invert=function(l){var h=new g;return l.invertToRef(h),h},g.RotationXToRef=function(l,h){var b=Math.sin(l),T=Math.cos(l);g.FromValuesToRef(1,0,0,0,0,T,b,0,0,-b,T,0,0,0,0,1,h),h._updateIdentityStatus(T===1&&b===0)},g.RotationY=function(l){var h=new g;return g.RotationYToRef(l,h),h},g.RotationYToRef=function(l,h){var b=Math.sin(l),T=Math.cos(l);g.FromValuesToRef(T,0,-b,0,0,1,0,0,b,0,T,0,0,0,0,1,h),h._updateIdentityStatus(T===1&&b===0)},g.RotationZ=function(l){var h=new g;return g.RotationZToRef(l,h),h},g.RotationZToRef=function(l,h){var b=Math.sin(l),T=Math.cos(l);g.FromValuesToRef(T,b,0,0,-b,T,0,0,0,0,1,0,0,0,0,1,h),h._updateIdentityStatus(T===1&&b===0)},g.RotationAxis=function(l,h){var b=new g;return g.RotationAxisToRef(l,h,b),b},g.RotationAxisToRef=function(l,h,b){var T=Math.sin(-h),D=Math.cos(-h),w=1-D;l.normalize();var N=b._m;N[0]=l._x*l._x*w+D,N[1]=l._x*l._y*w-l._z*T,N[2]=l._x*l._z*w+l._y*T,N[3]=0,N[4]=l._y*l._x*w+l._z*T,N[5]=l._y*l._y*w+D,N[6]=l._y*l._z*w-l._x*T,N[7]=0,N[8]=l._z*l._x*w-l._y*T,N[9]=l._z*l._y*w+l._x*T,N[10]=l._z*l._z*w+D,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,b._markAsUpdated()},g.RotationAlignToRef=function(l,h,b){var T=C.Cross(h,l),D=C.Dot(h,l),w=1/(1+D),N=b._m;N[0]=T._x*T._x*w+D,N[1]=T._y*T._x*w-T._z,N[2]=T._z*T._x*w+T._y,N[3]=0,N[4]=T._x*T._y*w+T._z,N[5]=T._y*T._y*w+D,N[6]=T._z*T._y*w-T._x,N[7]=0,N[8]=T._x*T._z*w-T._y,N[9]=T._y*T._z*w+T._x,N[10]=T._z*T._z*w+D,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,b._markAsUpdated()},g.RotationYawPitchRoll=function(l,h,b){var T=new g;return g.RotationYawPitchRollToRef(l,h,b,T),T},g.RotationYawPitchRollToRef=function(l,h,b,T){c.RotationYawPitchRollToRef(l,h,b,A.Quaternion[0]),A.Quaternion[0].toRotationMatrix(T)},g.Scaling=function(l,h,b){var T=new g;return g.ScalingToRef(l,h,b,T),T},g.ScalingToRef=function(l,h,b,T){g.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,b,0,0,0,0,1,T),T._updateIdentityStatus(l===1&&h===1&&b===1)},g.Translation=function(l,h,b){var T=new g;return g.TranslationToRef(l,h,b,T),T},g.TranslationToRef=function(l,h,b,T){g.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,l,h,b,1,T),T._updateIdentityStatus(l===0&&h===0&&b===0)},g.Lerp=function(l,h,b){var T=new g;return g.LerpToRef(l,h,b,T),T},g.LerpToRef=function(l,h,b,T){for(var D=T._m,w=l.m,N=h.m,I=0;I<16;I++)D[I]=w[I]*(1-b)+N[I]*b;T._markAsUpdated()},g.DecomposeLerp=function(l,h,b){var T=new g;return g.DecomposeLerpToRef(l,h,b,T),T},g.DecomposeLerpToRef=function(l,h,b,T){var D=A.Vector3[0],w=A.Quaternion[0],N=A.Vector3[1];l.decompose(D,w,N);var I=A.Vector3[2],V=A.Quaternion[1],W=A.Vector3[3];h.decompose(I,V,W);var j=A.Vector3[4];C.LerpToRef(D,I,b,j);var ne=A.Quaternion[2];c.SlerpToRef(w,V,b,ne);var te=A.Vector3[5];C.LerpToRef(N,W,b,te),g.ComposeToRef(j,ne,te,T)},g.LookAtLH=function(l,h,b){var T=new g;return g.LookAtLHToRef(l,h,b,T),T},g.LookAtLHToRef=function(l,h,b,T){var D=A.Vector3[0],w=A.Vector3[1],N=A.Vector3[2];h.subtractToRef(l,N),N.normalize(),C.CrossToRef(b,N,D);var I=D.lengthSquared();I===0?D.x=1:D.normalizeFromLength(Math.sqrt(I)),C.CrossToRef(N,D,w),w.normalize();var V=-C.Dot(D,l),W=-C.Dot(w,l),j=-C.Dot(N,l);g.FromValuesToRef(D._x,w._x,N._x,0,D._y,w._y,N._y,0,D._z,w._z,N._z,0,V,W,j,1,T)},g.LookAtRH=function(l,h,b){var T=new g;return g.LookAtRHToRef(l,h,b,T),T},g.LookAtRHToRef=function(l,h,b,T){var D=A.Vector3[0],w=A.Vector3[1],N=A.Vector3[2];l.subtractToRef(h,N),N.normalize(),C.CrossToRef(b,N,D);var I=D.lengthSquared();I===0?D.x=1:D.normalizeFromLength(Math.sqrt(I)),C.CrossToRef(N,D,w),w.normalize();var V=-C.Dot(D,l),W=-C.Dot(w,l),j=-C.Dot(N,l);g.FromValuesToRef(D._x,w._x,N._x,0,D._y,w._y,N._y,0,D._z,w._z,N._z,0,V,W,j,1,T)},g.OrthoLH=function(l,h,b,T){var D=new g;return g.OrthoLHToRef(l,h,b,T,D),D},g.OrthoLHToRef=function(l,h,b,T,D){var w=2/l,N=2/h,I=2/(T-b),V=-(T+b)/(T-b);g.FromValuesToRef(w,0,0,0,0,N,0,0,0,0,I,0,0,0,V,1,D),D._updateIdentityStatus(w===1&&N===1&&I===1&&V===0)},g.OrthoOffCenterLH=function(l,h,b,T,D,w){var N=new g;return g.OrthoOffCenterLHToRef(l,h,b,T,D,w,N),N},g.OrthoOffCenterLHToRef=function(l,h,b,T,D,w,N){var I=2/(h-l),V=2/(T-b),W=2/(w-D),j=-(w+D)/(w-D),ne=(l+h)/(l-h),te=(T+b)/(b-T);g.FromValuesToRef(I,0,0,0,0,V,0,0,0,0,W,0,ne,te,j,1,N),N._markAsUpdated()},g.OrthoOffCenterRH=function(l,h,b,T,D,w){var N=new g;return g.OrthoOffCenterRHToRef(l,h,b,T,D,w,N),N},g.OrthoOffCenterRHToRef=function(l,h,b,T,D,w,N){g.OrthoOffCenterLHToRef(l,h,b,T,D,w,N),N._m[10]*=-1},g.PerspectiveLH=function(l,h,b,T){var D=new g,w=2*b/l,N=2*b/h,I=(T+b)/(T-b),V=-2*T*b/(T-b);return g.FromValuesToRef(w,0,0,0,0,N,0,0,0,0,I,1,0,0,V,0,D),D._updateIdentityStatus(!1),D},g.PerspectiveFovLH=function(l,h,b,T){var D=new g;return g.PerspectiveFovLHToRef(l,h,b,T,D),D},g.PerspectiveFovLHToRef=function(l,h,b,T,D,w){w===void 0&&(w=!0);var N=b,I=T,V=1/Math.tan(.5*l),W=w?V/h:V,j=w?V:V*h,ne=(I+N)/(I-N),te=-2*I*N/(I-N);g.FromValuesToRef(W,0,0,0,0,j,0,0,0,0,ne,1,0,0,te,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovReverseLHToRef=function(l,h,b,T,D,w){w===void 0&&(w=!0);var N=1/Math.tan(.5*l),I=w?N/h:N,V=w?N:N*h;g.FromValuesToRef(I,0,0,0,0,V,0,0,0,0,-b,1,0,0,1,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovRH=function(l,h,b,T){var D=new g;return g.PerspectiveFovRHToRef(l,h,b,T,D),D},g.PerspectiveFovRHToRef=function(l,h,b,T,D,w){w===void 0&&(w=!0);var N=b,I=T,V=1/Math.tan(.5*l),W=w?V/h:V,j=w?V:V*h,ne=-(I+N)/(I-N),te=-2*I*N/(I-N);g.FromValuesToRef(W,0,0,0,0,j,0,0,0,0,ne,-1,0,0,te,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovReverseRHToRef=function(l,h,b,T,D,w){w===void 0&&(w=!0);var N=1/Math.tan(.5*l),I=w?N/h:N,V=w?N:N*h;g.FromValuesToRef(I,0,0,0,0,V,0,0,0,0,-b,-1,0,0,-1,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovWebVRToRef=function(l,h,b,T,D){D===void 0&&(D=!1);var w=D?-1:1,N=Math.tan(l.upDegrees*Math.PI/180),I=Math.tan(l.downDegrees*Math.PI/180),V=Math.tan(l.leftDegrees*Math.PI/180),W=Math.tan(l.rightDegrees*Math.PI/180),j=2/(V+W),ne=2/(N+I),te=T._m;te[0]=j,te[1]=te[2]=te[3]=te[4]=0,te[5]=ne,te[6]=te[7]=0,te[8]=(V-W)*j*.5,te[9]=-(N-I)*ne*.5,te[10]=-b/(h-b),te[11]=1*w,te[12]=te[13]=te[15]=0,te[14]=-2*b*h/(b-h),T._markAsUpdated()},g.GetFinalMatrix=function(l,h,b,T,D,w){var N=l.width,I=l.height,V=l.x,W=l.y,j=g.FromValues(N/2,0,0,0,0,-I/2,0,0,0,0,w-D,0,V+N/2,I/2+W,D,1),ne=A.Matrix[0];return h.multiplyToRef(b,ne),ne.multiplyToRef(T,ne),ne.multiply(j)},g.GetAsMatrix2x2=function(l){var h=l.m,b=[h[0],h[1],h[4],h[5]];return M.a.MatrixUse64Bits?b:new Float32Array(b)},g.GetAsMatrix3x3=function(l){var h=l.m,b=[h[0],h[1],h[2],h[4],h[5],h[6],h[8],h[9],h[10]];return M.a.MatrixUse64Bits?b:new Float32Array(b)},g.Transpose=function(l){var h=new g;return g.TransposeToRef(l,h),h},g.TransposeToRef=function(l,h){var b=h._m,T=l.m;b[0]=T[0],b[1]=T[4],b[2]=T[8],b[3]=T[12],b[4]=T[1],b[5]=T[5],b[6]=T[9],b[7]=T[13],b[8]=T[2],b[9]=T[6],b[10]=T[10],b[11]=T[14],b[12]=T[3],b[13]=T[7],b[14]=T[11],b[15]=T[15],h._updateIdentityStatus(l._isIdentity,l._isIdentityDirty)},g.Reflection=function(l){var h=new g;return g.ReflectionToRef(l,h),h},g.ReflectionToRef=function(l,h){l.normalize();var b=l.normal.x,T=l.normal.y,D=l.normal.z,w=-2*b,N=-2*T,I=-2*D;g.FromValuesToRef(w*b+1,N*b,I*b,0,w*T,N*T+1,I*T,0,w*D,N*D,I*D+1,0,w*l.d,N*l.d,I*l.d,1,h)},g.FromXYZAxesToRef=function(l,h,b,T){g.FromValuesToRef(l._x,l._y,l._z,0,h._x,h._y,h._z,0,b._x,b._y,b._z,0,0,0,0,1,T)},g.FromQuaternionToRef=function(l,h){var b=l._x*l._x,T=l._y*l._y,D=l._z*l._z,w=l._x*l._y,N=l._z*l._w,I=l._z*l._x,V=l._y*l._w,W=l._y*l._z,j=l._x*l._w;h._m[0]=1-2*(T+D),h._m[1]=2*(w+N),h._m[2]=2*(I-V),h._m[3]=0,h._m[4]=2*(w-N),h._m[5]=1-2*(D+b),h._m[6]=2*(W+j),h._m[7]=0,h._m[8]=2*(I+V),h._m[9]=2*(W-j),h._m[10]=1-2*(T+b),h._m[11]=0,h._m[12]=0,h._m[13]=0,h._m[14]=0,h._m[15]=1,h._markAsUpdated()},g._updateFlagSeed=0,g._identityReadOnly=g.Identity(),g}(),A=function(){function g(){}return g.Vector3=x.a.BuildArray(6,C.Zero),g.Matrix=x.a.BuildArray(2,E.Identity),g.Quaternion=x.a.BuildArray(3,c.Zero),g}(),S=function(){function g(){}return g.Vector2=x.a.BuildArray(3,R.Zero),g.Vector3=x.a.BuildArray(13,C.Zero),g.Vector4=x.a.BuildArray(3,m.Zero),g.Quaternion=x.a.BuildArray(2,c.Zero),g.Matrix=x.a.BuildArray(8,E.Identity),g}();u.a.RegisteredTypes["BABYLON.Vector2"]=R,u.a.RegisteredTypes["BABYLON.Vector3"]=C,u.a.RegisteredTypes["BABYLON.Vector4"]=m,u.a.RegisteredTypes["BABYLON.Matrix"]=E},function(Ae,v,f){f.d(v,"d",function(){return _}),f.d(v,"a",function(){return x}),f.d(v,"c",function(){return u}),f.d(v,"b",function(){return M}),f.d(v,"e",function(){return R}),f.d(v,"f",function(){return C});/*! ***************************************************************************** - 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. - ***************************************************************************** */var B=function(m,c){return(B=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,A){E.__proto__=A}||function(E,A){for(var S in A)Object.prototype.hasOwnProperty.call(A,S)&&(E[S]=A[S])})(m,c)};function _(m,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function E(){this.constructor=m}B(m,c),m.prototype=c===null?Object.create(c):(E.prototype=c.prototype,new E)}var x=function(){return(x=Object.assign||function(m){for(var c,E=1,A=arguments.length;E=0;h--)(S=m[h])&&(l=(g<3?S(l):g>3?S(c,E,l):S(c,E))||l);return g>3&&l&&Object.defineProperty(c,E,l),l}function M(m,c,E,A){return new(E||(E=Promise))(function(S,g){function l(T){try{b(A.next(T))}catch(D){g(D)}}function h(T){try{b(A.throw(T))}catch(D){g(D)}}function b(T){var D;T.done?S(T.value):(D=T.value,D instanceof E?D:new E(function(w){w(D)})).then(l,h)}b((A=A.apply(m,c||[])).next())})}function R(m,c){var E,A,S,g,l={label:0,sent:function(){if(1&S[0])throw S[1];return S[1]},trys:[],ops:[]};return g={next:h(0),throw:h(1),return:h(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function h(b){return function(T){return function(D){if(E)throw new TypeError("Generator is already executing.");for(;l;)try{if(E=1,A&&(S=2&D[0]?A.return:D[0]?A.throw||((S=A.return)&&S.call(A),0):A.next)&&!(S=S.call(A,D[1])).done)return S;switch(A=0,S&&(D=[2&D[0],S.value]),D[0]){case 0:case 1:S=D;break;case 4:return l.label++,{value:D[1],done:!1};case 5:l.label++,A=D[1],D=[0];continue;case 7:D=l.ops.pop(),l.trys.pop();continue;default:if(S=l.trys,!((S=S.length>0&&S[S.length-1])||D[0]!==6&&D[0]!==2)){l=0;continue}if(D[0]===3&&(!S||D[1]>S[0]&&D[1]=2?"WEBGL2":"WEBGL1"};this._loadShader(N,"Vertex","",function(de){w._rawVertexSourceCode=de,w._loadShader(I,"Fragment","Pixel",function(pe){w._rawFragmentSourceCode=pe,M.a.Process(de,te,function(ae){V&&(ae=V("vertex",ae)),te.isFragment=!0,M.a.Process(pe,te,function(ee){V&&(ee=V("fragment",ee)),w._useFinalCode(ae,ee,m)},w._engine)},w._engine)})})}return Object.defineProperty(C.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new B.c),this._onBindObservable},enumerable:!1,configurable:!0}),C.prototype._useFinalCode=function(m,c,E){if(E){var A=E.vertexElement||E.vertex||E.spectorName||E,S=E.fragmentElement||E.fragment||E.spectorName||E;this._vertexSourceCode="#define SHADER_NAME vertex:"+A+` -`+m,this._fragmentSourceCode="#define SHADER_NAME fragment:"+S+` -`+c}else this._vertexSourceCode=m,this._fragmentSourceCode=c;this._prepareEffect()},Object.defineProperty(C.prototype,"key",{get:function(){return this._key},enumerable:!1,configurable:!0}),C.prototype.isReady=function(){try{return this._isReadyInternal()}catch{return!1}},C.prototype._isReadyInternal=function(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady},C.prototype.getEngine=function(){return this._engine},C.prototype.getPipelineContext=function(){return this._pipelineContext},C.prototype.getAttributesNames=function(){return this._attributesNames},C.prototype.getAttributeLocation=function(m){return this._attributes[m]},C.prototype.getAttributeLocationByName=function(m){return this._attributeLocationByName[m]},C.prototype.getAttributesCount=function(){return this._attributes.length},C.prototype.getUniformIndex=function(m){return this._uniformsNames.indexOf(m)},C.prototype.getUniform=function(m){return this._uniforms[m]},C.prototype.getSamplers=function(){return this._samplerList},C.prototype.getUniformNames=function(){return this._uniformsNames},C.prototype.getUniformBuffersNames=function(){return this._uniformBuffersNamesList},C.prototype.getIndexParameters=function(){return this._indexParameters},C.prototype.getCompilationError=function(){return this._compilationError},C.prototype.allFallbacksProcessed=function(){return this._allFallbacksProcessed},C.prototype.executeWhenCompiled=function(m){var c=this;this.isReady()?m(this):(this.onCompileObservable.add(function(E){m(E)}),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout(function(){c._checkIsReady(null)},16))},C.prototype._checkIsReady=function(m){var c=this;try{if(this._isReadyInternal())return}catch(E){return void this._processCompilationErrors(E,m)}setTimeout(function(){c._checkIsReady(m)},16)},C.prototype._loadShader=function(m,c,E,A){var S;if(typeof HTMLElement<"u"&&m instanceof HTMLElement)return void A(x.a.GetDOMTextContent(m));m.substr(0,7)!=="source:"?m.substr(0,7)!=="base64:"?C.ShadersStore[m+c+"Shader"]?A(C.ShadersStore[m+c+"Shader"]):E&&C.ShadersStore[m+E+"Shader"]?A(C.ShadersStore[m+E+"Shader"]):(S=m[0]==="."||m[0]==="/"||m.indexOf("http")>-1?m:C.ShadersRepository+m,this._engine._loadFile(S+"."+c.toLowerCase()+".fx",A)):A(window.atob(m.substr(7))):A(m.substr(7))},Object.defineProperty(C.prototype,"vertexSourceCode",{get:function(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._vertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"fragmentSourceCode",{get:function(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._fragmentSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"rawVertexSourceCode",{get:function(){return this._rawVertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"rawFragmentSourceCode",{get:function(){return this._rawFragmentSourceCode},enumerable:!1,configurable:!0}),C.prototype._rebuildProgram=function(m,c,E,A){var S=this;this._isReady=!1,this._vertexSourceCodeOverride=m,this._fragmentSourceCodeOverride=c,this.onError=function(g,l){A&&A(l)},this.onCompiled=function(){var g=S.getEngine().scenes;if(g)for(var l=0;l=l&&(S="Offending line ["+l+"] in "+(E?"fragment":"vertex")+" code: "+h[l-1])}}return[m,S]},C.prototype._processCompilationErrors=function(m,c){var E,A,S,g,l;c===void 0&&(c=null),this._compilationError=m.message;var h=this._attributesNames,b=this._fallbacks;if(u.a.Error("Unable to compile effect:"),u.a.Error("Uniforms: "+this._uniformsNames.map(function(N){return" "+N})),u.a.Error("Attributes: "+h.map(function(N){return" "+N})),u.a.Error(`Defines:\r -`+this.defines),C.LogShaderCodeOnCompilationError){var T=null,D=null,w=null;!((S=this._pipelineContext)===null||S===void 0)&&S._getVertexShaderCode()&&(w=(E=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1))[0],T=E[1],w&&(u.a.Error("Vertex code:"),u.a.Error(w))),!((g=this._pipelineContext)===null||g===void 0)&&g._getFragmentShaderCode()&&(w=(A=this._getShaderCodeAndErrorLine((l=this._pipelineContext)===null||l===void 0?void 0:l._getFragmentShaderCode(),this._compilationError,!0))[0],D=A[1],w&&(u.a.Error("Fragment code:"),u.a.Error(w))),T&&u.a.Error(T),D&&u.a.Error(D)}u.a.Error("Error: "+this._compilationError),c&&(this._pipelineContext=c,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)),b?(this._pipelineContext=null,b.hasMoreFallbacks?(this._allFallbacksProcessed=!1,u.a.Error("Trying next fallback."),this.defines=b.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):this._allFallbacksProcessed=!0},Object.defineProperty(C.prototype,"isSupported",{get:function(){return this._compilationError===""},enumerable:!1,configurable:!0}),C.prototype._bindTexture=function(m,c){this._engine._bindTexture(this._samplers[m],c)},C.prototype.setTexture=function(m,c){this._engine.setTexture(this._samplers[m],this._uniforms[m],c)},C.prototype.setDepthStencilTexture=function(m,c){this._engine.setDepthStencilTexture(this._samplers[m],this._uniforms[m],c)},C.prototype.setTextureArray=function(m,c){var E=m+"Ex";if(this._samplerList.indexOf(E+"0")===-1){for(var A=this._samplerList.indexOf(m),S=1;S0},M.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},M.prototype.clone=function(){var R=new M;return R._observers=this._observers.slice(0),R},M.prototype.hasSpecificMask=function(R){R===void 0&&(R=-1);for(var C=0,m=this._observers;C0},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"hasThinInstances",{get:function(){var G;return((G=this._thinInstanceDataStorage.instancesCount)!==null&&G!==void 0?G:0)>0},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"morphTargetManager",{get:function(){return this._internalMeshDataInfo._morphTargetManager},set:function(G){this._internalMeshDataInfo._morphTargetManager!==G&&(this._internalMeshDataInfo._morphTargetManager=G,this._syncGeometryWithMorphTargetManager())},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"source",{get:function(){return this._internalMeshDataInfo._source},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"cloneMeshMap",{get:function(){return this._internalMeshDataInfo.meshMap},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"isUnIndexed",{get:function(){return this._unIndexed},set:function(G){this._unIndexed!==G&&(this._unIndexed=G,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"worldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.instancesData},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"manualUpdateOfWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.manualUpdate},set:function(G){this._instanceDataStorage.manualUpdate=G},enumerable:!1,configurable:!0}),L.prototype.instantiateHierarchy=function(G,Q,oe){G===void 0&&(G=null);var re=!(this.getTotalVertices()>0)||Q&&Q.doNotInstantiate?this.clone("Clone of "+(this.name||this.id),G||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));re&&(re.parent=G||this.parent,re.position=this.position.clone(),re.scaling=this.scaling.clone(),this.rotationQuaternion?re.rotationQuaternion=this.rotationQuaternion.clone():re.rotation=this.rotation.clone(),oe&&oe(this,re));for(var Y=0,k=this.getChildTransformNodes(!0);Y0},enumerable:!1,configurable:!0}),L.prototype.getLODLevels=function(){return this._internalMeshDataInfo._LODLevels},L.prototype._sortLODLevels=function(){this._internalMeshDataInfo._LODLevels.sort(function(G,Q){return G.distanceQ.distance?-1:0})},L.prototype.addLODLevel=function(G,Q){if(Q&&Q._masterMesh)return N.a.Warn("You cannot use a mesh as LOD level twice"),this;var oe=new j.a(G,Q);return this._internalMeshDataInfo._LODLevels.push(oe),Q&&(Q._masterMesh=this),this._sortLODLevels(),this},L.prototype.getLODLevelAtDistance=function(G){for(var Q=this._internalMeshDataInfo,oe=0;oeY)return this.onLODLevelSelection&&this.onLODLevelSelection(Y,this,this),this;for(var k=0;k0||this.hasThinInstances);this.computeWorldMatrix();var ge=this.material||q.defaultMaterial;if(ge){if(ge._storeEffectOnSubMeshes)for(var me=0,_e=this.subMeshes;me<_e.length;me++){var be=(He=_e[me]).getMaterial();if(be){if(be._storeEffectOnSubMeshes){if(!be.isReadyForSubMesh(this,He,he))return!1}else if(!be.isReady(this,he))return!1}}else if(!ge.isReady(this,he))return!1}for(var Ce=0,ye=this.lightSources;Ce0){var oe=this.getIndices();if(!oe)return null;var re=oe.length,Y=!1;if(G)Y=!0;else for(var k=0,H=this.subMeshes;kre){Y=!0;break}if(Z.verticesStart+Z.verticesCount>Q){Y=!0;break}}if(!Y)return this.subMeshes[0]}return this.releaseSubMeshes(),new g.a(0,0,Q,0,this.getTotalIndices(),this)},L.prototype.subdivide=function(G){if(!(G<1)){for(var Q=this.getTotalIndices(),oe=Q/G|0,re=0;oe%3!=0;)oe++;this.releaseSubMeshes();for(var Y=0;Y=Q);Y++)g.a.CreateFromIndices(0,re,Y===G-1?Q-re:oe,this),re+=oe;this.synchronizeInstances()}},L.prototype.setVerticesData=function(G,Q,oe,re){if(oe===void 0&&(oe=!1),this._geometry)this._geometry.setVerticesData(G,Q,oe,re);else{var Y=new E.a;Y.set(Q,G);var k=this.getScene();new A.a(A.a.RandomId(),k,Y,oe,this)}return this},L.prototype.removeVerticesData=function(G){this._geometry&&this._geometry.removeVerticesData(G)},L.prototype.markVerticesDataAsUpdatable=function(G,Q){Q===void 0&&(Q=!0);var oe=this.getVertexBuffer(G);oe&&oe.isUpdatable()!==Q&&this.setVerticesData(G,this.getVerticesData(G),Q)},L.prototype.setVerticesBuffer=function(G){return this._geometry||(this._geometry=A.a.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(G),this},L.prototype.updateVerticesData=function(G,Q,oe,re){return this._geometry?(re?(this.makeGeometryUnique(),this.updateVerticesData(G,Q,oe,!1)):this._geometry.updateVerticesData(G,Q,oe),this):this},L.prototype.updateMeshPositions=function(G,Q){Q===void 0&&(Q=!0);var oe=this.getVerticesData(c.b.PositionKind);if(!oe)return this;if(G(oe),this.updateVerticesData(c.b.PositionKind,oe,!1,!1),Q){var re=this.getIndices(),Y=this.getVerticesData(c.b.NormalKind);if(!Y)return this;E.a.ComputeNormals(oe,re,Y),this.updateVerticesData(c.b.NormalKind,Y,!1,!1)}return this},L.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;var G=this._geometry,Q=this._geometry.copy(A.a.RandomId());return G.releaseForMesh(this,!0),Q.applyToMesh(this),this},L.prototype.setIndices=function(G,Q,oe){if(Q===void 0&&(Q=null),oe===void 0&&(oe=!1),this._geometry)this._geometry.setIndices(G,Q,oe);else{var re=new E.a;re.indices=G;var Y=this.getScene();new A.a(A.a.RandomId(),Y,re,oe,this)}return this},L.prototype.updateIndices=function(G,Q,oe){return oe===void 0&&(oe=!1),this._geometry?(this._geometry.updateIndices(G,Q,oe),this):this},L.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},L.prototype._bind=function(G,Q,oe){if(!this._geometry)return this;var re,Y=this.getScene().getEngine();if(this._unIndexed)re=null;else switch(oe){case h.a.PointFillMode:re=null;break;case h.a.WireFrameFillMode:re=G._getLinesIndexBuffer(this.getIndices(),Y);break;default:case h.a.TriangleFillMode:re=this._geometry.getIndexBuffer()}return this._geometry._bind(Q,re),this},L.prototype._draw=function(G,Q,oe){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);var re=this.getScene().getEngine();return this._unIndexed||Q==h.a.PointFillMode?re.drawArraysType(Q,G.verticesStart,G.verticesCount,oe):Q==h.a.WireFrameFillMode?re.drawElementsType(Q,0,G._linesIndexCount,oe):re.drawElementsType(Q,G.indexStart,G.indexCount,oe),this},L.prototype.registerBeforeRender=function(G){return this.onBeforeRenderObservable.add(G),this},L.prototype.unregisterBeforeRender=function(G){return this.onBeforeRenderObservable.removeCallback(G),this},L.prototype.registerAfterRender=function(G){return this.onAfterRenderObservable.add(G),this},L.prototype.unregisterAfterRender=function(G){return this.onAfterRenderObservable.removeCallback(G),this},L.prototype._getInstancesRenderList=function(G,Q){if(Q===void 0&&(Q=!1),this._instanceDataStorage.isFrozen&&this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch;var oe=this.getScene(),re=oe._isInIntermediateRendering(),Y=re?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,k=this._instanceDataStorage.batchCache;if(k.mustReturn=!1,k.renderSelf[G]=Q||!Y&&this.isEnabled()&&this.isVisible,k.visibleInstances[G]=null,this._instanceDataStorage.visibleInstances&&!Q){var H=this._instanceDataStorage.visibleInstances,Z=oe.getRenderId(),X=re?H.intermediateDefaultRenderId:H.defaultRenderId;k.visibleInstances[G]=H[Z],!k.visibleInstances[G]&&X&&(k.visibleInstances[G]=H[X])}return k.hardwareInstancedRendering[G]=!Q&&this._instanceDataStorage.hardwareInstancedRendering&&k.visibleInstances[G]!==null&&k.visibleInstances[G]!==void 0,this._instanceDataStorage.previousBatch=k,k},L.prototype._renderWithInstances=function(G,Q,oe,re,Y){var k=oe.visibleInstances[G._id];if(!k)return this;for(var H=this._instanceDataStorage,Z=H.instancesBufferSize,X=H.instancesBuffer,q=16*(k.length+1)*4;H.instancesBufferSizehe&&re++,be!==0&&me++,ge+=be,he=be}if(X[me]++,me>k&&(k=me),ge===0)Y++;else{var Ce=1/ge,ye=0;for(_e=0;_e.001&&H++}}var Be=this.skeleton.bones.length,Ge=this.getVerticesData(c.b.MatricesIndicesKind),Xe=this.getVerticesData(c.b.MatricesIndicesExtraKind),He=0;for(q=0;q=Be||We<0)&&He++}return{skinned:!0,valid:Y===0&&H===0&&He===0,report:"Number of Weights = "+oe/4+` -Maximum influences = `+k+` -Missing Weights = `+Y+` -Not Sorted = `+re+` -Not Normalized = `+H+` -WeightCounts = [`+X+`] -Number of bones = `+Be+` -Bad Bone Indices = `+He}},L.prototype._checkDelayState=function(){var G=this.getScene();return this._geometry?this._geometry.load(G):this.delayLoadState===D.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=D.a.DELAYLOADSTATE_LOADING,this._queueLoad(G)),this},L.prototype._queueLoad=function(G){var Q=this;G._addPendingData(this);var oe=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return x.b.LoadFile(this.delayLoadingFile,function(re){re instanceof ArrayBuffer?Q._delayLoadingFunction(re,Q):Q._delayLoadingFunction(JSON.parse(re),Q),Q.instances.forEach(function(Y){Y.refreshBoundingInfo(),Y._syncSubMeshes()}),Q.delayLoadState=D.a.DELAYLOADSTATE_LOADED,G._removePendingData(Q)},function(){},G.offlineProvider,oe),this},L.prototype.isInFrustum=function(G){return this.delayLoadState!==D.a.DELAYLOADSTATE_LOADING&&!!$.prototype.isInFrustum.call(this,G)&&(this._checkDelayState(),!0)},L.prototype.setMaterialByID=function(G){var Q,oe=this.getScene().materials;for(Q=oe.length-1;Q>-1;Q--)if(oe[Q].id===G)return this.material=oe[Q],this;var re=this.getScene().multiMaterials;for(Q=re.length-1;Q>-1;Q--)if(re[Q].id===G)return this.material=re[Q],this;return this},L.prototype.getAnimatables=function(){var G=new Array;return this.material&&G.push(this.material),this.skeleton&&G.push(this.skeleton),G},L.prototype.bakeTransformIntoVertices=function(G){if(!this.isVerticesDataPresent(c.b.PositionKind))return this;var Q=this.subMeshes.splice(0);this._resetPointsArrayCache();var oe,re=this.getVerticesData(c.b.PositionKind),Y=new Array;for(oe=0;oe1)for(var oe=0,re=Q.meshes.slice(0);oe-1&&(re.morphTargetManager=Q.getMorphTargetManagerById(G.morphTargetManagerId)),G.skeletonId!==void 0&&G.skeletonId!==null&&(re.skeleton=Q.getLastSkeletonByID(G.skeletonId),G.numBoneInfluencers&&(re.numBoneInfluencers=G.numBoneInfluencers)),G.animations){for(var Y=0;Y4,he=q?this.getVerticesData(c.b.MatricesIndicesExtraKind):null,ge=q?this.getVerticesData(c.b.MatricesWeightsExtraKind):null,me=G.getTransformMatrices(this),_e=R.e.Zero(),be=new R.a,Ce=new R.a,ye=0,Be=0;Be0&&(R.a.FromFloat32ArrayToRefScaled(me,Math.floor(16*H[ye+X]),Ge,Ce),be.addToSelf(Ce));if(q)for(X=0;X<4;X++)(Ge=ge[ye+X])>0&&(R.a.FromFloat32ArrayToRefScaled(me,Math.floor(16*he[ye+X]),Ge,Ce),be.addToSelf(Ce));R.e.TransformCoordinatesFromFloatsToRef(oe._sourcePositions[Be],oe._sourcePositions[Be+1],oe._sourcePositions[Be+2],be,_e),_e.toArray(Y,Be),Q&&(R.e.TransformNormalFromFloatsToRef(oe._sourceNormals[Be],oe._sourceNormals[Be+1],oe._sourceNormals[Be+2],be,_e),_e.toArray(k,Be)),be.reset()}return this.updateVerticesData(c.b.PositionKind,Y),Q&&this.updateVerticesData(c.b.NormalKind,k),this},L.MinMax=function(G){var Q=null,oe=null;return G.forEach(function(re){var Y=re.getBoundingInfo().boundingBox;Q&&oe?(Q.minimizeInPlace(Y.minimumWorld),oe.maximizeInPlace(Y.maximumWorld)):(Q=Y.minimumWorld,oe=Y.maximumWorld)}),Q&&oe?{min:Q,max:oe}:{min:R.e.Zero(),max:R.e.Zero()}},L.Center=function(G){var Q=G instanceof Array?L.MinMax(G):G;return R.e.Center(Q.min,Q.max)},L.MergeMeshes=function(G,Q,oe,re,Y,k){var H;if(Q===void 0&&(Q=!0),!oe){var Z=0;for(H=0;H=65536)return N.a.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}if(k){var X,q,he=null;Y=!1}var ge,me=new Array,_e=new Array,be=null,Ce=new Array,ye=null;for(H=0;H
    ";_._AddLogEntry(M)},_._WarnDisabled=function(x){},_._WarnEnabled=function(x){var u=_._FormatMessage(x);console.warn("BJS - "+u);var M="
    "+u+"

    ";_._AddLogEntry(M)},_._ErrorDisabled=function(x){},_._ErrorEnabled=function(x){_.errorsCount++;var u=_._FormatMessage(x);console.error("BJS - "+u);var M="
    "+u+"

    ";_._AddLogEntry(M)},Object.defineProperty(_,"LogCache",{get:function(){return _._LogCache},enumerable:!1,configurable:!0}),_.ClearLogCache=function(){_._LogCache="",_.errorsCount=0},Object.defineProperty(_,"LogLevels",{set:function(x){(x&_.MessageLogLevel)===_.MessageLogLevel?_.Log=_._LogEnabled:_.Log=_._LogDisabled,(x&_.WarningLogLevel)===_.WarningLogLevel?_.Warn=_._WarnEnabled:_.Warn=_._WarnDisabled,(x&_.ErrorLogLevel)===_.ErrorLogLevel?_.Error=_._ErrorEnabled:_.Error=_._ErrorDisabled},enumerable:!1,configurable:!0}),_.NoneLogLevel=0,_.MessageLogLevel=1,_.WarningLogLevel=2,_.ErrorLogLevel=4,_.AllLogLevel=7,_._LogCache="",_.errorsCount=0,_.Log=_._LogEnabled,_.Warn=_._WarnEnabled,_.Error=_._ErrorEnabled,_}()},function(Ae,v,f){f.d(v,"a",function(){return M}),f.d(v,"b",function(){return R}),f.d(v,"c",function(){return C});var B=f(14),_=f(28),x=f(44),u=f(11),M=function(){function m(c,E,A){c===void 0&&(c=0),E===void 0&&(E=0),A===void 0&&(A=0),this.r=c,this.g=E,this.b=A}return m.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},m.prototype.getClassName=function(){return"Color3"},m.prototype.getHashCode=function(){var c=255*this.r|0;return c=397*(c=397*c^(255*this.g|0))^(255*this.b|0)},m.prototype.toArray=function(c,E){return E===void 0&&(E=0),c[E]=this.r,c[E+1]=this.g,c[E+2]=this.b,this},m.prototype.fromArray=function(c,E){return E===void 0&&(E=0),m.FromArrayToRef(c,E,this),this},m.prototype.toColor4=function(c){return c===void 0&&(c=1),new R(this.r,this.g,this.b,c)},m.prototype.asArray=function(){var c=new Array;return this.toArray(c,0),c},m.prototype.toLuminance=function(){return .3*this.r+.59*this.g+.11*this.b},m.prototype.multiply=function(c){return new m(this.r*c.r,this.g*c.g,this.b*c.b)},m.prototype.multiplyToRef=function(c,E){return E.r=this.r*c.r,E.g=this.g*c.g,E.b=this.b*c.b,this},m.prototype.equals=function(c){return c&&this.r===c.r&&this.g===c.g&&this.b===c.b},m.prototype.equalsFloats=function(c,E,A){return this.r===c&&this.g===E&&this.b===A},m.prototype.scale=function(c){return new m(this.r*c,this.g*c,this.b*c)},m.prototype.scaleToRef=function(c,E){return E.r=this.r*c,E.g=this.g*c,E.b=this.b*c,this},m.prototype.scaleAndAddToRef=function(c,E){return E.r+=this.r*c,E.g+=this.g*c,E.b+=this.b*c,this},m.prototype.clampToRef=function(c,E,A){return c===void 0&&(c=0),E===void 0&&(E=1),A.r=B.a.Clamp(this.r,c,E),A.g=B.a.Clamp(this.g,c,E),A.b=B.a.Clamp(this.b,c,E),this},m.prototype.add=function(c){return new m(this.r+c.r,this.g+c.g,this.b+c.b)},m.prototype.addToRef=function(c,E){return E.r=this.r+c.r,E.g=this.g+c.g,E.b=this.b+c.b,this},m.prototype.subtract=function(c){return new m(this.r-c.r,this.g-c.g,this.b-c.b)},m.prototype.subtractToRef=function(c,E){return E.r=this.r-c.r,E.g=this.g-c.g,E.b=this.b-c.b,this},m.prototype.clone=function(){return new m(this.r,this.g,this.b)},m.prototype.copyFrom=function(c){return this.r=c.r,this.g=c.g,this.b=c.b,this},m.prototype.copyFromFloats=function(c,E,A){return this.r=c,this.g=E,this.b=A,this},m.prototype.set=function(c,E,A){return this.copyFromFloats(c,E,A)},m.prototype.toHexString=function(){var c=255*this.r|0,E=255*this.g|0,A=255*this.b|0;return"#"+B.a.ToHex(c)+B.a.ToHex(E)+B.a.ToHex(A)},m.prototype.toLinearSpace=function(){var c=new m;return this.toLinearSpaceToRef(c),c},m.prototype.toHSV=function(){var c=new m;return this.toHSVToRef(c),c},m.prototype.toHSVToRef=function(c){var E=this.r,A=this.g,S=this.b,g=Math.max(E,A,S),l=Math.min(E,A,S),h=0,b=0,T=g,D=g-l;g!==0&&(b=D/g),g!=l&&(g==E?(h=(A-S)/D,A=0&&l<=1?(b=g,T=h):l>=1&&l<=2?(b=h,T=g):l>=2&&l<=3?(T=g,D=h):l>=3&&l<=4?(T=h,D=g):l>=4&&l<=5?(b=h,D=g):l>=5&&l<=6&&(b=g,D=h);var w=A-g;S.set(b+w,T+w,D+w)},m.FromHexString=function(c){if(c.substring(0,1)!=="#"||c.length!==7)return new m(0,0,0);var E=parseInt(c.substring(1,3),16),A=parseInt(c.substring(3,5),16),S=parseInt(c.substring(5,7),16);return m.FromInts(E,A,S)},m.FromArray=function(c,E){return E===void 0&&(E=0),new m(c[E],c[E+1],c[E+2])},m.FromArrayToRef=function(c,E,A){E===void 0&&(E=0),A.r=c[E],A.g=c[E+1],A.b=c[E+2]},m.FromInts=function(c,E,A){return new m(c/255,E/255,A/255)},m.Lerp=function(c,E,A){var S=new m(0,0,0);return m.LerpToRef(c,E,A,S),S},m.LerpToRef=function(c,E,A,S){S.r=c.r+(E.r-c.r)*A,S.g=c.g+(E.g-c.g)*A,S.b=c.b+(E.b-c.b)*A},m.Red=function(){return new m(1,0,0)},m.Green=function(){return new m(0,1,0)},m.Blue=function(){return new m(0,0,1)},m.Black=function(){return new m(0,0,0)},Object.defineProperty(m,"BlackReadOnly",{get:function(){return m._BlackReadOnly},enumerable:!1,configurable:!0}),m.White=function(){return new m(1,1,1)},m.Purple=function(){return new m(.5,0,.5)},m.Magenta=function(){return new m(1,0,1)},m.Yellow=function(){return new m(1,1,0)},m.Gray=function(){return new m(.5,.5,.5)},m.Teal=function(){return new m(0,1,1)},m.Random=function(){return new m(Math.random(),Math.random(),Math.random())},m._BlackReadOnly=m.Black(),m}(),R=function(){function m(c,E,A,S){c===void 0&&(c=0),E===void 0&&(E=0),A===void 0&&(A=0),S===void 0&&(S=1),this.r=c,this.g=E,this.b=A,this.a=S}return m.prototype.addInPlace=function(c){return this.r+=c.r,this.g+=c.g,this.b+=c.b,this.a+=c.a,this},m.prototype.asArray=function(){var c=new Array;return this.toArray(c,0),c},m.prototype.toArray=function(c,E){return E===void 0&&(E=0),c[E]=this.r,c[E+1]=this.g,c[E+2]=this.b,c[E+3]=this.a,this},m.prototype.fromArray=function(c,E){return E===void 0&&(E=0),m.FromArrayToRef(c,E,this),this},m.prototype.equals=function(c){return c&&this.r===c.r&&this.g===c.g&&this.b===c.b&&this.a===c.a},m.prototype.add=function(c){return new m(this.r+c.r,this.g+c.g,this.b+c.b,this.a+c.a)},m.prototype.subtract=function(c){return new m(this.r-c.r,this.g-c.g,this.b-c.b,this.a-c.a)},m.prototype.subtractToRef=function(c,E){return E.r=this.r-c.r,E.g=this.g-c.g,E.b=this.b-c.b,E.a=this.a-c.a,this},m.prototype.scale=function(c){return new m(this.r*c,this.g*c,this.b*c,this.a*c)},m.prototype.scaleToRef=function(c,E){return E.r=this.r*c,E.g=this.g*c,E.b=this.b*c,E.a=this.a*c,this},m.prototype.scaleAndAddToRef=function(c,E){return E.r+=this.r*c,E.g+=this.g*c,E.b+=this.b*c,E.a+=this.a*c,this},m.prototype.clampToRef=function(c,E,A){return c===void 0&&(c=0),E===void 0&&(E=1),A.r=B.a.Clamp(this.r,c,E),A.g=B.a.Clamp(this.g,c,E),A.b=B.a.Clamp(this.b,c,E),A.a=B.a.Clamp(this.a,c,E),this},m.prototype.multiply=function(c){return new m(this.r*c.r,this.g*c.g,this.b*c.b,this.a*c.a)},m.prototype.multiplyToRef=function(c,E){return E.r=this.r*c.r,E.g=this.g*c.g,E.b=this.b*c.b,E.a=this.a*c.a,E},m.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},m.prototype.getClassName=function(){return"Color4"},m.prototype.getHashCode=function(){var c=255*this.r|0;return c=397*(c=397*(c=397*c^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)},m.prototype.clone=function(){return new m(this.r,this.g,this.b,this.a)},m.prototype.copyFrom=function(c){return this.r=c.r,this.g=c.g,this.b=c.b,this.a=c.a,this},m.prototype.copyFromFloats=function(c,E,A,S){return this.r=c,this.g=E,this.b=A,this.a=S,this},m.prototype.set=function(c,E,A,S){return this.copyFromFloats(c,E,A,S)},m.prototype.toHexString=function(c){c===void 0&&(c=!1);var E=255*this.r|0,A=255*this.g|0,S=255*this.b|0;if(c)return"#"+B.a.ToHex(E)+B.a.ToHex(A)+B.a.ToHex(S);var g=255*this.a|0;return"#"+B.a.ToHex(E)+B.a.ToHex(A)+B.a.ToHex(S)+B.a.ToHex(g)},m.prototype.toLinearSpace=function(){var c=new m;return this.toLinearSpaceToRef(c),c},m.prototype.toLinearSpaceToRef=function(c){return c.r=Math.pow(this.r,_.c),c.g=Math.pow(this.g,_.c),c.b=Math.pow(this.b,_.c),c.a=this.a,this},m.prototype.toGammaSpace=function(){var c=new m;return this.toGammaSpaceToRef(c),c},m.prototype.toGammaSpaceToRef=function(c){return c.r=Math.pow(this.r,_.b),c.g=Math.pow(this.g,_.b),c.b=Math.pow(this.b,_.b),c.a=this.a,this},m.FromHexString=function(c){if(c.substring(0,1)!=="#"||c.length!==9)return new m(0,0,0,0);var E=parseInt(c.substring(1,3),16),A=parseInt(c.substring(3,5),16),S=parseInt(c.substring(5,7),16),g=parseInt(c.substring(7,9),16);return m.FromInts(E,A,S,g)},m.Lerp=function(c,E,A){var S=new m(0,0,0,0);return m.LerpToRef(c,E,A,S),S},m.LerpToRef=function(c,E,A,S){S.r=c.r+(E.r-c.r)*A,S.g=c.g+(E.g-c.g)*A,S.b=c.b+(E.b-c.b)*A,S.a=c.a+(E.a-c.a)*A},m.FromColor3=function(c,E){return E===void 0&&(E=1),new m(c.r,c.g,c.b,E)},m.FromArray=function(c,E){return E===void 0&&(E=0),new m(c[E],c[E+1],c[E+2],c[E+3])},m.FromArrayToRef=function(c,E,A){E===void 0&&(E=0),A.r=c[E],A.g=c[E+1],A.b=c[E+2],A.a=c[E+3]},m.FromInts=function(c,E,A,S){return new m(c/255,E/255,A/255,S/255)},m.CheckColors4=function(c,E){if(c.length===3*E){for(var A=[],S=0;S0?T.name:w+T.name,(S.a.StartsWith(T.url,"data:")||b.UseSerializedUrlIfAny&&T.url)&&(ae=T.url),W=new b(ae,D,!j,T.invertY,void 0,I)}return W},T,D);return V},b.CreateFromBase64String=function(T,D,w,N,I,V,W,j,ne){return V===void 0&&(V=b.TRILINEAR_SAMPLINGMODE),W===void 0&&(W=null),j===void 0&&(j=null),ne===void 0&&(ne=R.a.TEXTUREFORMAT_RGBA),new b("data:"+D,w,N,I,V,W,j,T,!1,ne)},b.LoadFromDataString=function(T,D,w,N,I,V,W,j,ne,te){return N===void 0&&(N=!1),I===void 0&&(I=!1),V===void 0&&(V=!0),W===void 0&&(W=b.TRILINEAR_SAMPLINGMODE),j===void 0&&(j=null),ne===void 0&&(ne=null),te===void 0&&(te=R.a.TEXTUREFORMAT_RGBA),T.substr(0,5)!=="data:"&&(T="data:"+T),new b(T,w,I,V,W,j,ne,D,N,te)},b.SerializeBuffers=!0,b.ForceSerializeBuffers=!1,b._CubeTextureParser=function(T,D,w){throw m.a.WarnImport("CubeTexture")},b._CreateMirror=function(T,D,w,N){throw m.a.WarnImport("MirrorTexture")},b._CreateRenderTargetTexture=function(T,D,w,N){throw m.a.WarnImport("RenderTargetTexture")},b.NEAREST_SAMPLINGMODE=R.a.TEXTURE_NEAREST_SAMPLINGMODE,b.NEAREST_NEAREST_MIPLINEAR=R.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,b.BILINEAR_SAMPLINGMODE=R.a.TEXTURE_BILINEAR_SAMPLINGMODE,b.LINEAR_LINEAR_MIPNEAREST=R.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,b.TRILINEAR_SAMPLINGMODE=R.a.TEXTURE_TRILINEAR_SAMPLINGMODE,b.LINEAR_LINEAR_MIPLINEAR=R.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,b.NEAREST_NEAREST_MIPNEAREST=R.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,b.NEAREST_LINEAR_MIPNEAREST=R.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,b.NEAREST_LINEAR_MIPLINEAR=R.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,b.NEAREST_LINEAR=R.a.TEXTURE_NEAREST_LINEAR,b.NEAREST_NEAREST=R.a.TEXTURE_NEAREST_NEAREST,b.LINEAR_NEAREST_MIPNEAREST=R.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,b.LINEAR_NEAREST_MIPLINEAR=R.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,b.LINEAR_LINEAR=R.a.TEXTURE_LINEAR_LINEAR,b.LINEAR_NEAREST=R.a.TEXTURE_LINEAR_NEAREST,b.EXPLICIT_MODE=R.a.TEXTURE_EXPLICIT_MODE,b.SPHERICAL_MODE=R.a.TEXTURE_SPHERICAL_MODE,b.PLANAR_MODE=R.a.TEXTURE_PLANAR_MODE,b.CUBIC_MODE=R.a.TEXTURE_CUBIC_MODE,b.PROJECTION_MODE=R.a.TEXTURE_PROJECTION_MODE,b.SKYBOX_MODE=R.a.TEXTURE_SKYBOX_MODE,b.INVCUBIC_MODE=R.a.TEXTURE_INVCUBIC_MODE,b.EQUIRECTANGULAR_MODE=R.a.TEXTURE_EQUIRECTANGULAR_MODE,b.FIXED_EQUIRECTANGULAR_MODE=R.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,b.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=R.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,b.CLAMP_ADDRESSMODE=R.a.TEXTURE_CLAMP_ADDRESSMODE,b.WRAP_ADDRESSMODE=R.a.TEXTURE_WRAP_ADDRESSMODE,b.MIRROR_ADDRESSMODE=R.a.TEXTURE_MIRROR_ADDRESSMODE,b.UseSerializedUrlIfAny=!1,Object(B.c)([Object(_.c)()],b.prototype,"url",void 0),Object(B.c)([Object(_.c)()],b.prototype,"uOffset",void 0),Object(B.c)([Object(_.c)()],b.prototype,"vOffset",void 0),Object(B.c)([Object(_.c)()],b.prototype,"uScale",void 0),Object(B.c)([Object(_.c)()],b.prototype,"vScale",void 0),Object(B.c)([Object(_.c)()],b.prototype,"uAng",void 0),Object(B.c)([Object(_.c)()],b.prototype,"vAng",void 0),Object(B.c)([Object(_.c)()],b.prototype,"wAng",void 0),Object(B.c)([Object(_.c)()],b.prototype,"uRotationCenter",void 0),Object(B.c)([Object(_.c)()],b.prototype,"vRotationCenter",void 0),Object(B.c)([Object(_.c)()],b.prototype,"wRotationCenter",void 0),Object(B.c)([Object(_.c)()],b.prototype,"homogeneousRotationInUVTransform",void 0),Object(B.c)([Object(_.c)()],b.prototype,"isBlocking",null),b}(M.a);C.a.RegisteredTypes["BABYLON.Texture"]=l,_.a._TextureParser=l.Parse},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){}return _.GetClass=function(x){return this.RegisteredTypes&&this.RegisteredTypes[x]?this.RegisteredTypes[x]:null},_.RegisteredTypes={},_}()},function(Ae,v,f){f.d(v,"b",function(){return l}),f.d(v,"c",function(){return h}),f.d(v,"a",function(){return b});var B=f(6),_=f(38),x=f(8),u=f(41),M=f(57),R=f(21),C=f(49),m=f(22),c=f(56),E=f(145),A=f(104),S=f(122),g=f(120),l=function(){function T(){}return Object.defineProperty(T,"BaseUrl",{get:function(){return c.a.BaseUrl},set:function(D){c.a.BaseUrl=D},enumerable:!1,configurable:!0}),Object.defineProperty(T,"DefaultRetryStrategy",{get:function(){return c.a.DefaultRetryStrategy},set:function(D){c.a.DefaultRetryStrategy=D},enumerable:!1,configurable:!0}),Object.defineProperty(T,"CorsBehavior",{get:function(){return c.a.CorsBehavior},set:function(D){c.a.CorsBehavior=D},enumerable:!1,configurable:!0}),Object.defineProperty(T,"UseFallbackTexture",{get:function(){return m.a.UseFallbackTexture},set:function(D){m.a.UseFallbackTexture=D},enumerable:!1,configurable:!0}),Object.defineProperty(T,"RegisteredExternalClasses",{get:function(){return S.a.RegisteredExternalClasses},set:function(D){S.a.RegisteredExternalClasses=D},enumerable:!1,configurable:!0}),Object.defineProperty(T,"fallbackTexture",{get:function(){return m.a.FallbackTexture},set:function(D){m.a.FallbackTexture=D},enumerable:!1,configurable:!0}),T.FetchToRef=function(D,w,N,I,V,W){var j=4*((Math.abs(D)*N%N|0)+(Math.abs(w)*I%I|0)*N);W.r=V[j]/255,W.g=V[j+1]/255,W.b=V[j+2]/255,W.a=V[j+3]/255},T.Mix=function(D,w,N){return D*(1-N)+w*N},T.Instantiate=function(D){return S.a.Instantiate(D)},T.Slice=function(D,w,N){return D.slice?D.slice(w,N):Array.prototype.slice.call(D,w,N)},T.SliceToArray=function(D,w,N){return Array.isArray(D)?D.slice(w,N):Array.prototype.slice.call(D,w,N)},T.SetImmediate=function(D){A.a.SetImmediate(D)},T.IsExponentOfTwo=function(D){var w=1;do w*=2;while(w=D)break;if(N(te),V&&V()){j.breakLoop();break}}j.executeNext()},W)},I)},T}();m.a.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",E.a.Apply()},function(Ae,v,f){f.d(v,"a",function(){return S});var B=f(1),_=f(6),x=f(38),u=f(22),M=f(21),R=f(26),C=f(2),m=f(146),c=f(55),E=f(88),A=f(8),S=(f(123),f(129),f(124),function(g){function l(h,b,T,D){D===void 0&&(D=!1);var w=g.call(this,h,b,T,D)||this;if(w.enableOfflineSupport=!1,w.disableManifestCheck=!1,w.scenes=new Array,w.onNewSceneAddedObservable=new _.c,w.postProcesses=new Array,w.isPointerLock=!1,w.onResizeObservable=new _.c,w.onCanvasBlurObservable=new _.c,w.onCanvasFocusObservable=new _.c,w.onCanvasPointerOutObservable=new _.c,w.onBeginFrameObservable=new _.c,w.customAnimationFrameRequester=null,w.onEndFrameObservable=new _.c,w.onBeforeShaderCompilationObservable=new _.c,w.onAfterShaderCompilationObservable=new _.c,w._deterministicLockstep=!1,w._lockstepMaxSteps=4,w._timeStep=1/60,w._fps=60,w._deltaTime=0,w._drawCalls=new c.a,w.canvasTabIndex=1,w.disablePerformanceMonitorInBackground=!1,w._performanceMonitor=new m.a,l.Instances.push(w),!h)return w;if(T=w._creationOptions,h.getContext){var N=h;if(w._onCanvasFocus=function(){w.onCanvasFocusObservable.notifyObservers(w)},w._onCanvasBlur=function(){w.onCanvasBlurObservable.notifyObservers(w)},N.addEventListener("focus",w._onCanvasFocus),N.addEventListener("blur",w._onCanvasBlur),w._onBlur=function(){w.disablePerformanceMonitorInBackground&&w._performanceMonitor.disable(),w._windowIsBackground=!0},w._onFocus=function(){w.disablePerformanceMonitorInBackground&&w._performanceMonitor.enable(),w._windowIsBackground=!1},w._onCanvasPointerOut=function(W){w.onCanvasPointerOutObservable.notifyObservers(W)},N.addEventListener("pointerout",w._onCanvasPointerOut),x.a.IsWindowObjectExist()){var I=w.getHostWindow();I.addEventListener("blur",w._onBlur),I.addEventListener("focus",w._onFocus);var V=document;w._onFullscreenChange=function(){V.fullscreen!==void 0?w.isFullscreen=V.fullscreen:V.mozFullScreen!==void 0?w.isFullscreen=V.mozFullScreen:V.webkitIsFullScreen!==void 0?w.isFullscreen=V.webkitIsFullScreen:V.msIsFullScreen!==void 0&&(w.isFullscreen=V.msIsFullScreen),w.isFullscreen&&w._pointerLockRequested&&N&&l._RequestPointerlock(N)},document.addEventListener("fullscreenchange",w._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",w._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",w._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",w._onFullscreenChange,!1),w._onPointerLockChange=function(){w.isPointerLock=V.mozPointerLockElement===N||V.webkitPointerLockElement===N||V.msPointerLockElement===N||V.pointerLockElement===N},document.addEventListener("pointerlockchange",w._onPointerLockChange,!1),document.addEventListener("mspointerlockchange",w._onPointerLockChange,!1),document.addEventListener("mozpointerlockchange",w._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",w._onPointerLockChange,!1),!l.audioEngine&&T.audioEngine&&l.AudioEngineFactory&&(l.audioEngine=l.AudioEngineFactory(w.getRenderingCanvas()))}w._connectVREvents(),w.enableOfflineSupport=l.OfflineProviderFactory!==void 0,T.doNotHandleTouchAction||w._disableTouchAction(),w._deterministicLockstep=!!T.deterministicLockstep,w._lockstepMaxSteps=T.lockstepMaxSteps||0,w._timeStep=T.timeStep||1/60}return w._prepareVRComponent(),T.autoEnableWebVR&&w.initWebVR(),w}return Object(B.d)(l,g),Object.defineProperty(l,"NpmPackage",{get:function(){return R.a.NpmPackage},enumerable:!1,configurable:!0}),Object.defineProperty(l,"Version",{get:function(){return R.a.Version},enumerable:!1,configurable:!0}),Object.defineProperty(l,"Instances",{get:function(){return u.a.Instances},enumerable:!1,configurable:!0}),Object.defineProperty(l,"LastCreatedEngine",{get:function(){return u.a.LastCreatedEngine},enumerable:!1,configurable:!0}),Object.defineProperty(l,"LastCreatedScene",{get:function(){return u.a.LastCreatedScene},enumerable:!1,configurable:!0}),l.MarkAllMaterialsAsDirty=function(h,b){for(var T=0;T0?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},l.prototype._renderViews=function(){return!1},l.prototype.switchFullscreen=function(h){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(h)},l.prototype.enterFullscreen=function(h){this.isFullscreen||(this._pointerLockRequested=h,this._renderingCanvas&&l._RequestFullscreen(this._renderingCanvas))},l.prototype.exitFullscreen=function(){this.isFullscreen&&l._ExitFullscreen()},l.prototype.enterPointerlock=function(){this._renderingCanvas&&l._RequestPointerlock(this._renderingCanvas)},l.prototype.exitPointerlock=function(){l._ExitPointerlock()},l.prototype.beginFrame=function(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),g.prototype.beginFrame.call(this)},l.prototype.endFrame=function(){g.prototype.endFrame.call(this),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)},l.prototype.resize=function(){this.isVRPresenting()||g.prototype.resize.call(this)},l.prototype.setSize=function(h,b){if(!this._renderingCanvas||!g.prototype.setSize.call(this,h,b))return!1;if(this.scenes){for(var T=0;T1&&w){var I=this.createTransformFeedback();this.bindTransformFeedback(I),this.setTranformFeedbackVaryings(N,w),h.transformFeedback=I}return D.linkProgram(N),this.webGLVersion>1&&w&&this.bindTransformFeedback(null),h.context=D,h.vertexShader=b,h.fragmentShader=T,h.isParallelCompiled||this._finalizePipelineContext(h),N},l.prototype._releaseTexture=function(h){g.prototype._releaseTexture.call(this,h),this.scenes.forEach(function(b){b.postProcesses.forEach(function(T){T._outputTexture==h&&(T._outputTexture=null)}),b.cameras.forEach(function(T){T._postProcesses.forEach(function(D){D&&D._outputTexture==h&&(D._outputTexture=null)})})})},l.prototype._rescaleTexture=function(h,b,T,D,w){var N=this;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);var I=this.createRenderTargetTexture({width:b.width,height:b.height},{generateMipMaps:!1,type:C.a.TEXTURETYPE_UNSIGNED_INT,samplingMode:C.a.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&l._RescalePostProcessFactory&&(this._rescalePostProcess=l._RescalePostProcessFactory(this)),this._rescalePostProcess.getEffect().executeWhenCompiled(function(){N._rescalePostProcess.onApply=function(W){W._bindTexture("textureSampler",h)};var V=T;V||(V=N.scenes[N.scenes.length-1]),V.postProcessManager.directRender([N._rescalePostProcess],I,!0),N._bindTextureDirectly(N._gl.TEXTURE_2D,b,!0),N._gl.copyTexImage2D(N._gl.TEXTURE_2D,0,D,0,0,b.width,b.height,0),N.unBindFramebuffer(I),N._releaseTexture(I),w&&w()})},l.prototype.getFps=function(){return this._fps},l.prototype.getDeltaTime=function(){return this._deltaTime},l.prototype._measureFps=function(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0},l.prototype._uploadImageToTexture=function(h,b,T,D){T===void 0&&(T=0),D===void 0&&(D=0);var w=this._gl,N=this._getWebGLTextureType(h.type),I=this._getInternalFormat(h.format),V=this._getRGBABufferInternalSizedFormat(h.type,I),W=h.isCube?w.TEXTURE_CUBE_MAP:w.TEXTURE_2D;this._bindTextureDirectly(W,h,!0),this._unpackFlipY(h.invertY);var j=w.TEXTURE_2D;h.isCube&&(j=w.TEXTURE_CUBE_MAP_POSITIVE_X+T),w.texImage2D(j,D,V,I,N,b),this._bindTextureDirectly(W,null,!0)},l.prototype.updateRenderTargetTextureSampleCount=function(h,b){if(this.webGLVersion<2||!h)return 1;if(h.samples===b)return b;var T=this._gl;if(b=Math.min(b,this.getCaps().maxMSAASamples),h._depthStencilBuffer&&(T.deleteRenderbuffer(h._depthStencilBuffer),h._depthStencilBuffer=null),h._MSAAFramebuffer&&(T.deleteFramebuffer(h._MSAAFramebuffer),h._MSAAFramebuffer=null),h._MSAARenderBuffer&&(T.deleteRenderbuffer(h._MSAARenderBuffer),h._MSAARenderBuffer=null),b>1&&T.renderbufferStorageMultisample){var D=T.createFramebuffer();if(!D)throw new Error("Unable to create multi sampled framebuffer");h._MSAAFramebuffer=D,this._bindUnboundFramebuffer(h._MSAAFramebuffer);var w=T.createRenderbuffer();if(!w)throw new Error("Unable to create multi sampled framebuffer");T.bindRenderbuffer(T.RENDERBUFFER,w),T.renderbufferStorageMultisample(T.RENDERBUFFER,b,this._getRGBAMultiSampleBufferFormat(h.type),h.width,h.height),T.framebufferRenderbuffer(T.FRAMEBUFFER,T.COLOR_ATTACHMENT0,T.RENDERBUFFER,w),h._MSAARenderBuffer=w}else this._bindUnboundFramebuffer(h._framebuffer);return h.samples=b,h._depthStencilBuffer=this._setupFramebufferDepthAttachments(h._generateStencilBuffer,h._generateDepthBuffer,h.width,h.height,b),this._bindUnboundFramebuffer(null),b},l.prototype.updateTextureComparisonFunction=function(h,b){if(this.webGLVersion!==1){var T=this._gl;h.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),b===0?(T.texParameteri(T.TEXTURE_CUBE_MAP,T.TEXTURE_COMPARE_FUNC,C.a.LEQUAL),T.texParameteri(T.TEXTURE_CUBE_MAP,T.TEXTURE_COMPARE_MODE,T.NONE)):(T.texParameteri(T.TEXTURE_CUBE_MAP,T.TEXTURE_COMPARE_FUNC,b),T.texParameteri(T.TEXTURE_CUBE_MAP,T.TEXTURE_COMPARE_MODE,T.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,h,!0),b===0?(T.texParameteri(T.TEXTURE_2D,T.TEXTURE_COMPARE_FUNC,C.a.LEQUAL),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_COMPARE_MODE,T.NONE)):(T.texParameteri(T.TEXTURE_2D,T.TEXTURE_COMPARE_FUNC,b),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_COMPARE_MODE,T.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),h._comparisonFunction=b}else A.a.Error("WebGL 1 does not support texture comparison.")},l.prototype.createInstancesBuffer=function(h){var b=this._gl.createBuffer();if(!b)throw new Error("Unable to create instance buffer");var T=new E.a(b);return T.capacity=h,this.bindArrayBuffer(T),this._gl.bufferData(this._gl.ARRAY_BUFFER,h,this._gl.DYNAMIC_DRAW),T},l.prototype.deleteInstancesBuffer=function(h){this._gl.deleteBuffer(h)},l.prototype._clientWaitAsync=function(h,b,T){b===void 0&&(b=0),T===void 0&&(T=10);var D=this._gl;return new Promise(function(w,N){var I=function(){var V=D.clientWaitSync(h,b,0);V!=D.WAIT_FAILED?V!=D.TIMEOUT_EXPIRED?w():setTimeout(I,T):N()};I()})},l.prototype._readPixelsAsync=function(h,b,T,D,w,N,I){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");var V=this._gl,W=V.createBuffer();V.bindBuffer(V.PIXEL_PACK_BUFFER,W),V.bufferData(V.PIXEL_PACK_BUFFER,I.byteLength,V.STREAM_READ),V.readPixels(h,b,T,D,w,N,0),V.bindBuffer(V.PIXEL_PACK_BUFFER,null);var j=V.fenceSync(V.SYNC_GPU_COMMANDS_COMPLETE,0);return j?(V.flush(),this._clientWaitAsync(j,0,10).then(function(){return V.deleteSync(j),V.bindBuffer(V.PIXEL_PACK_BUFFER,W),V.getBufferSubData(V.PIXEL_PACK_BUFFER,0,I),V.bindBuffer(V.PIXEL_PACK_BUFFER,null),V.deleteBuffer(W),I})):null},l.prototype.dispose=function(){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();l.Instances.length===1&&l.audioEngine&&l.audioEngine.dispose(),this.disableVR(),x.a.IsWindowObjectExist()&&(window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut)),x.a.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))),g.prototype.dispose.call(this);var h=l.Instances.indexOf(this);h>=0&&l.Instances.splice(h,1),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()},l.prototype._disableTouchAction=function(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.msTouchAction="none")},l.prototype.displayLoadingUI=function(){if(x.a.IsWindowObjectExist()){var h=this.loadingScreen;h&&h.displayLoadingUI()}},l.prototype.hideLoadingUI=function(){if(x.a.IsWindowObjectExist()){var h=this._loadingScreen;h&&h.hideLoadingUI()}},Object.defineProperty(l.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=l.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(h){this._loadingScreen=h},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"loadingUIText",{set:function(h){this.loadingScreen.loadingUIText=h},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"loadingUIBackgroundColor",{set:function(h){this.loadingScreen.loadingUIBackgroundColor=h},enumerable:!1,configurable:!0}),l._RequestPointerlock=function(h){h.requestPointerLock=h.requestPointerLock||h.msRequestPointerLock||h.mozRequestPointerLock||h.webkitRequestPointerLock,h.requestPointerLock&&h.requestPointerLock()},l._ExitPointerlock=function(){var h=document;document.exitPointerLock=document.exitPointerLock||h.msExitPointerLock||h.mozExitPointerLock||h.webkitExitPointerLock,document.exitPointerLock&&document.exitPointerLock()},l._RequestFullscreen=function(h){var b=h.requestFullscreen||h.msRequestFullscreen||h.webkitRequestFullscreen||h.mozRequestFullScreen;b&&b.call(h)},l._ExitFullscreen=function(){var h=document;document.exitFullscreen?document.exitFullscreen():h.mozCancelFullScreen?h.mozCancelFullScreen():h.webkitCancelFullScreen?h.webkitCancelFullScreen():h.msCancelFullScreen&&h.msCancelFullScreen()},l.ALPHA_DISABLE=C.a.ALPHA_DISABLE,l.ALPHA_ADD=C.a.ALPHA_ADD,l.ALPHA_COMBINE=C.a.ALPHA_COMBINE,l.ALPHA_SUBTRACT=C.a.ALPHA_SUBTRACT,l.ALPHA_MULTIPLY=C.a.ALPHA_MULTIPLY,l.ALPHA_MAXIMIZED=C.a.ALPHA_MAXIMIZED,l.ALPHA_ONEONE=C.a.ALPHA_ONEONE,l.ALPHA_PREMULTIPLIED=C.a.ALPHA_PREMULTIPLIED,l.ALPHA_PREMULTIPLIED_PORTERDUFF=C.a.ALPHA_PREMULTIPLIED_PORTERDUFF,l.ALPHA_INTERPOLATE=C.a.ALPHA_INTERPOLATE,l.ALPHA_SCREENMODE=C.a.ALPHA_SCREENMODE,l.DELAYLOADSTATE_NONE=C.a.DELAYLOADSTATE_NONE,l.DELAYLOADSTATE_LOADED=C.a.DELAYLOADSTATE_LOADED,l.DELAYLOADSTATE_LOADING=C.a.DELAYLOADSTATE_LOADING,l.DELAYLOADSTATE_NOTLOADED=C.a.DELAYLOADSTATE_NOTLOADED,l.NEVER=C.a.NEVER,l.ALWAYS=C.a.ALWAYS,l.LESS=C.a.LESS,l.EQUAL=C.a.EQUAL,l.LEQUAL=C.a.LEQUAL,l.GREATER=C.a.GREATER,l.GEQUAL=C.a.GEQUAL,l.NOTEQUAL=C.a.NOTEQUAL,l.KEEP=C.a.KEEP,l.REPLACE=C.a.REPLACE,l.INCR=C.a.INCR,l.DECR=C.a.DECR,l.INVERT=C.a.INVERT,l.INCR_WRAP=C.a.INCR_WRAP,l.DECR_WRAP=C.a.DECR_WRAP,l.TEXTURE_CLAMP_ADDRESSMODE=C.a.TEXTURE_CLAMP_ADDRESSMODE,l.TEXTURE_WRAP_ADDRESSMODE=C.a.TEXTURE_WRAP_ADDRESSMODE,l.TEXTURE_MIRROR_ADDRESSMODE=C.a.TEXTURE_MIRROR_ADDRESSMODE,l.TEXTUREFORMAT_ALPHA=C.a.TEXTUREFORMAT_ALPHA,l.TEXTUREFORMAT_LUMINANCE=C.a.TEXTUREFORMAT_LUMINANCE,l.TEXTUREFORMAT_LUMINANCE_ALPHA=C.a.TEXTUREFORMAT_LUMINANCE_ALPHA,l.TEXTUREFORMAT_RGB=C.a.TEXTUREFORMAT_RGB,l.TEXTUREFORMAT_RGBA=C.a.TEXTUREFORMAT_RGBA,l.TEXTUREFORMAT_RED=C.a.TEXTUREFORMAT_RED,l.TEXTUREFORMAT_R=C.a.TEXTUREFORMAT_R,l.TEXTUREFORMAT_RG=C.a.TEXTUREFORMAT_RG,l.TEXTUREFORMAT_RED_INTEGER=C.a.TEXTUREFORMAT_RED_INTEGER,l.TEXTUREFORMAT_R_INTEGER=C.a.TEXTUREFORMAT_R_INTEGER,l.TEXTUREFORMAT_RG_INTEGER=C.a.TEXTUREFORMAT_RG_INTEGER,l.TEXTUREFORMAT_RGB_INTEGER=C.a.TEXTUREFORMAT_RGB_INTEGER,l.TEXTUREFORMAT_RGBA_INTEGER=C.a.TEXTUREFORMAT_RGBA_INTEGER,l.TEXTURETYPE_UNSIGNED_BYTE=C.a.TEXTURETYPE_UNSIGNED_BYTE,l.TEXTURETYPE_UNSIGNED_INT=C.a.TEXTURETYPE_UNSIGNED_INT,l.TEXTURETYPE_FLOAT=C.a.TEXTURETYPE_FLOAT,l.TEXTURETYPE_HALF_FLOAT=C.a.TEXTURETYPE_HALF_FLOAT,l.TEXTURETYPE_BYTE=C.a.TEXTURETYPE_BYTE,l.TEXTURETYPE_SHORT=C.a.TEXTURETYPE_SHORT,l.TEXTURETYPE_UNSIGNED_SHORT=C.a.TEXTURETYPE_UNSIGNED_SHORT,l.TEXTURETYPE_INT=C.a.TEXTURETYPE_INT,l.TEXTURETYPE_UNSIGNED_INTEGER=C.a.TEXTURETYPE_UNSIGNED_INTEGER,l.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=C.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,l.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=C.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,l.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=C.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,l.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=C.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,l.TEXTURETYPE_UNSIGNED_INT_24_8=C.a.TEXTURETYPE_UNSIGNED_INT_24_8,l.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=C.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,l.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=C.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,l.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=C.a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,l.TEXTURE_NEAREST_SAMPLINGMODE=C.a.TEXTURE_NEAREST_SAMPLINGMODE,l.TEXTURE_BILINEAR_SAMPLINGMODE=C.a.TEXTURE_BILINEAR_SAMPLINGMODE,l.TEXTURE_TRILINEAR_SAMPLINGMODE=C.a.TEXTURE_TRILINEAR_SAMPLINGMODE,l.TEXTURE_NEAREST_NEAREST_MIPLINEAR=C.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,l.TEXTURE_LINEAR_LINEAR_MIPNEAREST=C.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,l.TEXTURE_LINEAR_LINEAR_MIPLINEAR=C.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,l.TEXTURE_NEAREST_NEAREST_MIPNEAREST=C.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,l.TEXTURE_NEAREST_LINEAR_MIPNEAREST=C.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,l.TEXTURE_NEAREST_LINEAR_MIPLINEAR=C.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,l.TEXTURE_NEAREST_LINEAR=C.a.TEXTURE_NEAREST_LINEAR,l.TEXTURE_NEAREST_NEAREST=C.a.TEXTURE_NEAREST_NEAREST,l.TEXTURE_LINEAR_NEAREST_MIPNEAREST=C.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,l.TEXTURE_LINEAR_NEAREST_MIPLINEAR=C.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,l.TEXTURE_LINEAR_LINEAR=C.a.TEXTURE_LINEAR_LINEAR,l.TEXTURE_LINEAR_NEAREST=C.a.TEXTURE_LINEAR_NEAREST,l.TEXTURE_EXPLICIT_MODE=C.a.TEXTURE_EXPLICIT_MODE,l.TEXTURE_SPHERICAL_MODE=C.a.TEXTURE_SPHERICAL_MODE,l.TEXTURE_PLANAR_MODE=C.a.TEXTURE_PLANAR_MODE,l.TEXTURE_CUBIC_MODE=C.a.TEXTURE_CUBIC_MODE,l.TEXTURE_PROJECTION_MODE=C.a.TEXTURE_PROJECTION_MODE,l.TEXTURE_SKYBOX_MODE=C.a.TEXTURE_SKYBOX_MODE,l.TEXTURE_INVCUBIC_MODE=C.a.TEXTURE_INVCUBIC_MODE,l.TEXTURE_EQUIRECTANGULAR_MODE=C.a.TEXTURE_EQUIRECTANGULAR_MODE,l.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=C.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,l.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=C.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,l.SCALEMODE_FLOOR=C.a.SCALEMODE_FLOOR,l.SCALEMODE_NEAREST=C.a.SCALEMODE_NEAREST,l.SCALEMODE_CEILING=C.a.SCALEMODE_CEILING,l._RescalePostProcessFactory=null,l}(R.a))},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){}return _.WithinEpsilon=function(x,u,M){M===void 0&&(M=1401298e-51);var R=x-u;return-M<=R&&R<=M},_.ToHex=function(x){var u=x.toString(16);return x<=15?("0"+u).toUpperCase():u.toUpperCase()},_.Sign=function(x){return(x=+x)==0||isNaN(x)?x:x>0?1:-1},_.Clamp=function(x,u,M){return u===void 0&&(u=0),M===void 0&&(M=1),Math.min(M,Math.max(u,x))},_.Log2=function(x){return Math.log(x)*Math.LOG2E},_.Repeat=function(x,u){return x-Math.floor(x/u)*u},_.Normalize=function(x,u,M){return(x-u)/(M-u)},_.Denormalize=function(x,u,M){return x*(M-u)+u},_.DeltaAngle=function(x,u){var M=_.Repeat(u-x,360);return M>180&&(M-=360),M},_.PingPong=function(x,u){var M=_.Repeat(x,2*u);return u-Math.abs(M-u)},_.SmoothStep=function(x,u,M){var R=_.Clamp(M);return u*(R=-2*R*R*R+3*R*R)+x*(1-R)},_.MoveTowards=function(x,u,M){return Math.abs(u-x)<=M?u:x+_.Sign(u-x)*M},_.MoveTowardsAngle=function(x,u,M){var R=_.DeltaAngle(x,u),C=0;return-M180&&(R-=360),x+R*_.Clamp(M)},_.InverseLerp=function(x,u,M){return x!=u?_.Clamp((M-x)/(u-x)):0},_.Hermite=function(x,u,M,R,C){var m=C*C,c=C*m;return x*(2*c-3*m+1)+M*(-2*c+3*m)+u*(c-2*m+C)+R*(c-m)},_.RandomRange=function(x,u){return x===u?x:Math.random()*(u-x)+x},_.RangeToPercent=function(x,u,M){return(x-u)/(M-u)},_.PercentToRange=function(x,u,M){return(M-u)*x+u},_.NormalizeRadians=function(x){return x-=_.TwoPi*Math.floor((x+Math.PI)/_.TwoPi)},_.TwoPi=2*Math.PI,_}()},function(Ae,v,f){f.d(v,"a",function(){return c});var B=f(8),_=f(20),x=f(22),u=f(4),M=f(48),R=f(2),C=f(9),m=f(119),c=function(){function E(){}return E.BindEyePosition=function(A,S,g){if(g===void 0&&(g="vEyePosition"),S._forcedViewPosition)A.setVector3(g,S._forcedViewPosition);else{var l=S.activeCamera.globalPosition;l||(l=S.activeCamera.devicePosition),A.setVector3(g,S._mirroredCameraPosition?S._mirroredCameraPosition:l)}},E.PrepareDefinesForMergedUV=function(A,S,g){S._needUVs=!0,S[g]=!0,A.getTextureMatrix().isIdentityAs3x2()?(S[g+"DIRECTUV"]=A.coordinatesIndex+1,A.coordinatesIndex===0?S.MAINUV1=!0:S.MAINUV2=!0):S[g+"DIRECTUV"]=0},E.BindTextureMatrix=function(A,S,g){var l=A.getTextureMatrix();S.updateMatrix(g+"Matrix",l)},E.GetFogState=function(A,S){return S.fogEnabled&&A.applyFog&&S.fogMode!==_.a.FOGMODE_NONE},E.PrepareDefinesForMisc=function(A,S,g,l,h,b,T){T._areMiscDirty&&(T.LOGARITHMICDEPTH=g,T.POINTSIZE=l,T.FOG=h&&this.GetFogState(A,S),T.NONUNIFORMSCALING=A.nonUniformScaling,T.ALPHATEST=b)},E.PrepareDefinesForFrameBoundValues=function(A,S,g,l,h,b){h===void 0&&(h=null),b===void 0&&(b=!1);var T,D,w,N,I,V,W=!1;T=h??(A.clipPlane!==void 0&&A.clipPlane!==null),D=h??(A.clipPlane2!==void 0&&A.clipPlane2!==null),w=h??(A.clipPlane3!==void 0&&A.clipPlane3!==null),N=h??(A.clipPlane4!==void 0&&A.clipPlane4!==null),I=h??(A.clipPlane5!==void 0&&A.clipPlane5!==null),V=h??(A.clipPlane6!==void 0&&A.clipPlane6!==null),g.CLIPPLANE!==T&&(g.CLIPPLANE=T,W=!0),g.CLIPPLANE2!==D&&(g.CLIPPLANE2=D,W=!0),g.CLIPPLANE3!==w&&(g.CLIPPLANE3=w,W=!0),g.CLIPPLANE4!==N&&(g.CLIPPLANE4=N,W=!0),g.CLIPPLANE5!==I&&(g.CLIPPLANE5=I,W=!0),g.CLIPPLANE6!==V&&(g.CLIPPLANE6=V,W=!0),g.DEPTHPREPASS!==!S.getColorWrite()&&(g.DEPTHPREPASS=!g.DEPTHPREPASS,W=!0),g.INSTANCES!==l&&(g.INSTANCES=l,W=!0),g.THIN_INSTANCES!==b&&(g.THIN_INSTANCES=b,W=!0),W&&g.markAsUnprocessed()},E.PrepareDefinesForBones=function(A,S){if(A.useBones&&A.computeBonesUsingShaders&&A.skeleton){S.NUM_BONE_INFLUENCERS=A.numBoneInfluencers;var g=S.BONETEXTURE!==void 0;if(A.skeleton.isUsingTextureForMatrices&&g)S.BONETEXTURE=!0;else{S.BonesPerMesh=A.skeleton.bones.length+1,S.BONETEXTURE=!g&&void 0;var l=A.getScene().prePassRenderer;if(l&&l.enabled){var h=l.excludedSkinnedMesh.indexOf(A)===-1;S.BONES_VELOCITY_ENABLED=h}}}else S.NUM_BONE_INFLUENCERS=0,S.BonesPerMesh=0},E.PrepareDefinesForMorphTargets=function(A,S){var g=A.morphTargetManager;g?(S.MORPHTARGETS_UV=g.supportsUVs&&S.UV1,S.MORPHTARGETS_TANGENT=g.supportsTangents&&S.TANGENT,S.MORPHTARGETS_NORMAL=g.supportsNormals&&S.NORMAL,S.MORPHTARGETS=g.numInfluencers>0,S.NUM_MORPH_INFLUENCERS=g.numInfluencers):(S.MORPHTARGETS_UV=!1,S.MORPHTARGETS_TANGENT=!1,S.MORPHTARGETS_NORMAL=!1,S.MORPHTARGETS=!1,S.NUM_MORPH_INFLUENCERS=0)},E.PrepareDefinesForAttributes=function(A,S,g,l,h,b){if(h===void 0&&(h=!1),b===void 0&&(b=!0),!S._areAttributesDirty&&S._needNormals===S._normals&&S._needUVs===S._uvs)return!1;if(S._normals=S._needNormals,S._uvs=S._needUVs,S.NORMAL=S._needNormals&&A.isVerticesDataPresent(u.b.NormalKind),S._needNormals&&A.isVerticesDataPresent(u.b.TangentKind)&&(S.TANGENT=!0),S._needUVs?(S.UV1=A.isVerticesDataPresent(u.b.UVKind),S.UV2=A.isVerticesDataPresent(u.b.UV2Kind)):(S.UV1=!1,S.UV2=!1),g){var T=A.useVertexColors&&A.isVerticesDataPresent(u.b.ColorKind);S.VERTEXCOLOR=T,S.VERTEXALPHA=A.hasVertexAlpha&&T&&b}return l&&this.PrepareDefinesForBones(A,S),h&&this.PrepareDefinesForMorphTargets(A,S),!0},E.PrepareDefinesForMultiview=function(A,S){if(A.activeCamera){var g=S.MULTIVIEW;S.MULTIVIEW=A.activeCamera.outputRenderTarget!==null&&A.activeCamera.outputRenderTarget.getViewCount()>1,S.MULTIVIEW!=g&&S.markAsUnprocessed()}},E.PrepareDefinesForPrePass=function(A,S,g){var l=S.PREPASS;if(S._arePrePassDirty){var h=[{type:R.a.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:R.a.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:R.a.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:R.a.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:R.a.PREPASS_ALBEDO_TEXTURE_TYPE,define:"PREPASS_ALBEDO",index:"PREPASS_ALBEDO_INDEX"},{type:R.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE,define:"PREPASS_DEPTHNORMAL",index:"PREPASS_DEPTHNORMAL_INDEX"}];if(A.prePassRenderer&&A.prePassRenderer.enabled&&g){S.PREPASS=!0,S.SCENE_MRT_COUNT=A.prePassRenderer.mrtCount;for(var b=0;b0&&(T.shadowEnabled=!0,D.prepareDefines(h,l))}}g.lightmapMode!=M.a.LIGHTMAP_DEFAULT?(T.lightmapMode=!0,h["LIGHTMAPEXCLUDED"+l]=!0,h["LIGHTMAPNOSPECULAR"+l]=g.lightmapMode==M.a.LIGHTMAP_SHADOWSONLY):(h["LIGHTMAPEXCLUDED"+l]=!1,h["LIGHTMAPNOSPECULAR"+l]=!1)},E.PrepareDefinesForLights=function(A,S,g,l,h,b){if(h===void 0&&(h=4),b===void 0&&(b=!1),!g._areLightsDirty)return g._needNormals;var T=0,D={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(A.lightsEnabled&&!b)for(var w=0,N=S.lightSources;w0&&(h=l+b,S.addFallback(h,"LIGHT"+b)),A.SHADOWS||(A["SHADOW"+b]&&S.addFallback(l,"SHADOW"+b),A["SHADOWPCF"+b]&&S.addFallback(l,"SHADOWPCF"+b),A["SHADOWPCSS"+b]&&S.addFallback(l,"SHADOWPCSS"+b),A["SHADOWPOISSON"+b]&&S.addFallback(l,"SHADOWPOISSON"+b),A["SHADOWESM"+b]&&S.addFallback(l,"SHADOWESM"+b),A["SHADOWCLOSEESM"+b]&&S.addFallback(l,"SHADOWCLOSEESM"+b));return h++},E.PrepareAttributesForMorphTargetsInfluencers=function(A,S,g){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=g,this.PrepareAttributesForMorphTargets(A,S,this._TmpMorphInfluencers)},E.PrepareAttributesForMorphTargets=function(A,S,g){var l=g.NUM_MORPH_INFLUENCERS;if(l>0&&x.a.LastCreatedEngine)for(var h=x.a.LastCreatedEngine.getCaps().maxVertexAttribs,b=S.morphTargetManager,T=b&&b.supportsNormals&&g.NORMAL,D=b&&b.supportsTangents&&g.TANGENT,w=b&&b.supportsUVs&&g.UV1,N=0;Nh&&B.a.Error("Cannot add more vertex attributes for mesh "+S.name)},E.PrepareAttributesForBones=function(A,S,g,l){g.NUM_BONE_INFLUENCERS>0&&(l.addCPUSkinningFallback(0,S),A.push(u.b.MatricesIndicesKind),A.push(u.b.MatricesWeightsKind),g.NUM_BONE_INFLUENCERS>4&&(A.push(u.b.MatricesIndicesExtraKind),A.push(u.b.MatricesWeightsExtraKind)))},E.PrepareAttributesForInstances=function(A,S){(S.INSTANCES||S.THIN_INSTANCES)&&this.PushAttributesForInstances(A)},E.PushAttributesForInstances=function(A){A.push("world0"),A.push("world1"),A.push("world2"),A.push("world3")},E.BindLightProperties=function(A,S,g){A.transferToEffect(S,g+"")},E.BindLight=function(A,S,g,l,h,b){b===void 0&&(b=!1),A._bindLight(S,g,l,h,b)},E.BindLights=function(A,S,g,l,h,b){h===void 0&&(h=4),b===void 0&&(b=!1);for(var T=Math.min(S.lightSources.length,h),D=0;D-1){var h=l.getTransformMatrixTexture(A);S.setTexture("boneSampler",h),S.setFloat("boneTextureWidth",4*(l.bones.length+1))}else{var b=l.getTransformMatrices(A);b&&(S.setMatrices("mBones",b),g&&A.getScene().prePassRenderer&&A.getScene().prePassRenderer.getIndex(R.a.PREPASS_VELOCITY_TEXTURE_TYPE)&&(g.previousBones[A.uniqueId]&&S.setMatrices("mPreviousBones",g.previousBones[A.uniqueId]),E._CopyBonesTransformationMatrices(b,g.previousBones[A.uniqueId])))}}},E._CopyBonesTransformationMatrices=function(A,S){return S.set(A),S},E.BindMorphTargetParameters=function(A,S){var g=A.morphTargetManager;A&&g&&S.setFloatArray("morphTargetInfluences",g.influences)},E.BindLogDepth=function(A,S,g){A.LOGARITHMICDEPTH&&S.setFloat("logarithmicDepthConstant",2/(Math.log(g.activeCamera.maxZ+1)/Math.LN2))},E.BindClipPlane=function(A,S){m.a.BindClipPlane(A,S)},E._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},E._tempFogColor=C.a.Black(),E}()},function(Ae,v,f){f.d(v,"a",function(){return R});var B=f(0),_=f(4),x=f(21),u=f(9),M=f(8),R=function(){function C(){}return C.prototype.set=function(m,c){switch(m.length||M.a.Warn("Setting vertex data kind '"+c+"' with an empty array"),c){case _.b.PositionKind:this.positions=m;break;case _.b.NormalKind:this.normals=m;break;case _.b.TangentKind:this.tangents=m;break;case _.b.UVKind:this.uvs=m;break;case _.b.UV2Kind:this.uvs2=m;break;case _.b.UV3Kind:this.uvs3=m;break;case _.b.UV4Kind:this.uvs4=m;break;case _.b.UV5Kind:this.uvs5=m;break;case _.b.UV6Kind:this.uvs6=m;break;case _.b.ColorKind:this.colors=m;break;case _.b.MatricesIndicesKind:this.matricesIndices=m;break;case _.b.MatricesWeightsKind:this.matricesWeights=m;break;case _.b.MatricesIndicesExtraKind:this.matricesIndicesExtra=m;break;case _.b.MatricesWeightsExtraKind:this.matricesWeightsExtra=m}},C.prototype.applyToMesh=function(m,c){return this._applyTo(m,c),this},C.prototype.applyToGeometry=function(m,c){return this._applyTo(m,c),this},C.prototype.updateMesh=function(m){return this._update(m),this},C.prototype.updateGeometry=function(m){return this._update(m),this},C.prototype._applyTo=function(m,c){return c===void 0&&(c=!1),this.positions&&m.setVerticesData(_.b.PositionKind,this.positions,c),this.normals&&m.setVerticesData(_.b.NormalKind,this.normals,c),this.tangents&&m.setVerticesData(_.b.TangentKind,this.tangents,c),this.uvs&&m.setVerticesData(_.b.UVKind,this.uvs,c),this.uvs2&&m.setVerticesData(_.b.UV2Kind,this.uvs2,c),this.uvs3&&m.setVerticesData(_.b.UV3Kind,this.uvs3,c),this.uvs4&&m.setVerticesData(_.b.UV4Kind,this.uvs4,c),this.uvs5&&m.setVerticesData(_.b.UV5Kind,this.uvs5,c),this.uvs6&&m.setVerticesData(_.b.UV6Kind,this.uvs6,c),this.colors&&m.setVerticesData(_.b.ColorKind,this.colors,c),this.matricesIndices&&m.setVerticesData(_.b.MatricesIndicesKind,this.matricesIndices,c),this.matricesWeights&&m.setVerticesData(_.b.MatricesWeightsKind,this.matricesWeights,c),this.matricesIndicesExtra&&m.setVerticesData(_.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,c),this.matricesWeightsExtra&&m.setVerticesData(_.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,c),this.indices?m.setIndices(this.indices,null,c):m.setIndices([],null),this},C.prototype._update=function(m,c,E){return this.positions&&m.updateVerticesData(_.b.PositionKind,this.positions,c,E),this.normals&&m.updateVerticesData(_.b.NormalKind,this.normals,c,E),this.tangents&&m.updateVerticesData(_.b.TangentKind,this.tangents,c,E),this.uvs&&m.updateVerticesData(_.b.UVKind,this.uvs,c,E),this.uvs2&&m.updateVerticesData(_.b.UV2Kind,this.uvs2,c,E),this.uvs3&&m.updateVerticesData(_.b.UV3Kind,this.uvs3,c,E),this.uvs4&&m.updateVerticesData(_.b.UV4Kind,this.uvs4,c,E),this.uvs5&&m.updateVerticesData(_.b.UV5Kind,this.uvs5,c,E),this.uvs6&&m.updateVerticesData(_.b.UV6Kind,this.uvs6,c,E),this.colors&&m.updateVerticesData(_.b.ColorKind,this.colors,c,E),this.matricesIndices&&m.updateVerticesData(_.b.MatricesIndicesKind,this.matricesIndices,c,E),this.matricesWeights&&m.updateVerticesData(_.b.MatricesWeightsKind,this.matricesWeights,c,E),this.matricesIndicesExtra&&m.updateVerticesData(_.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,c,E),this.matricesWeightsExtra&&m.updateVerticesData(_.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,c,E),this.indices&&m.setIndices(this.indices,null),this},C.prototype.transform=function(m){var c,E=m.determinant()<0,A=B.e.Zero();if(this.positions){var S=B.e.Zero();for(c=0;cA.bbSize.y?A.bbSize.x:A.bbSize.y;lt=lt>A.bbSize.z?lt:A.bbSize.z,H=A.subDiv.X*re/A.bbSize.x,Z=A.subDiv.Y*re/A.bbSize.y,X=A.subDiv.Z*re/A.bbSize.z,q=A.subDiv.max*A.subDiv.max,A.facetPartitioning.length=0}for(S=0;Sre.LongPressDelay&&!H._isPointerSwiping()&&(H._startingPointerTime=0,X.processTrigger(I.a.ACTION_OnLongPressTrigger,T.a.CreateNew(_e.pickedMesh,k)))},re.LongPressDelay)}}else for(var q=0,he=Z._pointerDownStage;qre.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>re.DragMovementThreshold},re.prototype.simulatePointerUp=function(Y,k,H){var Z=new PointerEvent("pointerup",k),X=new ae;H?X.doubleClick=!0:X.singleClick=!0,this._checkPrePointerObservable(Y,Z,te.a.POINTERUP)||this._processPointerUp(Y,Z,X)},re.prototype._processPointerUp=function(Y,k,H){var Z=this._scene;if(Y&&Y&&Y.pickedMesh){if(this._pickedUpMesh=Y.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(Z.onPointerPick&&Z.onPointerPick(k,Y),H.singleClick&&!H.ignore&&Z.onPointerObservable.hasObservers())){var X=te.a.POINTERPICK,q=new te.b(X,k,Y);this._setRayOnPointerInfo(q),Z.onPointerObservable.notifyObservers(q,X)}var he=Y.pickedMesh._getActionManagerForTrigger();if(he&&!H.ignore){he.processTrigger(I.a.ACTION_OnPickUpTrigger,T.a.CreateNew(Y.pickedMesh,k)),!H.hasSwiped&&H.singleClick&&he.processTrigger(I.a.ACTION_OnPickTrigger,T.a.CreateNew(Y.pickedMesh,k));var ge=Y.pickedMesh._getActionManagerForTrigger(I.a.ACTION_OnDoublePickTrigger);H.doubleClick&&ge&&ge.processTrigger(I.a.ACTION_OnDoublePickTrigger,T.a.CreateNew(Y.pickedMesh,k))}}else if(!H.ignore)for(var me=0,_e=Z._pointerUpStage;me<_e.length;me++)Y=_e[me].action(this._unTranslatedPointerX,this._unTranslatedPointerY,Y,k);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){var be=this._pickedDownMesh._getActionManagerForTrigger(I.a.ACTION_OnPickOutTrigger);be&&be.processTrigger(I.a.ACTION_OnPickOutTrigger,T.a.CreateNew(this._pickedDownMesh,k))}var Ce=0;Z.onPointerObservable.hasObservers()&&(!H.ignore&&!H.hasSwiped&&(H.singleClick&&Z.onPointerObservable.hasSpecificMask(te.a.POINTERTAP)?Ce=te.a.POINTERTAP:H.doubleClick&&Z.onPointerObservable.hasSpecificMask(te.a.POINTERDOUBLETAP)&&(Ce=te.a.POINTERDOUBLETAP),Ce)&&(q=new te.b(Ce,k,Y),this._setRayOnPointerInfo(q),Z.onPointerObservable.notifyObservers(q,Ce)),H.ignore||(Ce=te.a.POINTERUP,q=new te.b(Ce,k,Y),this._setRayOnPointerInfo(q),Z.onPointerObservable.notifyObservers(q,Ce))),Z.onPointerUp&&!H.ignore&&Z.onPointerUp(k,Y,Ce)},re.prototype.isPointerCaptured=function(Y){return Y===void 0&&(Y=0),this._pointerCaptures[Y]},re.prototype.attachControl=function(Y,k,H,Z){var X=this;Y===void 0&&(Y=!0),k===void 0&&(k=!0),H===void 0&&(H=!0),Z===void 0&&(Z=null);var q=this._scene;if(Z||(Z=q.getEngine().getInputElement()),Z){this._alreadyAttached&&this.detachControl(),this._alreadyAttachedTo=Z;var he=q.getEngine();this._initActionManager=function(be,Ce){if(!X._meshPickProceed){var ye=q.pick(X._unTranslatedPointerX,X._unTranslatedPointerY,q.pointerDownPredicate,!1,q.cameraToUseForPointers);X._currentPickResult=ye,ye&&(be=ye.hit&&ye.pickedMesh?ye.pickedMesh._getActionManagerForTrigger():null),X._meshPickProceed=!0}return be},this._delayedSimpleClick=function(be,Ce,ye){(Date.now()-X._previousStartingPointerTime>re.DoubleClickDelay&&!X._doubleClickOccured||be!==X._previousButtonPressed)&&(X._doubleClickOccured=!1,Ce.singleClick=!0,Ce.ignore=!1,ye(Ce,X._currentPickResult))},this._initClickEvent=function(be,Ce,ye,Be){var Ge=new ae;X._currentPickResult=null;var Xe=null,He=be.hasSpecificMask(te.a.POINTERPICK)||Ce.hasSpecificMask(te.a.POINTERPICK)||be.hasSpecificMask(te.a.POINTERTAP)||Ce.hasSpecificMask(te.a.POINTERTAP)||be.hasSpecificMask(te.a.POINTERDOUBLETAP)||Ce.hasSpecificMask(te.a.POINTERDOUBLETAP);!He&&de.a&&(Xe=X._initActionManager(Xe,Ge))&&(He=Xe.hasPickTriggers);var We=!1;if(He){var Ze=ye.button;if(Ge.hasSwiped=X._isPointerSwiping(),!Ge.hasSwiped){var ze=!re.ExclusiveDoubleClickMode;ze||(ze=!be.hasSpecificMask(te.a.POINTERDOUBLETAP)&&!Ce.hasSpecificMask(te.a.POINTERDOUBLETAP))&&!de.a.HasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)&&(Xe=X._initActionManager(Xe,Ge))&&(ze=!Xe.hasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)),ze?(Date.now()-X._previousStartingPointerTime>re.DoubleClickDelay||Ze!==X._previousButtonPressed)&&(Ge.singleClick=!0,Be(Ge,X._currentPickResult),We=!0):(X._previousDelayedSimpleClickTimeout=X._delayedSimpleClickTimeout,X._delayedSimpleClickTimeout=window.setTimeout(X._delayedSimpleClick.bind(X,Ze,Ge,Be),re.DoubleClickDelay));var it=be.hasSpecificMask(te.a.POINTERDOUBLETAP)||Ce.hasSpecificMask(te.a.POINTERDOUBLETAP);!it&&de.a.HasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)&&(Xe=X._initActionManager(Xe,Ge))&&(it=Xe.hasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)),it&&(Ze===X._previousButtonPressed&&Date.now()-X._previousStartingPointerTime0){for(var k=0,H=this._transientComponents;k0)return!1;for(k=0;k0,q=0,he=this._isReadyForMeshStage;q0){for(var ge=0,me=this.activeCameras;ge0},enumerable:!1,configurable:!0}),Y.prototype.executeWhenReady=function(k){var H=this;this.onReadyObservable.add(k),this._executeWhenReadyTimeoutId===-1&&(this._executeWhenReadyTimeoutId=setTimeout(function(){H._checkIsReady()},150))},Y.prototype.whenReadyAsync=function(){var k=this;return new Promise(function(H){k.executeWhenReady(function(){H()})})},Y.prototype._checkIsReady=function(){var k=this;return this._registerTransientComponents(),this.isReady()?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):void(this._executeWhenReadyTimeoutId=setTimeout(function(){k._checkIsReady()},150))},Object.defineProperty(Y.prototype,"animatables",{get:function(){return this._activeAnimatables},enumerable:!1,configurable:!0}),Y.prototype.resetLastAnimationTimeFrame=function(){this._animationTimeLast=x.a.Now},Y.prototype.getViewMatrix=function(){return this._viewMatrix},Y.prototype.getProjectionMatrix=function(){return this._projectionMatrix},Y.prototype.getTransformMatrix=function(){return this._transformMatrix},Y.prototype.setTransformMatrix=function(k,H,Z,X){this._viewUpdateFlag===k.updateFlag&&this._projectionUpdateFlag===H.updateFlag||(this._viewUpdateFlag=k.updateFlag,this._projectionUpdateFlag=H.updateFlag,this._viewMatrix=k,this._projectionMatrix=H,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?L.a.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=L.a.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(Z,X):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.update()))},Y.prototype.getSceneUniformBuffer=function(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo},Y.prototype.getUniqueId=function(){return G.a.UniqueId},Y.prototype.addMesh=function(k,H){var Z=this;H===void 0&&(H=!1),this._blockEntityCollection||(this.meshes.push(k),k._resyncLightSources(),k.parent||k._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(k),H&&k.getChildMeshes().forEach(function(X){Z.addMesh(X)}))},Y.prototype.removeMesh=function(k,H){var Z=this;H===void 0&&(H=!1);var X=this.meshes.indexOf(k);return X!==-1&&(this.meshes[X]=this.meshes[this.meshes.length-1],this.meshes.pop(),k.parent||k._removeFromSceneRootNodes()),this.onMeshRemovedObservable.notifyObservers(k),H&&k.getChildMeshes().forEach(function(q){Z.removeMesh(q)}),X},Y.prototype.addTransformNode=function(k){this._blockEntityCollection||(k._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(k),k.parent||k._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(k))},Y.prototype.removeTransformNode=function(k){var H=k._indexInSceneTransformNodesArray;if(H!==-1){if(H!==this.transformNodes.length-1){var Z=this.transformNodes[this.transformNodes.length-1];this.transformNodes[H]=Z,Z._indexInSceneTransformNodesArray=H}k._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),k.parent||k._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(k),H},Y.prototype.removeSkeleton=function(k){var H=this.skeletons.indexOf(k);return H!==-1&&(this.skeletons.splice(H,1),this.onSkeletonRemovedObservable.notifyObservers(k)),H},Y.prototype.removeMorphTargetManager=function(k){var H=this.morphTargetManagers.indexOf(k);return H!==-1&&this.morphTargetManagers.splice(H,1),H},Y.prototype.removeLight=function(k){var H=this.lights.indexOf(k);if(H!==-1){for(var Z=0,X=this.meshes;Z0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(k),H},Y.prototype.removeParticleSystem=function(k){var H=this.particleSystems.indexOf(k);return H!==-1&&this.particleSystems.splice(H,1),H},Y.prototype.removeAnimation=function(k){var H=this.animations.indexOf(k);return H!==-1&&this.animations.splice(H,1),H},Y.prototype.stopAnimation=function(k,H,Z){},Y.prototype.removeAnimationGroup=function(k){var H=this.animationGroups.indexOf(k);return H!==-1&&this.animationGroups.splice(H,1),H},Y.prototype.removeMultiMaterial=function(k){var H=this.multiMaterials.indexOf(k);return H!==-1&&this.multiMaterials.splice(H,1),this.onMultiMaterialRemovedObservable.notifyObservers(k),H},Y.prototype.removeMaterial=function(k){var H=k._indexInSceneMaterialArray;if(H!==-1&&H=0;H--)if(this.materials[H].id===k)return this.materials[H];return null},Y.prototype.getMaterialByName=function(k){for(var H=0;H=0;H--)if(this.meshes[H].id===k)return this.meshes[H];return null},Y.prototype.getLastEntryByID=function(k){var H;for(H=this.meshes.length-1;H>=0;H--)if(this.meshes[H].id===k)return this.meshes[H];for(H=this.transformNodes.length-1;H>=0;H--)if(this.transformNodes[H].id===k)return this.transformNodes[H];for(H=this.cameras.length-1;H>=0;H--)if(this.cameras[H].id===k)return this.cameras[H];for(H=this.lights.length-1;H>=0;H--)if(this.lights[H].id===k)return this.lights[H];return null},Y.prototype.getNodeByID=function(k){var H=this.getMeshByID(k);if(H)return H;var Z=this.getTransformNodeByID(k);if(Z)return Z;var X=this.getLightByID(k);if(X)return X;var q=this.getCameraByID(k);if(q)return q;var he=this.getBoneByID(k);return he||null},Y.prototype.getNodeByName=function(k){var H=this.getMeshByName(k);if(H)return H;var Z=this.getTransformNodeByName(k);if(Z)return Z;var X=this.getLightByName(k);if(X)return X;var q=this.getCameraByName(k);if(q)return q;var he=this.getBoneByName(k);return he||null},Y.prototype.getMeshByName=function(k){for(var H=0;H=0;H--)if(this.skeletons[H].id===k)return this.skeletons[H];return null},Y.prototype.getSkeletonByUniqueId=function(k){for(var H=0;H0&&(me.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||me.alwaysSelectAsActiveMesh||me.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(me),this.activeCamera._activeMeshes.push(me),_e!==me&&_e._activate(this._renderId,!1);for(var be=0,Ce=this._preActiveMeshStage;be0)for(var Z=this.getActiveSubMeshCandidates(H),X=Z.length,q=0;q1)this.activeCamera.outputRenderTarget._bindFrameBuffer();else{var k=this.activeCamera.outputRenderTarget.getInternalTexture();k?this.getEngine().bindFramebuffer(k):W.a.Error("Camera contains invalid customDefaultRenderTarget")}else this.getEngine().restoreDefaultFramebuffer()},Y.prototype._renderForCamera=function(k,H){if(!k||!k._skipRendering){var Z=this._engine;if(this._activeCamera=k,!this.activeCamera)throw new Error("Active camera not set");Z.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,this.getEngine().getCaps().multiview&&k.outputRenderTarget&&k.outputRenderTarget.getViewCount()>1?this.setTransformMatrix(k._rigCameras[0].getViewMatrix(),k._rigCameras[0].getProjectionMatrix(),k._rigCameras[1].getViewMatrix(),k._rigCameras[1].getProjectionMatrix()):this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(var X=0;X0&&this._renderTargets.concatWithNoDuplicate(k.customRenderTargets),H&&H.customRenderTargets&&H.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(H.customRenderTargets);for(var he=0,ge=this._gatherActiveCameraRenderTargetsStage;he0){_.b.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var _e=0;_e0),this._renderId++}for(var ye=0,Be=this._cameraDrawRenderTargetStage;ye1&&this.getEngine().getCaps().multiview)return this._renderForCamera(k),void this.onAfterRenderCameraObservable.notifyObservers(k);if(k._useMultiviewToSingleView)this._renderMultiviewToSingleView(k);else for(var H=0;H-1&&(X.trigger===I.a.ACTION_OnIntersectionExitTrigger&&X._executeCurrent(T.a.CreateNew(H,void 0,he)),H.actionManager.hasSpecificTrigger(I.a.ACTION_OnIntersectionExitTrigger,function(_e){var be=_e instanceof E.a?_e:_e.mesh;return he===be})&&X.trigger!==I.a.ACTION_OnIntersectionExitTrigger||H._intersectionsInProgress.splice(me,1))}}}},Y.prototype._advancePhysicsEngineStep=function(k){},Y.prototype._animate=function(){},Y.prototype.animate=function(){if(this._engine.isDeterministicLockStep()){var k=Math.max(Y.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Y.MaxDeltaTime))+this._timeAccumulator,H=this._engine.getTimeStep(),Z=1e3/H/1e3,X=0,q=this._engine.getLockstepMaxSteps(),he=Math.floor(k/H);for(he=Math.min(he,q);k>0&&X0)for(var q=0;q0),this._intermediateRendering=!0;for(var be=0;be0),this._intermediateRendering=!1,this._renderId++}this.activeCamera=_e,this._activeCamera&&this._activeCamera.cameraRigMode!==A.a.RIG_MODE_CUSTOM&&!this.prePass&&this._bindFrameBuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(var ye=0,Be=this._beforeClearStage;ye0)for(q=0;q0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[q]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections();for(var He=0,We=this._afterRenderStage;He-1&&this._engine.scenes.splice(q,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(Y.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),Y.prototype.clearCachedVertexData=function(){for(var k=0;k-1?(m.a.Error("You're trying to reuse a post process not defined as reusable."),0):(T==null||T<0?this._postProcesses.push(b):this._postProcesses[T]===null?this._postProcesses[T]=b:this._postProcesses.splice(T,0,b),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(b))},h.prototype.detachPostProcess=function(b){var T=this._postProcesses.indexOf(b);T!==-1&&(this._postProcesses[T]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()},h.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix},h.prototype._getViewMatrix=function(){return R.a.Identity()},h.prototype.getViewMatrix=function(b){return!b&&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},h.prototype.freezeProjectionMatrix=function(b){this._doNotComputeProjectionMatrix=!0,b!==void 0&&(this._projectionMatrix=b)},h.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},h.prototype.getProjectionMatrix=function(b){var T,D,w,N,I,V,W,j;if(this._doNotComputeProjectionMatrix||!b&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var ne=this.getEngine(),te=this.getScene();if(this.mode===h.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=ne.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1);var de=ne.useReverseDepthBuffer;(te.useRightHandedSystem?de?R.a.PerspectiveFovReverseRHToRef:R.a.PerspectiveFovRHToRef:de?R.a.PerspectiveFovReverseLHToRef:R.a.PerspectiveFovLHToRef)(this.fov,ne.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===h.FOVMODE_VERTICAL_FIXED)}else{var pe=ne.getRenderWidth()/2,ae=ne.getRenderHeight()/2;te.useRightHandedSystem?R.a.OrthoOffCenterRHToRef((T=this.orthoLeft)!==null&&T!==void 0?T:-pe,(D=this.orthoRight)!==null&&D!==void 0?D:pe,(w=this.orthoBottom)!==null&&w!==void 0?w:-ae,(N=this.orthoTop)!==null&&N!==void 0?N:ae,this.minZ,this.maxZ,this._projectionMatrix):R.a.OrthoOffCenterLHToRef((I=this.orthoLeft)!==null&&I!==void 0?I:-pe,(V=this.orthoRight)!==null&&V!==void 0?V:pe,(W=this.orthoBottom)!==null&&W!==void 0?W:-ae,(j=this.orthoTop)!==null&&j!==void 0?j:ae,this.minZ,this.maxZ,this._projectionMatrix),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=ne.getRenderWidth(),this._cache.renderHeight=ne.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},h.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},h.prototype._updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?S.a.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=S.a.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},h.prototype.isInFrustum=function(b,T){if(T===void 0&&(T=!1),this._updateFrustumPlanes(),T&&this.rigCameras.length>0){var D=!1;return this.rigCameras.forEach(function(w){w._updateFrustumPlanes(),D=D||b.isInFrustum(w._frustumPlanes)}),D}return b.isInFrustum(this._frustumPlanes)},h.prototype.isCompletelyInFrustum=function(b){return this._updateFrustumPlanes(),b.isCompletelyInFrustum(this._frustumPlanes)},h.prototype.getForwardRay=function(b,T,D){throw E.a.WarnImport("Ray")},h.prototype.getForwardRayToRef=function(b,T,D,w){throw E.a.WarnImport("Ray")},h.prototype.dispose=function(b,T){for(T===void 0&&(T=!1),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;){var D=this._rigCameras.pop();D&&D.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==h.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var w=this._postProcesses.length;--w>=0;){var N=this._postProcesses[w];N&&N.dispose(this)}for(w=this.customRenderTargets.length;--w>=0;)this.customRenderTargets[w].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),l.prototype.dispose.call(this,b,T)},Object.defineProperty(h.prototype,"isLeftCamera",{get:function(){return this._isLeftCamera},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"isRightCamera",{get:function(){return this._isRightCamera},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!1,configurable:!0}),h.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},h.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},h.prototype.setCameraRigMode=function(b,T){if(this.cameraRigMode!==b){for(;this._rigCameras.length>0;){var D=this._rigCameras.pop();D&&D.dispose()}if(this.cameraRigMode=b,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=T.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=u.b.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==h.RIG_MODE_NONE){var w=this.createRigCamera(this.name+"_L",0);w&&(w._isLeftCamera=!0);var N=this.createRigCamera(this.name+"_R",1);N&&(N._isRightCamera=!0),w&&N&&(this._rigCameras.push(w),this._rigCameras.push(N))}switch(this.cameraRigMode){case h.RIG_MODE_STEREOSCOPIC_ANAGLYPH:h._setStereoscopicAnaglyphRigMode(this);break;case h.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case h.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case h.RIG_MODE_STEREOSCOPIC_OVERUNDER:case h.RIG_MODE_STEREOSCOPIC_INTERLACED:h._setStereoscopicRigMode(this);break;case h.RIG_MODE_VR:h._setVRRigMode(this,T);break;case h.RIG_MODE_WEBVR:h._setWebVRRigMode(this,T)}this._cascadePostProcessesToRigCams(),this.update()}},h._setStereoscopicRigMode=function(b){throw"Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode"},h._setStereoscopicAnaglyphRigMode=function(b){throw"Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode"},h._setVRRigMode=function(b,T){throw"Import Cameras/RigModes/vrRigMode before using VR rig mode"},h._setWebVRRigMode=function(b,T){throw"Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode"},h.prototype._getVRProjectionMatrix=function(){return R.a.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},h.prototype._updateCameraRotationMatrix=function(){},h.prototype._updateWebVRCameraRotationMatrix=function(){},h.prototype._getWebVRProjectionMatrix=function(){return R.a.Identity()},h.prototype._getWebVRViewMatrix=function(){return R.a.Identity()},h.prototype.setCameraRigParameter=function(b,T){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[b]=T,b==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=u.b.ToRadians(T/.0637))},h.prototype.createRigCamera=function(b,T){return null},h.prototype._updateRigCameras=function(){for(var b=0;b=1)&&(this.needAlphaBlending()||g.visibility<1||g.hasVertexAlpha)},S.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest},S.prototype._shouldTurnAlphaTestOn=function(g){return!this.needAlphaBlendingForMesh(g)&&this.needAlphaTesting()},S.prototype.getAlphaTestTexture=function(){return null},S.prototype.markDirty=function(){for(var g=0,l=this.getScene().meshes;g1&&be.renderbufferStorageMultisample?be.renderbufferStorageMultisample(be.RENDERBUFFER,he,me,X,q):be.renderbufferStorage(be.RENDERBUFFER,ge,X,q),be.framebufferRenderbuffer(be.FRAMEBUFFER,_e,be.RENDERBUFFER,Ce),be.bindRenderbuffer(be.RENDERBUFFER,null),Ce},this._boundUniforms={};var te=null;if(I){if(W=W||{},T.a.SetMatrixPrecision(!!W.useHighPrecisionMatrix),I.getContext){if(te=I,this._renderingCanvas=te,V!=null&&(W.antialias=V),W.deterministicLockstep===void 0&&(W.deterministicLockstep=!1),W.lockstepMaxSteps===void 0&&(W.lockstepMaxSteps=4),W.timeStep===void 0&&(W.timeStep=1/60),W.preserveDrawingBuffer===void 0&&(W.preserveDrawingBuffer=!1),W.audioEngine===void 0&&(W.audioEngine=!0),W.stencil===void 0&&(W.stencil=!0),W.premultipliedAlpha===!1&&(this.premultipliedAlpha=!1),W.xrCompatible===void 0&&(W.xrCompatible=!0),this._doNotHandleContextLost=!!W.doNotHandleContextLost,navigator&&navigator.userAgent){var de=navigator.userAgent;this.hostInformation.isMobile=de.indexOf("Mobile")!==-1;for(var pe=0,ae=N.ExceptionList;pe0&&parseInt(Q[Q.length-1])>=G)continue}for(var oe=0,re=$;oe1?this._shaderProcessor=new g.a:this._shaderProcessor=new S,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._creationOptions=W,console.log("Babylon.js v"+N.Version+" - "+this.description)}}return Object.defineProperty(N,"NpmPackage",{get:function(){return"babylonjs@4.2.2"},enumerable:!1,configurable:!0}),Object.defineProperty(N,"Version",{get:function(){return"4.2.2"},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"description",{get:function(){var I="WebGL"+this.webGLVersion;return this._caps.parallelShaderCompile&&(I+=" - Parallel shader compilation"),I},enumerable:!1,configurable:!0}),Object.defineProperty(N,"ShadersRepository",{get:function(){return _.a.ShadersRepository},set:function(I){_.a.ShadersRepository=I},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"supportsUniformBuffers",{get:function(){return this.webGLVersion>1&&!this.disableUniformBuffers},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"_shouldUseHighPrecisionShader",{get:function(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(I){this._doNotHandleContextLost=I},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"framebufferDimensionsObject",{set:function(I){this._framebufferDimensionsObject=I},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,m.a.TEXTUREFORMAT_RGBA,!1,!1,m.a.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,m.a.TEXTUREFORMAT_RGBA,!1,!1,m.a.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"emptyTexture2DArray",{get:function(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,m.a.TEXTUREFORMAT_RGBA,!1,!1,m.a.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture2DArray},enumerable:!1,configurable:!0}),Object.defineProperty(N.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var I=new Uint8Array(4),V=[I,I,I,I,I,I];this._emptyCubeTexture=this.createRawCubeTexture(V,1,m.a.TEXTUREFORMAT_RGBA,m.a.TEXTURETYPE_UNSIGNED_INT,!1,!1,m.a.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!1,configurable:!0}),N.prototype._rebuildInternalTextures=function(){for(var I=0,V=this._internalTexturesCache.slice();I1?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"),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"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_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")),blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1},this._glVersion=this._gl.getParameter(this._gl.VERSION);var I=this._gl.getExtension("WEBGL_debug_renderer_info");if(I!=null&&(this._glRenderer=this._gl.getParameter(I.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(I.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor="Unknown vendor"),this._glRenderer||(this._glRenderer="Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),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._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._gl.getParameter(this._gl.MAX_SAMPLES);else{var V=this._gl.getExtension("WEBGL_draw_buffers");if(V!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=V.drawBuffersWEBGL.bind(V),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var W=0;W<16;W++)this._gl["COLOR_ATTACHMENT"+W+"_WEBGL"]=V["COLOR_ATTACHMENT"+W+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var j=this._gl.getExtension("WEBGL_depth_texture");j!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=j.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var ne=this._gl.getExtension("OES_vertex_array_object");ne!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=ne.createVertexArrayOES.bind(ne),this._gl.bindVertexArray=ne.bindVertexArrayOES.bind(ne),this._gl.deleteVertexArray=ne.deleteVertexArrayOES.bind(ne))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var te=this._gl.getExtension("ANGLE_instanced_arrays");te!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=te.drawArraysInstancedANGLE.bind(te),this._gl.drawElementsInstanced=te.drawElementsInstancedANGLE.bind(te),this._gl.vertexAttribDivisor=te.vertexAttribDivisorANGLE.bind(te)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){var de=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),pe=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);de&&pe&&(this._caps.highPrecisionShaderSupported=de.precision!==0&&pe.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{var ae=this._gl.getExtension("EXT_blend_minmax");ae!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=ae.MAX_EXT,this._gl.MIN=ae.MIN_EXT)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var ee=0;ee=0&&this._activeRenderLoops.splice(V,1)}else this._activeRenderLoops=[]},N.prototype._renderLoop=function(){if(!this._contextWasLost){var I=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(I=!1),I){this.beginFrame();for(var V=0;V0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1},N.prototype.getRenderingCanvas=function(){return this._renderingCanvas},N.prototype.getHostWindow=function(){return A.a.IsWindowObjectExist()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null},N.prototype.getRenderWidth=function(I){return I===void 0&&(I=!1),!I&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth},N.prototype.getRenderHeight=function(I){return I===void 0&&(I=!1),!I&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight},N.prototype._queueNewFrame=function(I,V){return N.QueueNewFrame(I,V)},N.prototype.runRenderLoop=function(I){this._activeRenderLoops.indexOf(I)===-1&&(this._activeRenderLoops.push(I),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))},N.prototype.clear=function(I,V,W,j){j===void 0&&(j=!1),this.applyStates();var ne=0;V&&I&&(this._gl.clearColor(I.r,I.g,I.b,I.a!==void 0?I.a:1),ne|=this._gl.COLOR_BUFFER_BIT),W&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GREATER,this._gl.clearDepth(0)):this._gl.clearDepth(1),ne|=this._gl.DEPTH_BUFFER_BIT),j&&(this._gl.clearStencil(0),ne|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(ne)},N.prototype._viewport=function(I,V,W,j){I===this._viewportCached.x&&V===this._viewportCached.y&&W===this._viewportCached.z&&j===this._viewportCached.w||(this._viewportCached.x=I,this._viewportCached.y=V,this._viewportCached.z=W,this._viewportCached.w=j,this._gl.viewport(I,V,W,j))},N.prototype.setViewport=function(I,V,W){var j=V||this.getRenderWidth(),ne=W||this.getRenderHeight(),te=I.x||0,de=I.y||0;this._cachedViewport=I,this._viewport(te*j,de*ne,j*I.width,ne*I.height)},N.prototype.beginFrame=function(){},N.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer()},N.prototype.resize=function(){var I,V;A.a.IsWindowObjectExist()?(I=this._renderingCanvas?this._renderingCanvas.clientWidth||this._renderingCanvas.width:window.innerWidth,V=this._renderingCanvas?this._renderingCanvas.clientHeight||this._renderingCanvas.height:window.innerHeight):(I=this._renderingCanvas?this._renderingCanvas.width:100,V=this._renderingCanvas?this._renderingCanvas.height:100),this.setSize(I/this._hardwareScalingLevel,V/this._hardwareScalingLevel)},N.prototype.setSize=function(I,V){return!!this._renderingCanvas&&(I|=0,V|=0,(this._renderingCanvas.width!==I||this._renderingCanvas.height!==V)&&(this._renderingCanvas.width=I,this._renderingCanvas.height=V,!0))},N.prototype.bindFramebuffer=function(I,V,W,j,ne,te,de){V===void 0&&(V=0),te===void 0&&(te=0),de===void 0&&(de=0),this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=I,this._bindUnboundFramebuffer(I._MSAAFramebuffer?I._MSAAFramebuffer:I._framebuffer);var pe=this._gl;I.is2DArray?pe.framebufferTextureLayer(pe.FRAMEBUFFER,pe.COLOR_ATTACHMENT0,I._webGLTexture,te,de):I.isCube&&pe.framebufferTexture2D(pe.FRAMEBUFFER,pe.COLOR_ATTACHMENT0,pe.TEXTURE_CUBE_MAP_POSITIVE_X+V,I._webGLTexture,te);var ae=I._depthStencilTexture;if(ae){var ee=ae._generateStencilBuffer?pe.DEPTH_STENCIL_ATTACHMENT:pe.DEPTH_ATTACHMENT;I.is2DArray?pe.framebufferTextureLayer(pe.FRAMEBUFFER,ee,ae._webGLTexture,te,de):I.isCube?pe.framebufferTexture2D(pe.FRAMEBUFFER,ee,pe.TEXTURE_CUBE_MAP_POSITIVE_X+V,ae._webGLTexture,te):pe.framebufferTexture2D(pe.FRAMEBUFFER,ee,pe.TEXTURE_2D,ae._webGLTexture,te)}this._cachedViewport&&!ne?this.setViewport(this._cachedViewport,W,j):(W||(W=I.width,te&&(W/=Math.pow(2,te))),j||(j=I.height,te&&(j/=Math.pow(2,te))),this._viewport(0,0,W,j)),this.wipeCaches()},N.prototype._bindUnboundFramebuffer=function(I){this._currentFramebuffer!==I&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,I),this._currentFramebuffer=I)},N.prototype.unBindFramebuffer=function(I,V,W){V===void 0&&(V=!1),this._currentRenderTarget=null;var j=this._gl;if(I._MSAAFramebuffer){if(I._textureArray)return void this.unBindMultiColorAttachmentFramebuffer(I._textureArray,V,W);j.bindFramebuffer(j.READ_FRAMEBUFFER,I._MSAAFramebuffer),j.bindFramebuffer(j.DRAW_FRAMEBUFFER,I._framebuffer),j.blitFramebuffer(0,0,I.width,I.height,0,0,I.width,I.height,j.COLOR_BUFFER_BIT,j.NEAREST)}!I.generateMipMaps||V||I.isCube||(this._bindTextureDirectly(j.TEXTURE_2D,I,!0),j.generateMipmap(j.TEXTURE_2D),this._bindTextureDirectly(j.TEXTURE_2D,null)),W&&(I._MSAAFramebuffer&&this._bindUnboundFramebuffer(I._framebuffer),W()),this._bindUnboundFramebuffer(null)},N.prototype.flushFramebuffer=function(){this._gl.flush()},N.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()},N.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},N.prototype.createVertexBuffer=function(I){return this._createVertexBuffer(I,this._gl.STATIC_DRAW)},N.prototype._createVertexBuffer=function(I,V){var W=this._gl.createBuffer();if(!W)throw new Error("Unable to create vertex buffer");var j=new l.a(W);return this.bindArrayBuffer(j),I instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(I),this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,I,this._gl.STATIC_DRAW),this._resetVertexBufferBinding(),j.references=1,j},N.prototype.createDynamicVertexBuffer=function(I){return this._createVertexBuffer(I,this._gl.DYNAMIC_DRAW)},N.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},N.prototype.createIndexBuffer=function(I,V){var W=this._gl.createBuffer(),j=new l.a(W);if(!W)throw new Error("Unable to create index buffer");this.bindIndexBuffer(j);var ne=this._normalizeIndexData(I);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,ne,V?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),j.references=1,j.is32Bits=ne.BYTES_PER_ELEMENT===4,j},N.prototype._normalizeIndexData=function(I){if(I instanceof Uint16Array)return I;if(this._caps.uintIndices){if(I instanceof Uint32Array)return I;for(var V=0;V=65535)return new Uint32Array(I);return new Uint16Array(I)}return new Uint16Array(I)},N.prototype.bindArrayBuffer=function(I){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(I,this._gl.ARRAY_BUFFER)},N.prototype.bindUniformBlock=function(I,V,W){var j=I.program,ne=this._gl.getUniformBlockIndex(j,V);this._gl.uniformBlockBinding(j,ne,W)},N.prototype.bindIndexBuffer=function(I){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(I,this._gl.ELEMENT_ARRAY_BUFFER)},N.prototype.bindBuffer=function(I,V){(this._vaoRecordInProgress||this._currentBoundBuffer[V]!==I)&&(this._gl.bindBuffer(V,I?I.underlyingResource:null),this._currentBoundBuffer[V]=I)},N.prototype.updateArrayBuffer=function(I){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,I)},N.prototype._vertexAttribPointer=function(I,V,W,j,ne,te,de){var pe=this._currentBufferPointers[V];if(pe){var ae=!1;pe.active?(pe.buffer!==I&&(pe.buffer=I,ae=!0),pe.size!==W&&(pe.size=W,ae=!0),pe.type!==j&&(pe.type=j,ae=!0),pe.normalized!==ne&&(pe.normalized=ne,ae=!0),pe.stride!==te&&(pe.stride=te,ae=!0),pe.offset!==de&&(pe.offset=de,ae=!0)):(ae=!0,pe.active=!0,pe.index=V,pe.size=W,pe.type=j,pe.normalized=ne,pe.stride=te,pe.offset=de,pe.buffer=I),(ae||this._vaoRecordInProgress)&&(this.bindArrayBuffer(I),this._gl.vertexAttribPointer(V,W,j,ne,te,de))}},N.prototype._bindIndexBufferWithCache=function(I){I!=null&&this._cachedIndexBuffer!==I&&(this._cachedIndexBuffer=I,this.bindIndexBuffer(I),this._uintIndicesCurrentlySet=I.is32Bits)},N.prototype._bindVertexBuffersAttributes=function(I,V){var W=V.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var j=0;j=0){var te=I[W[j]];if(!te)continue;this._gl.enableVertexAttribArray(ne),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[ne]=!0);var de=te.getBuffer();de&&(this._vertexAttribPointer(de,ne,te.getSize(),te.type,te.normalized,te.byteStride,te.byteOffset),te.getIsInstanced()&&(this._gl.vertexAttribDivisor(ne,te.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(ne),this._currentInstanceBuffers.push(de))))}}},N.prototype.recordVertexArrayObject=function(I,V,W){var j=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(j),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(I,W),this.bindIndexBuffer(V),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),j},N.prototype.bindVertexArrayObject=function(I,V){this._cachedVertexArrayObject!==I&&(this._cachedVertexArrayObject=I,this._gl.bindVertexArray(I),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=V!=null&&V.is32Bits,this._mustWipeVertexAttributes=!0)},N.prototype.bindBuffersDirectly=function(I,V,W,j,ne){if(this._cachedVertexBuffers!==I||this._cachedEffectForVertexBuffers!==ne){this._cachedVertexBuffers=I,this._cachedEffectForVertexBuffers=ne;var te=ne.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var de=0,pe=0;pe=0&&(this._gl.enableVertexAttribArray(ae),this._vertexAttribArraysEnabled[ae]=!0,this._vertexAttribPointer(I,ae,W[pe],this._gl.FLOAT,!1,j,de)),de+=4*W[pe]}}this._bindIndexBufferWithCache(V)},N.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},N.prototype.bindBuffers=function(I,V,W){this._cachedVertexBuffers===I&&this._cachedEffectForVertexBuffers===W||(this._cachedVertexBuffers=I,this._cachedEffectForVertexBuffers=W,this._bindVertexBuffersAttributes(I,W)),this._bindIndexBufferWithCache(V)},N.prototype.unbindInstanceAttributes=function(){for(var I,V=0,W=this._currentInstanceLocations.length;V1?`#version 300 es -#define WEBGL2 -`:"",pe=this._compileShader(V,"vertex",j,de),ae=this._compileShader(W,"fragment",j,de);return this._createShaderProgram(I,pe,ae,ne,te)},N.prototype.createPipelineContext=function(){var I=new h.a;return I.engine=this,this._caps.parallelShaderCompile&&(I.isParallelCompiled=!0),I},N.prototype._createShaderProgram=function(I,V,W,j,ne){var te=j.createProgram();if(I.program=te,!te)throw new Error("Unable to create program");return j.attachShader(te,V),j.attachShader(te,W),j.linkProgram(te),I.context=j,I.vertexShader=V,I.fragmentShader=W,I.isParallelCompiled||this._finalizePipelineContext(I),te},N.prototype._finalizePipelineContext=function(I){var V=I.context,W=I.vertexShader,j=I.fragmentShader,ne=I.program;if(!V.getProgramParameter(ne,V.LINK_STATUS)){var te,de;if(!this._gl.getShaderParameter(W,this._gl.COMPILE_STATUS)&&(te=this._gl.getShaderInfoLog(W)))throw I.vertexCompilationError=te,new Error("VERTEX SHADER "+te);if(!this._gl.getShaderParameter(j,this._gl.COMPILE_STATUS)&&(te=this._gl.getShaderInfoLog(j)))throw I.fragmentCompilationError=te,new Error("FRAGMENT SHADER "+te);if(de=V.getProgramInfoLog(ne))throw I.programLinkError=de,new Error(de)}if(this.validateShaderPrograms&&(V.validateProgram(ne),!V.getProgramParameter(ne,V.VALIDATE_STATUS)&&(de=V.getProgramInfoLog(ne))))throw I.programValidationError=de,new Error(de);V.deleteShader(W),V.deleteShader(j),I.vertexShader=void 0,I.fragmentShader=void 0,I.onCompiled&&(I.onCompiled(),I.onCompiled=void 0)},N.prototype._preparePipelineContext=function(I,V,W,j,ne,te,de){var pe=I;pe.program=j?this.createRawShaderProgram(pe,V,W,void 0,de):this.createShaderProgram(pe,V,W,te,void 0,de),pe.program.__SPECTOR_rebuildProgram=ne},N.prototype._isRenderingStateCompiled=function(I){var V=I;return!!this._gl.getProgramParameter(V.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(V),!0)},N.prototype._executeWhenRenderingStateIsCompiled=function(I,V){var W=I;if(W.isParallelCompiled){var j=W.onCompiled;W.onCompiled=j?function(){j(),V()}:V}else V()},N.prototype.getUniforms=function(I,V){for(var W=new Array,j=I,ne=0;ne-1?I.substring(H).toLowerCase():""),X=null;Z.indexOf("?")>-1&&(Z=Z.split("?")[0]);for(var q=0,he=N._TextureLoaders;qze||ye.height>ze||!G._supportsHardwareTextureRescaling)return G._prepareWorkingCanvas(),!(!G._workingCanvas||!G._workingContext)&&(G._workingCanvas.width=Be,G._workingCanvas.height=Ge,G._workingContext.drawImage(ye,0,0,ye.width,ye.height,0,0,Be,Ge),He.texImage2D(He.TEXTURE_2D,0,Ze,Ze,He.UNSIGNED_BYTE,G._workingCanvas),Y.width=Be,Y.height=Ge,!1);var it=new c.a(G,c.b.Temp);return G._bindTextureDirectly(He.TEXTURE_2D,it,!0),He.texImage2D(He.TEXTURE_2D,0,Ze,Ze,He.UNSIGNED_BYTE,ye),G._rescaleTexture(it,Y,j,Ze,function(){G._releaseTexture(it),G._bindTextureDirectly(He.TEXTURE_2D,Y,!0),Xe()}),!0},ne)};!Q||re?pe&&(pe.decoding||pe.close)?Ce(pe):N._FileToolsLoadImage(I,Ce,_e,j?j.offlineProvider:null,$):typeof pe=="string"||pe instanceof ArrayBuffer||ArrayBuffer.isView(pe)||pe instanceof Blob?N._FileToolsLoadImage(pe,Ce,_e,j?j.offlineProvider:null,$):pe&&Ce(pe)}return Y},N._FileToolsLoadImage=function(I,V,W,j,ne){throw x.a.WarnImport("FileTools")},N.prototype._rescaleTexture=function(I,V,W,j,ne){},N.prototype.createRawTexture=function(I,V,W,j,ne,te,de,pe,ae){throw ae===void 0&&(ae=m.a.TEXTURETYPE_UNSIGNED_INT),x.a.WarnImport("Engine.RawTexture")},N.prototype.createRawCubeTexture=function(I,V,W,j,ne,te,de,pe){throw x.a.WarnImport("Engine.RawTexture")},N.prototype.createRawTexture3D=function(I,V,W,j,ne,te,de,pe,ae,ee){throw ee===void 0&&(ee=m.a.TEXTURETYPE_UNSIGNED_INT),x.a.WarnImport("Engine.RawTexture")},N.prototype.createRawTexture2DArray=function(I,V,W,j,ne,te,de,pe,ae,ee){throw ee===void 0&&(ee=m.a.TEXTURETYPE_UNSIGNED_INT),x.a.WarnImport("Engine.RawTexture")},N.prototype._unpackFlipY=function(I){this._unpackFlipYCached!==I&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,I?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=I))},N.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},N.prototype._getTextureTarget=function(I){return I.isCube?this._gl.TEXTURE_CUBE_MAP:I.is3D?this._gl.TEXTURE_3D:I.is2DArray||I.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D},N.prototype.updateTextureSamplingMode=function(I,V,W){W===void 0&&(W=!1);var j=this._getTextureTarget(V),ne=this._getSamplingParameters(I,V.generateMipMaps||W);this._setTextureParameterInteger(j,this._gl.TEXTURE_MAG_FILTER,ne.mag,V),this._setTextureParameterInteger(j,this._gl.TEXTURE_MIN_FILTER,ne.min),W&&(V.generateMipMaps=!0,this._gl.generateMipmap(j)),this._bindTextureDirectly(j,null),V.samplingMode=I},N.prototype.updateTextureWrappingMode=function(I,V,W,j){W===void 0&&(W=null),j===void 0&&(j=null);var ne=this._getTextureTarget(I);V!==null&&(this._setTextureParameterInteger(ne,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(V),I),I._cachedWrapU=V),W!==null&&(this._setTextureParameterInteger(ne,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(W),I),I._cachedWrapV=W),(I.is2DArray||I.is3D)&&j!==null&&(this._setTextureParameterInteger(ne,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(j),I),I._cachedWrapR=j),this._bindTextureDirectly(ne,null)},N.prototype._setupDepthStencilTexture=function(I,V,W,j,ne){var te=V.width||V,de=V.height||V,pe=V.layers||0;I.baseWidth=te,I.baseHeight=de,I.width=te,I.height=de,I.is2DArray=pe>0,I.depth=pe,I.isReady=!0,I.samples=1,I.generateMipMaps=!1,I._generateDepthBuffer=!0,I._generateStencilBuffer=W,I.samplingMode=j?m.a.TEXTURE_BILINEAR_SAMPLINGMODE:m.a.TEXTURE_NEAREST_SAMPLINGMODE,I.type=m.a.TEXTURETYPE_UNSIGNED_INT,I._comparisonFunction=ne;var ae=this._gl,ee=this._getTextureTarget(I),K=this._getSamplingParameters(I.samplingMode,!1);ae.texParameteri(ee,ae.TEXTURE_MAG_FILTER,K.mag),ae.texParameteri(ee,ae.TEXTURE_MIN_FILTER,K.min),ae.texParameteri(ee,ae.TEXTURE_WRAP_S,ae.CLAMP_TO_EDGE),ae.texParameteri(ee,ae.TEXTURE_WRAP_T,ae.CLAMP_TO_EDGE),ne===0?(ae.texParameteri(ee,ae.TEXTURE_COMPARE_FUNC,m.a.LEQUAL),ae.texParameteri(ee,ae.TEXTURE_COMPARE_MODE,ae.NONE)):(ae.texParameteri(ee,ae.TEXTURE_COMPARE_FUNC,ne),ae.texParameteri(ee,ae.TEXTURE_COMPARE_MODE,ae.COMPARE_REF_TO_TEXTURE))},N.prototype._uploadCompressedDataToTextureDirectly=function(I,V,W,j,ne,te,de){te===void 0&&(te=0),de===void 0&&(de=0);var pe=this._gl,ae=pe.TEXTURE_2D;I.isCube&&(ae=pe.TEXTURE_CUBE_MAP_POSITIVE_X+te),this._gl.compressedTexImage2D(ae,de,V,W,j,0,ne)},N.prototype._uploadDataToTextureDirectly=function(I,V,W,j,ne,te){W===void 0&&(W=0),j===void 0&&(j=0),te===void 0&&(te=!1);var de=this._gl,pe=this._getWebGLTextureType(I.type),ae=this._getInternalFormat(I.format),ee=ne===void 0?this._getRGBABufferInternalSizedFormat(I.type,I.format):this._getInternalFormat(ne);this._unpackFlipY(I.invertY);var K=de.TEXTURE_2D;I.isCube&&(K=de.TEXTURE_CUBE_MAP_POSITIVE_X+W);var $=Math.round(Math.log(I.width)*Math.LOG2E),L=Math.round(Math.log(I.height)*Math.LOG2E),G=te?I.width:Math.pow(2,Math.max($-j,0)),Q=te?I.height:Math.pow(2,Math.max(L-j,0));de.texImage2D(K,j,ee,G,Q,0,ae,pe,V)},N.prototype.updateTextureData=function(I,V,W,j,ne,te,de,pe){de===void 0&&(de=0),pe===void 0&&(pe=0);var ae=this._gl,ee=this._getWebGLTextureType(I.type),K=this._getInternalFormat(I.format);this._unpackFlipY(I.invertY);var $=ae.TEXTURE_2D;I.isCube&&($=ae.TEXTURE_CUBE_MAP_POSITIVE_X+de),ae.texSubImage2D($,pe,W,j,ne,te,K,ee,V)},N.prototype._uploadArrayBufferViewToTexture=function(I,V,W,j){W===void 0&&(W=0),j===void 0&&(j=0);var ne=this._gl,te=I.isCube?ne.TEXTURE_CUBE_MAP:ne.TEXTURE_2D;this._bindTextureDirectly(te,I,!0),this._uploadDataToTextureDirectly(I,V,W,j),this._bindTextureDirectly(te,null,!0)},N.prototype._prepareWebGLTextureContinuation=function(I,V,W,j,ne){var te=this._gl;if(te){var de=this._getSamplingParameters(ne,!W);te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MAG_FILTER,de.mag),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MIN_FILTER,de.min),W||j||te.generateMipmap(te.TEXTURE_2D),this._bindTextureDirectly(te.TEXTURE_2D,null),V&&V._removePendingData(I),I.onLoadedObservable.notifyObservers(I),I.onLoadedObservable.clear()}},N.prototype._prepareWebGLTexture=function(I,V,W,j,ne,te,de,pe,ae){var ee=this;ae===void 0&&(ae=m.a.TEXTURE_TRILINEAR_SAMPLINGMODE);var K=this.getCaps().maxTextureSize,$=Math.min(K,this.needPOTTextures?N.GetExponentOfTwo(W,K):W),L=Math.min(K,this.needPOTTextures?N.GetExponentOfTwo(j,K):j),G=this._gl;G&&(I._webGLTexture?(this._bindTextureDirectly(G.TEXTURE_2D,I,!0),this._unpackFlipY(ne===void 0||!!ne),I.baseWidth=W,I.baseHeight=j,I.width=$,I.height=L,I.isReady=!0,pe($,L,function(){ee._prepareWebGLTextureContinuation(I,V,te,de,ae)})||this._prepareWebGLTextureContinuation(I,V,te,de,ae)):V&&V._removePendingData(I))},N.prototype._setupFramebufferDepthAttachments=function(I,V,W,j,ne){ne===void 0&&(ne=1);var te=this._gl;if(I&&V)return this._getDepthStencilBuffer(W,j,ne,te.DEPTH_STENCIL,te.DEPTH24_STENCIL8,te.DEPTH_STENCIL_ATTACHMENT);if(V){var de=te.DEPTH_COMPONENT16;return this._webGLVersion>1&&(de=te.DEPTH_COMPONENT32F),this._getDepthStencilBuffer(W,j,ne,de,de,te.DEPTH_ATTACHMENT)}return I?this._getDepthStencilBuffer(W,j,ne,te.STENCIL_INDEX8,te.STENCIL_INDEX8,te.STENCIL_ATTACHMENT):null},N.prototype._releaseFramebufferObjects=function(I){var V=this._gl;I._framebuffer&&(V.deleteFramebuffer(I._framebuffer),I._framebuffer=null),I._depthStencilBuffer&&(V.deleteRenderbuffer(I._depthStencilBuffer),I._depthStencilBuffer=null),I._MSAAFramebuffer&&(V.deleteFramebuffer(I._MSAAFramebuffer),I._MSAAFramebuffer=null),I._MSAARenderBuffer&&(V.deleteRenderbuffer(I._MSAARenderBuffer),I._MSAARenderBuffer=null)},N.prototype._releaseTexture=function(I){this._releaseFramebufferObjects(I),this._deleteTexture(I._webGLTexture),this.unbindAllTextures();var V=this._internalTexturesCache.indexOf(I);V!==-1&&this._internalTexturesCache.splice(V,1),I._lodTextureHigh&&I._lodTextureHigh.dispose(),I._lodTextureMid&&I._lodTextureMid.dispose(),I._lodTextureLow&&I._lodTextureLow.dispose(),I._irradianceTexture&&I._irradianceTexture.dispose()},N.prototype._deleteTexture=function(I){this._gl.deleteTexture(I)},N.prototype._setProgram=function(I){this._currentProgram!==I&&(this._gl.useProgram(I),this._currentProgram=I)},N.prototype.bindSamplers=function(I){var V=I.getPipelineContext();this._setProgram(V.program);for(var W=I.getSamplers(),j=0;j-1;return W&&te&&(this._activeChannel=V._associatedChannel),this._boundTexturesCache[this._activeChannel]!==V||j?(this._activateCurrentTexture(),V&&V.isMultiview?this._gl.bindTexture(I,V?V._colorTextureArray:null):this._gl.bindTexture(I,V?V._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=V,V&&(V._associatedChannel=this._activeChannel)):W&&(ne=!0,this._activateCurrentTexture()),te&&!W&&this._bindSamplerUniformToChannel(V._associatedChannel,this._activeChannel),ne},N.prototype._bindTexture=function(I,V){if(I!==void 0){V&&(V._associatedChannel=I),this._activeChannel=I;var W=V?this._getTextureTarget(V):this._gl.TEXTURE_2D;this._bindTextureDirectly(W,V)}},N.prototype.unbindAllTextures=function(){for(var I=0;I1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))},N.prototype.setTexture=function(I,V,W){I!==void 0&&(V&&(this._boundUniforms[I]=V),this._setTexture(I,W))},N.prototype._bindSamplerUniformToChannel=function(I,V){var W=this._boundUniforms[I];W&&W._currentState!==V&&(this._gl.uniform1i(W,V),W._currentState=V)},N.prototype._getTextureWrapMode=function(I){switch(I){case m.a.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case m.a.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case m.a.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},N.prototype._setTexture=function(I,V,W,j){if(W===void 0&&(W=!1),j===void 0&&(j=!1),!V)return this._boundTexturesCache[I]!=null&&(this._activeChannel=I,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(V.video)this._activeChannel=I,V.update();else if(V.delayLoadState===m.a.DELAYLOADSTATE_NOTLOADED)return V.delayLoad(),!1;var ne;ne=j?V.depthStencilTexture:V.isReady()?V.getInternalTexture():V.isCube?this.emptyCubeTexture:V.is3D?this.emptyTexture3D:V.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!W&&ne&&(ne._associatedChannel=I);var te=!0;this._boundTexturesCache[I]===ne&&(W||this._bindSamplerUniformToChannel(ne._associatedChannel,I),te=!1),this._activeChannel=I;var de=this._getTextureTarget(ne);if(te&&this._bindTextureDirectly(de,ne,W),ne&&!ne.isMultiview){if(ne.isCube&&ne._cachedCoordinatesMode!==V.coordinatesMode){ne._cachedCoordinatesMode=V.coordinatesMode;var pe=V.coordinatesMode!==m.a.TEXTURE_CUBIC_MODE&&V.coordinatesMode!==m.a.TEXTURE_SKYBOX_MODE?m.a.TEXTURE_WRAP_ADDRESSMODE:m.a.TEXTURE_CLAMP_ADDRESSMODE;V.wrapU=pe,V.wrapV=pe}ne._cachedWrapU!==V.wrapU&&(ne._cachedWrapU=V.wrapU,this._setTextureParameterInteger(de,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(V.wrapU),ne)),ne._cachedWrapV!==V.wrapV&&(ne._cachedWrapV=V.wrapV,this._setTextureParameterInteger(de,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(V.wrapV),ne)),ne.is3D&&ne._cachedWrapR!==V.wrapR&&(ne._cachedWrapR=V.wrapR,this._setTextureParameterInteger(de,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(V.wrapR),ne)),this._setAnisotropicLevel(de,ne,V.anisotropicFilteringLevel)}return!0},N.prototype.setTextureArray=function(I,V,W){if(I!==void 0&&V){this._textureUnits&&this._textureUnits.length===W.length||(this._textureUnits=new Int32Array(W.length));for(var j=0;j=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[I]||this.disableAttributeByIndex(I)}},N.prototype.releaseEffects=function(){for(var I in this._compiledEffects){var V=this._compiledEffects[I].getPipelineContext();this._deletePipelineContext(V)}this._compiledEffects={}},N.prototype.dispose=function(){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(),this.unbindAllAttributes(),this._boundUniforms=[],A.a.IsWindowObjectExist()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,_.a.ResetCache();for(var I=0,V=this._activeRequests;I1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(m.a.TEXTURETYPE_FLOAT)},N.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(m.a.TEXTURETYPE_HALF_FLOAT)},N.prototype._canRenderToFramebuffer=function(I){for(var V=this._gl;V.getError()!==V.NO_ERROR;);var W=!0,j=V.createTexture();V.bindTexture(V.TEXTURE_2D,j),V.texImage2D(V.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(I),1,1,0,V.RGBA,this._getWebGLTextureType(I),null),V.texParameteri(V.TEXTURE_2D,V.TEXTURE_MIN_FILTER,V.NEAREST),V.texParameteri(V.TEXTURE_2D,V.TEXTURE_MAG_FILTER,V.NEAREST);var ne=V.createFramebuffer();V.bindFramebuffer(V.FRAMEBUFFER,ne),V.framebufferTexture2D(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_2D,j,0);var te=V.checkFramebufferStatus(V.FRAMEBUFFER);if((W=(W=W&&te===V.FRAMEBUFFER_COMPLETE)&&V.getError()===V.NO_ERROR)&&(V.clear(V.COLOR_BUFFER_BIT),W=W&&V.getError()===V.NO_ERROR),W){V.bindFramebuffer(V.FRAMEBUFFER,null);var de=V.RGBA,pe=V.UNSIGNED_BYTE,ae=new Uint8Array(4);V.readPixels(0,0,1,1,de,pe,ae),W=W&&V.getError()===V.NO_ERROR}for(V.deleteTexture(j),V.deleteFramebuffer(ne),V.bindFramebuffer(V.FRAMEBUFFER,null);!W&&V.getError()!==V.NO_ERROR;);return W},N.prototype._getWebGLTextureType=function(I){if(this._webGLVersion===1){switch(I){case m.a.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case m.a.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case m.a.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case m.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case m.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case m.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(I){case m.a.TEXTURETYPE_BYTE:return this._gl.BYTE;case m.a.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case m.a.TEXTURETYPE_SHORT:return this._gl.SHORT;case m.a.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case m.a.TEXTURETYPE_INT:return this._gl.INT;case m.a.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case m.a.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case m.a.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case m.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case m.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case m.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case m.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case m.a.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case m.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case m.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case m.a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE},N.prototype._getInternalFormat=function(I){var V=this._gl.RGBA;switch(I){case m.a.TEXTUREFORMAT_ALPHA:V=this._gl.ALPHA;break;case m.a.TEXTUREFORMAT_LUMINANCE:V=this._gl.LUMINANCE;break;case m.a.TEXTUREFORMAT_LUMINANCE_ALPHA:V=this._gl.LUMINANCE_ALPHA;break;case m.a.TEXTUREFORMAT_RED:V=this._gl.RED;break;case m.a.TEXTUREFORMAT_RG:V=this._gl.RG;break;case m.a.TEXTUREFORMAT_RGB:V=this._gl.RGB;break;case m.a.TEXTUREFORMAT_RGBA:V=this._gl.RGBA}if(this._webGLVersion>1)switch(I){case m.a.TEXTUREFORMAT_RED_INTEGER:V=this._gl.RED_INTEGER;break;case m.a.TEXTUREFORMAT_RG_INTEGER:V=this._gl.RG_INTEGER;break;case m.a.TEXTUREFORMAT_RGB_INTEGER:V=this._gl.RGB_INTEGER;break;case m.a.TEXTUREFORMAT_RGBA_INTEGER:V=this._gl.RGBA_INTEGER}return V},N.prototype._getRGBABufferInternalSizedFormat=function(I,V){if(this._webGLVersion===1){if(V!==void 0)switch(V){case m.a.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case m.a.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case m.a.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case m.a.TEXTUREFORMAT_RGB:return this._gl.RGB}return this._gl.RGBA}switch(I){case m.a.TEXTURETYPE_BYTE:switch(V){case m.a.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case m.a.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case m.a.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case m.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case m.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case m.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case m.a.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case m.a.TEXTURETYPE_UNSIGNED_BYTE:switch(V){case m.a.TEXTUREFORMAT_RED:return this._gl.R8;case m.a.TEXTUREFORMAT_RG:return this._gl.RG8;case m.a.TEXTUREFORMAT_RGB:return this._gl.RGB8;case m.a.TEXTUREFORMAT_RGBA:return this._gl.RGBA8;case m.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case m.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case m.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case m.a.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case m.a.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case m.a.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case m.a.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case m.a.TEXTURETYPE_SHORT:switch(V){case m.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case m.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case m.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case m.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case m.a.TEXTURETYPE_UNSIGNED_SHORT:switch(V){case m.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case m.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case m.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case m.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case m.a.TEXTURETYPE_INT:switch(V){case m.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case m.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case m.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case m.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case m.a.TEXTURETYPE_UNSIGNED_INTEGER:switch(V){case m.a.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case m.a.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case m.a.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case m.a.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case m.a.TEXTURETYPE_FLOAT:switch(V){case m.a.TEXTUREFORMAT_RED:return this._gl.R32F;case m.a.TEXTUREFORMAT_RG:return this._gl.RG32F;case m.a.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case m.a.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case m.a.TEXTURETYPE_HALF_FLOAT:switch(V){case m.a.TEXTUREFORMAT_RED:return this._gl.R16F;case m.a.TEXTUREFORMAT_RG:return this._gl.RG16F;case m.a.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case m.a.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case m.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case m.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case m.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case m.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case m.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case m.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(V){case m.a.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case m.a.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return this._gl.RGBA8},N.prototype._getRGBAMultiSampleBufferFormat=function(I){return I===m.a.TEXTURETYPE_FLOAT?this._gl.RGBA32F:I===m.a.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},N.prototype._loadFile=function(I,V,W,j,ne,te){var de=this,pe=N._FileToolsLoadFile(I,V,W,j,ne,te);return this._activeRequests.push(pe),pe.onCompleteObservable.add(function(ae){de._activeRequests.splice(de._activeRequests.indexOf(ae),1)}),pe},N._FileToolsLoadFile=function(I,V,W,j,ne,te){throw x.a.WarnImport("FileTools")},N.prototype.readPixels=function(I,V,W,j,ne){ne===void 0&&(ne=!0);var te=ne?4:3,de=ne?this._gl.RGBA:this._gl.RGB,pe=new Uint8Array(j*W*te);return this._gl.readPixels(I,V,W,j,de,this._gl.UNSIGNED_BYTE,pe),pe},Object.defineProperty(N,"IsSupported",{get:function(){return this.isSupported()},enumerable:!1,configurable:!0}),N.isSupported=function(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{var I=b.a.CreateCanvas(1,1),V=I.getContext("webgl")||I.getContext("experimental-webgl");this._IsSupported=V!=null&&!!window.WebGLRenderingContext}catch{this._IsSupported=!1}return this._IsSupported},Object.defineProperty(N,"HasMajorPerformanceCaveat",{get:function(){if(this._HasMajorPerformanceCaveat===null)try{var I=b.a.CreateCanvas(1,1),V=I.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||I.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!V}catch{this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat},enumerable:!1,configurable:!0}),N.CeilingPOT=function(I){return I--,I|=I>>1,I|=I>>2,I|=I>>4,I|=I>>8,I|=I>>16,++I},N.FloorPOT=function(I){return I|=I>>1,I|=I>>2,I|=I>>4,I|=I>>8,(I|=I>>16)-(I>>1)},N.NearestPOT=function(I){var V=N.CeilingPOT(I),W=N.FloorPOT(I);return V-I>I-W?W:V},N.GetExponentOfTwo=function(I,V,W){var j;switch(W===void 0&&(W=m.a.SCALEMODE_NEAREST),W){case m.a.SCALEMODE_FLOOR:j=N.FloorPOT(I);break;case m.a.SCALEMODE_NEAREST:j=N.NearestPOT(I);break;case m.a.SCALEMODE_CEILING:default:j=N.CeilingPOT(I)}return Math.min(j,V)},N.QueueNewFrame=function(I,V){return A.a.IsWindowObjectExist()?(V||(V=window),V.requestPostAnimationFrame?V.requestPostAnimationFrame(I):V.requestAnimationFrame?V.requestAnimationFrame(I):V.msRequestAnimationFrame?V.msRequestAnimationFrame(I):V.webkitRequestAnimationFrame?V.webkitRequestAnimationFrame(I):V.mozRequestAnimationFrame?V.mozRequestAnimationFrame(I):V.oRequestAnimationFrame?V.oRequestAnimationFrame(I):window.setTimeout(I,16)):typeof requestAnimationFrame<"u"?requestAnimationFrame(I):setTimeout(I,16)},N.prototype.getHostDocument=function(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:document},N.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"]}],N._TextureLoaders=[],N.CollisionsEpsilon=.001,N._IsSupported=null,N._HasMajorPerformanceCaveat=null,N}()},function(Ae,v,f){f.d(v,"b",function(){return B}),f.d(v,"a",function(){return R});var B,_=f(6),x=f(102),u=f(2),M=f(21);(function(C){C[C.Unknown=0]="Unknown",C[C.Url=1]="Url",C[C.Temp=2]="Temp",C[C.Raw=3]="Raw",C[C.Dynamic=4]="Dynamic",C[C.RenderTarget=5]="RenderTarget",C[C.MultiRenderTarget=6]="MultiRenderTarget",C[C.Cube=7]="Cube",C[C.CubeRaw=8]="CubeRaw",C[C.CubePrefiltered=9]="CubePrefiltered",C[C.Raw3D=10]="Raw3D",C[C.Raw2DArray=11]="Raw2DArray",C[C.Depth=12]="Depth",C[C.CubeRawRGBD=13]="CubeRawRGBD"})(B||(B={}));var R=function(){function C(m,c,E){E===void 0&&(E=!1),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.samplingMode=-1,this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new _.c,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=B.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._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._MSAARenderBuffer=null,this._attachments=null,this._textureArray=null,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._isDisabled=!1,this._compression=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._comparisonFunction=0,this._sphericalPolynomial=null,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._webGLTexture=null,this._references=1,this._gammaSpace=null,this._engine=m,this._source=c,E||(this._webGLTexture=m._createTexture())}return C.prototype.getEngine=function(){return this._engine},Object.defineProperty(C.prototype,"source",{get:function(){return this._source},enumerable:!1,configurable:!0}),C.prototype.incrementReferences=function(){this._references++},C.prototype.updateSize=function(m,c,E){E===void 0&&(E=1),this.width=m,this.height=c,this.depth=E,this.baseWidth=m,this.baseHeight=c,this.baseDepth=E,this._size=m*c*E},C.prototype._rebuild=function(){var m,c,E=this;switch(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedAnisotropicFilteringLevel=null,this.source){case B.Temp:return;case B.Url:return void(c=this._engine.createTexture((m=this._originalUrl)!==null&&m!==void 0?m:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,function(){c._swapAndDie(E),E.isReady=!0},null,this._buffer,void 0,this.format));case B.Raw:return(c=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case B.Raw3D:return(c=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case B.Raw2DArray:return(c=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case B.Dynamic:return(c=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this),void this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);case B.RenderTarget:var A=new x.a;if(A.generateDepthBuffer=this._generateDepthBuffer,A.generateMipMaps=this.generateMipMaps,A.generateStencilBuffer=this._generateStencilBuffer,A.samplingMode=this.samplingMode,A.type=this.type,this.isCube)c=this._engine.createRenderTargetCubeTexture(this.width,A);else{var S={width:this.width,height:this.height,layers:this.is2DArray?this.depth:void 0};c=this._engine.createRenderTargetTexture(S,A)}return c._swapAndDie(this),void(this.isReady=!0);case B.Depth:var g={bilinearFiltering:this.samplingMode!==u.a.TEXTURE_BILINEAR_SAMPLINGMODE,comparisonFunction:this._comparisonFunction,generateStencil:this._generateStencilBuffer,isCube:this.isCube},l={width:this.width,height:this.height,layers:this.is2DArray?this.depth:void 0};return(c=this._engine.createDepthStencilTexture(l,g))._swapAndDie(this),void(this.isReady=!0);case B.Cube:return void(c=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,function(){c._swapAndDie(E),E.isReady=!0},null,this.format,this._extension));case B.CubeRaw:return(c=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this),void(this.isReady=!0);case B.CubeRawRGBD:return c=this._engine.createRawCubeTexture(null,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),void C._UpdateRGBDAsync(c,this._bufferViewArrayArray,this._sphericalPolynomial,this._lodGenerationScale,this._lodGenerationOffset).then(function(){c._swapAndDie(E),E.isReady=!0});case B.CubePrefiltered:return void((c=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,function(h){h&&h._swapAndDie(E),E.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial)}},C.prototype._swapAndDie=function(m){m._webGLTexture=this._webGLTexture,m._isRGBD=this._isRGBD,this._framebuffer&&(m._framebuffer=this._framebuffer),this._depthStencilBuffer&&(m._depthStencilBuffer=this._depthStencilBuffer),m._depthStencilTexture=this._depthStencilTexture,this._lodTextureHigh&&(m._lodTextureHigh&&m._lodTextureHigh.dispose(),m._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(m._lodTextureMid&&m._lodTextureMid.dispose(),m._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(m._lodTextureLow&&m._lodTextureLow.dispose(),m._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(m._irradianceTexture&&m._irradianceTexture.dispose(),m._irradianceTexture=this._irradianceTexture);var c,E=this._engine.getLoadedTexturesCache();(c=E.indexOf(this))!==-1&&E.splice(c,1),(c=E.indexOf(m))===-1&&E.push(m)},C.prototype.dispose=function(){this._webGLTexture&&(this._references--,this._references===0&&(this._engine._releaseTexture(this),this._webGLTexture=null))},C._UpdateRGBDAsync=function(m,c,E,A,S){throw M.a.WarnImport("environmentTextureTools")},C}()},function(Ae,v,f){f.d(v,"b",function(){return B}),f.d(v,"c",function(){return _}),f.d(v,"a",function(){return x});var B=1/2.2,_=2.2,x=.001},function(Ae,v,f){f.d(v,"a",function(){return C});var B=f(1),_=f(0),x=f(3),u=f(6),M=f(22),R=f(21),C=function(){function m(c,E){E===void 0&&(E=null),this.state="",this.metadata=null,this.reservedDataStore=null,this._doNotSerialize=!1,this._isDisposed=!1,this.animations=new Array,this._ranges={},this.onReady=null,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=_.a.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._sceneRootNodesIndex=-1,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new u.c,this._onDisposeObserver=null,this._behaviors=new Array,this.name=c,this.id=c,this._scene=E||M.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return m.AddNodeConstructor=function(c,E){this._NodeConstructors[c]=E},m.Construct=function(c,E,A,S){var g=this._NodeConstructors[c];return g?g(E,A,S):null},Object.defineProperty(m.prototype,"doNotSerialize",{get:function(){return!!this._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize},set:function(c){this._doNotSerialize=c},enumerable:!1,configurable:!0}),m.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(m.prototype,"parent",{get:function(){return this._parentNode},set:function(c){if(this._parentNode!==c){var E=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){var A=this._parentNode._children.indexOf(this);A!==-1&&this._parentNode._children.splice(A,1),c||this._isDisposed||this._addToSceneRootNodes()}this._parentNode=c,this._parentNode&&(this._parentNode._children!==void 0&&this._parentNode._children!==null||(this._parentNode._children=new Array),this._parentNode._children.push(this),E||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}},enumerable:!1,configurable:!0}),m.prototype._addToSceneRootNodes=function(){this._sceneRootNodesIndex===-1&&(this._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))},m.prototype._removeFromSceneRootNodes=function(){if(this._sceneRootNodesIndex!==-1){var c=this._scene.rootNodes,E=c.length-1;c[this._sceneRootNodesIndex]=c[E],c[this._sceneRootNodesIndex]._sceneRootNodesIndex=this._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._sceneRootNodesIndex=-1}},Object.defineProperty(m.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(c){this._animationPropertiesOverride=c},enumerable:!1,configurable:!0}),m.prototype.getClassName=function(){return"Node"},Object.defineProperty(m.prototype,"onDispose",{set:function(c){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(c)},enumerable:!1,configurable:!0}),m.prototype.getScene=function(){return this._scene},m.prototype.getEngine=function(){return this._scene.getEngine()},m.prototype.addBehavior=function(c,E){var A=this;return E===void 0&&(E=!1),this._behaviors.indexOf(c)!==-1||(c.init(),this._scene.isLoading&&!E?this._scene.onDataLoadedObservable.addOnce(function(){c.attach(A)}):c.attach(this),this._behaviors.push(c)),this},m.prototype.removeBehavior=function(c){var E=this._behaviors.indexOf(c);return E===-1||(this._behaviors[E].detach(),this._behaviors.splice(E,1)),this},Object.defineProperty(m.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!1,configurable:!0}),m.prototype.getBehaviorByName=function(c){for(var E=0,A=this._behaviors;E -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -#include[SCENE_MRT_COUNT] -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif - -#define RECIPROCAL_PI2 0.15915494 -uniform vec3 vEyePosition; -uniform vec3 vAmbientColor; - -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef VERTEXCOLOR -varying vec4 vColor; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif - -#include - -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include - -#ifdef DIFFUSE -#if DIFFUSEDIRECTUV == 1 -#define vDiffuseUV vMainUV1 -#elif DIFFUSEDIRECTUV == 2 -#define vDiffuseUV vMainUV2 -#else -varying vec2 vDiffuseUV; -#endif -uniform sampler2D diffuseSampler; -#endif -#ifdef AMBIENT -#if AMBIENTDIRECTUV == 1 -#define vAmbientUV vMainUV1 -#elif AMBIENTDIRECTUV == 2 -#define vAmbientUV vMainUV2 -#else -varying vec2 vAmbientUV; -#endif -uniform sampler2D ambientSampler; -#endif -#ifdef OPACITY -#if OPACITYDIRECTUV == 1 -#define vOpacityUV vMainUV1 -#elif OPACITYDIRECTUV == 2 -#define vOpacityUV vMainUV2 -#else -varying vec2 vOpacityUV; -#endif -uniform sampler2D opacitySampler; -#endif -#ifdef EMISSIVE -#if EMISSIVEDIRECTUV == 1 -#define vEmissiveUV vMainUV1 -#elif EMISSIVEDIRECTUV == 2 -#define vEmissiveUV vMainUV2 -#else -varying vec2 vEmissiveUV; -#endif -uniform sampler2D emissiveSampler; -#endif -#ifdef LIGHTMAP -#if LIGHTMAPDIRECTUV == 1 -#define vLightmapUV vMainUV1 -#elif LIGHTMAPDIRECTUV == 2 -#define vLightmapUV vMainUV2 -#else -varying vec2 vLightmapUV; -#endif -uniform sampler2D lightmapSampler; -#endif -#ifdef REFRACTION -#ifdef REFRACTIONMAP_3D -uniform samplerCube refractionCubeSampler; -#else -uniform sampler2D refraction2DSampler; -#endif -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -#if SPECULARDIRECTUV == 1 -#define vSpecularUV vMainUV1 -#elif SPECULARDIRECTUV == 2 -#define vSpecularUV vMainUV2 -#else -varying vec2 vSpecularUV; -#endif -uniform sampler2D specularSampler; -#endif -#ifdef ALPHATEST -uniform float alphaCutOff; -#endif - -#include - -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -uniform samplerCube reflectionCubeSampler; -#else -uniform sampler2D reflection2DSampler; -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -vec3 viewDirectionW=normalize(vEyePosition-vPositionW); - -vec4 baseColor=vec4(1.,1.,1.,1.); -vec3 diffuseColor=vDiffuseColor.rgb; - -float alpha=vDiffuseColor.a; - -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); -#endif -#include -#ifdef TWOSIDEDLIGHTING -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -#ifdef DIFFUSE -baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); -#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) -if (baseColor.a -#ifdef VERTEXCOLOR -baseColor.rgb*=vColor.rgb; -#endif -#ifdef DETAIL -baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); -#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[0..maxSimultaneousLights] - -vec4 refractionColor=vec4(0.,0.,0.,1.); -#ifdef REFRACTION -vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); -#ifdef REFRACTIONMAP_3D -refractionVector.y=refractionVector.y*vRefractionInfos.w; -if (dot(refractionVector,viewDirectionW)<1.0) { -refractionColor=textureCube(refractionCubeSampler,refractionVector); -} -#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_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 -#ifdef VERTEXALPHA -alpha*=vColor.a; -#endif -#ifdef OPACITYFRESNEL -float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w); -alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; -#endif -#ifdef ALPHATEST -#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS -if (alpha -#include - - -#ifdef IMAGEPROCESSINGPOSTPROCESS -color.rgb=toLinearSpace(color.rgb); -#else -#ifdef IMAGEPROCESSING -color.rgb=toLinearSpace(color.rgb); -color=applyImageProcessing(color); -#endif -#endif -color.a*=visibility; -#ifdef PREMULTIPLYALPHA - -color.rgb*=color.a; -#endif -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -gl_FragData[0]=color; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,1.0); -#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,1.0); -#endif -#ifdef PREPASS_IRRADIANCE -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,1.0); -#endif -#ifdef PREPASS_DEPTHNORMAL -gl_FragData[PREPASS_DEPTHNORMAL_INDEX]=vec4(vViewPos.z,(view*vec4(normalW,0.0)).rgb); -#endif -#ifdef PREPASS_ALBEDO -gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(0.0,0.0,0.0,1.0); -#endif -#ifdef PREPASS_REFLECTIVITY -#if defined(SPECULAR) -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=specularMapColor; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0); -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=color; -#endif -} -`;T.a.ShadersStore.defaultPixelShader=N;var I=` -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 -`;T.a.IncludesShadersStore.defaultVertexDeclaration=I,f(78),f(79),f(163),f(164),f(117),f(137),f(93),f(94),f(100),f(80),f(81),f(165),f(156),f(111),f(157),f(138),T.a.IncludesShadersStore.pointCloudVertex=`#ifdef POINTSIZE -gl_PointSize=pointSize; -#endif`,f(158);var V=`#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 -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include - -#include -#include -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 -varying vec2 vDiffuseUV; -#endif -#if defined(DETAIL) && DETAILDIRECTUV == 0 -varying vec2 vDetailUV; -#endif -#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 -varying vec2 vAmbientUV; -#endif -#if defined(OPACITY) && OPACITYDIRECTUV == 0 -varying vec2 vOpacityUV; -#endif -#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 -varying vec2 vEmissiveUV; -#endif -#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 -varying vec2 vLightmapUV; -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0 -varying vec2 vSpecularUV; -#endif -#if defined(BUMP) && BUMPDIRECTUV == 0 -varying vec2 vBumpUV; -#endif - -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef VERTEXCOLOR -varying vec4 vColor; -#endif -#include -#include -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) - -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0); -#endif -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2])); -vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR == 0u) { -gl_Position=viewProjection*worldPos; -} else { -gl_Position=viewProjectionR*worldPos; -} -#else -gl_Position=viewProjection*worldPos; -#endif -vPositionW=vec3(worldPos); -#include -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif - -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 -if (vDiffuseInfos.x == 0.) -{ -vDiffuseUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(DETAIL) && DETAILDIRECTUV == 0 -if (vDetailInfos.x == 0.) -{ -vDetailUV=vec2(detailMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vDetailUV=vec2(detailMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 -if (vAmbientInfos.x == 0.) -{ -vAmbientUV=vec2(ambientMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(OPACITY) && OPACITYDIRECTUV == 0 -if (vOpacityInfos.x == 0.) -{ -vOpacityUV=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 -if (vEmissiveInfos.x == 0.) -{ -vEmissiveUV=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 -if (vLightmapInfos.x == 0.) -{ -vLightmapUV=vec2(lightmapMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0 -if (vSpecularInfos.x == 0.) -{ -vSpecularUV=vec2(specularMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(BUMP) && BUMPDIRECTUV == 0 -if (vBumpInfos.x == 0.) -{ -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#include -#include -#include -#include[0..maxSimultaneousLights] -#ifdef VERTEXCOLOR - -vColor=color; -#endif -#include -#include -#define CUSTOM_VERTEX_MAIN_END -} -`;T.a.ShadersStore.defaultVertexShader=V;var W=f(2),j=f(67),ne=f(92),te={effect:null,subMesh:null},de=function(ae){function ee(){var K=ae.call(this)||this;return K.MAINUV1=!1,K.MAINUV2=!1,K.DIFFUSE=!1,K.DIFFUSEDIRECTUV=0,K.DETAIL=!1,K.DETAILDIRECTUV=0,K.DETAIL_NORMALBLENDMETHOD=0,K.AMBIENT=!1,K.AMBIENTDIRECTUV=0,K.OPACITY=!1,K.OPACITYDIRECTUV=0,K.OPACITYRGB=!1,K.REFLECTION=!1,K.EMISSIVE=!1,K.EMISSIVEDIRECTUV=0,K.SPECULAR=!1,K.SPECULARDIRECTUV=0,K.BUMP=!1,K.BUMPDIRECTUV=0,K.PARALLAX=!1,K.PARALLAXOCCLUSION=!1,K.SPECULAROVERALPHA=!1,K.CLIPPLANE=!1,K.CLIPPLANE2=!1,K.CLIPPLANE3=!1,K.CLIPPLANE4=!1,K.CLIPPLANE5=!1,K.CLIPPLANE6=!1,K.ALPHATEST=!1,K.DEPTHPREPASS=!1,K.ALPHAFROMDIFFUSE=!1,K.POINTSIZE=!1,K.FOG=!1,K.SPECULARTERM=!1,K.DIFFUSEFRESNEL=!1,K.OPACITYFRESNEL=!1,K.REFLECTIONFRESNEL=!1,K.REFRACTIONFRESNEL=!1,K.EMISSIVEFRESNEL=!1,K.FRESNEL=!1,K.NORMAL=!1,K.UV1=!1,K.UV2=!1,K.VERTEXCOLOR=!1,K.VERTEXALPHA=!1,K.NUM_BONE_INFLUENCERS=0,K.BonesPerMesh=0,K.BONETEXTURE=!1,K.BONES_VELOCITY_ENABLED=!1,K.INSTANCES=!1,K.THIN_INSTANCES=!1,K.GLOSSINESS=!1,K.ROUGHNESS=!1,K.EMISSIVEASILLUMINATION=!1,K.LINKEMISSIVEWITHDIFFUSE=!1,K.REFLECTIONFRESNELFROMSPECULAR=!1,K.LIGHTMAP=!1,K.LIGHTMAPDIRECTUV=0,K.OBJECTSPACE_NORMALMAP=!1,K.USELIGHTMAPASSHADOWMAP=!1,K.REFLECTIONMAP_3D=!1,K.REFLECTIONMAP_SPHERICAL=!1,K.REFLECTIONMAP_PLANAR=!1,K.REFLECTIONMAP_CUBIC=!1,K.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,K.REFLECTIONMAP_PROJECTION=!1,K.REFLECTIONMAP_SKYBOX=!1,K.REFLECTIONMAP_EXPLICIT=!1,K.REFLECTIONMAP_EQUIRECTANGULAR=!1,K.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,K.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,K.INVERTCUBICMAP=!1,K.LOGARITHMICDEPTH=!1,K.REFRACTION=!1,K.REFRACTIONMAP_3D=!1,K.REFLECTIONOVERALPHA=!1,K.TWOSIDEDLIGHTING=!1,K.SHADOWFLOAT=!1,K.MORPHTARGETS=!1,K.MORPHTARGETS_NORMAL=!1,K.MORPHTARGETS_TANGENT=!1,K.MORPHTARGETS_UV=!1,K.NUM_MORPH_INFLUENCERS=0,K.NONUNIFORMSCALING=!1,K.PREMULTIPLYALPHA=!1,K.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,K.ALPHABLEND=!0,K.PREPASS=!1,K.PREPASS_IRRADIANCE=!1,K.PREPASS_IRRADIANCE_INDEX=-1,K.PREPASS_ALBEDO=!1,K.PREPASS_ALBEDO_INDEX=-1,K.PREPASS_DEPTHNORMAL=!1,K.PREPASS_DEPTHNORMAL_INDEX=-1,K.PREPASS_POSITION=!1,K.PREPASS_POSITION_INDEX=-1,K.PREPASS_VELOCITY=!1,K.PREPASS_VELOCITY_INDEX=-1,K.PREPASS_REFLECTIVITY=!1,K.PREPASS_REFLECTIVITY_INDEX=-1,K.SCENE_MRT_COUNT=0,K.RGBDLIGHTMAP=!1,K.RGBDREFLECTION=!1,K.RGBDREFRACTION=!1,K.IMAGEPROCESSING=!1,K.VIGNETTE=!1,K.VIGNETTEBLENDMODEMULTIPLY=!1,K.VIGNETTEBLENDMODEOPAQUE=!1,K.TONEMAPPING=!1,K.TONEMAPPING_ACES=!1,K.CONTRAST=!1,K.COLORCURVES=!1,K.COLORGRADING=!1,K.COLORGRADING3D=!1,K.SAMPLER3DGREENDEPTH=!1,K.SAMPLER3DBGRMAP=!1,K.IMAGEPROCESSINGPOSTPROCESS=!1,K.MULTIVIEW=!1,K.IS_REFLECTION_LINEAR=!1,K.IS_REFRACTION_LINEAR=!1,K.EXPOSURE=!1,K.rebuild(),K}return Object(B.d)(ee,ae),ee.prototype.setReflectionMode=function(K){for(var $=0,L=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];$0,Q.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,Q.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===l.a.INVCUBIC_MODE,Q.REFLECTIONMAP_3D=this._reflectionTexture.isCube,Q.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case l.a.EXPLICIT_MODE:Q.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case l.a.PLANAR_MODE:Q.setReflectionMode("REFLECTIONMAP_PLANAR");break;case l.a.PROJECTION_MODE:Q.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case l.a.SKYBOX_MODE:Q.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case l.a.SPHERICAL_MODE:Q.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case l.a.EQUIRECTANGULAR_MODE:Q.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case l.a.FIXED_EQUIRECTANGULAR_MODE:Q.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case l.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:Q.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case l.a.CUBIC_MODE:case l.a.INVCUBIC_MODE:default:Q.setReflectionMode("REFLECTIONMAP_CUBIC")}Q.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else Q.REFLECTION=!1;if(this._emissiveTexture&&ee.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;g.a.PrepareDefinesForMergedUV(this._emissiveTexture,Q,"EMISSIVE")}else Q.EMISSIVE=!1;if(this._lightmapTexture&&ee.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;g.a.PrepareDefinesForMergedUV(this._lightmapTexture,Q,"LIGHTMAP"),Q.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,Q.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else Q.LIGHTMAP=!1;if(this._specularTexture&&ee.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;g.a.PrepareDefinesForMergedUV(this._specularTexture,Q,"SPECULAR"),Q.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else Q.SPECULAR=!1;if(G.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&ee.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;g.a.PrepareDefinesForMergedUV(this._bumpTexture,Q,"BUMP"),Q.PARALLAX=this._useParallax,Q.PARALLAXOCCLUSION=this._useParallaxOcclusion,Q.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else Q.BUMP=!1;if(this._refractionTexture&&ee.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;Q._needUVs=!0,Q.REFRACTION=!0,Q.REFRACTIONMAP_3D=this._refractionTexture.isCube,Q.RGBDREFRACTION=this._refractionTexture.isRGBD}else Q.REFRACTION=!1;Q.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else Q.DIFFUSE=!1,Q.AMBIENT=!1,Q.OPACITY=!1,Q.REFLECTION=!1,Q.EMISSIVE=!1,Q.LIGHTMAP=!1,Q.BUMP=!1,Q.REFRACTION=!1;Q.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),Q.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,Q.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,Q.SPECULAROVERALPHA=this._useSpecularOverAlpha,Q.PREMULTIPLYALPHA=this.alphaMode===W.a.ALPHA_PREMULTIPLIED||this.alphaMode===W.a.ALPHA_PREMULTIPLIED_PORTERDUFF,Q.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,Q.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(K)}if(!this.detailMap.isReadyForSubMesh(Q,G))return!1;if(Q._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(Q),Q.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,Q.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(Q._areFresnelDirty&&(ee.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(Q.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,Q.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,Q.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,Q.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,Q.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,Q.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,Q._needNormals=!0,Q.FRESNEL=!0):Q.FRESNEL=!1),g.a.PrepareDefinesForMisc(K,G,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(K)||this._forceAlphaTest,Q),g.a.PrepareDefinesForAttributes(K,Q,!0,!0,!0),g.a.PrepareDefinesForFrameBoundValues(G,oe,Q,L,null,$.getRenderingMesh().hasThinInstances),this.detailMap.prepareDefines(Q,G),Q.isDirty){var re=Q._areLightsDisposed;Q.markAsProcessed();var Y=new j.a;Q.REFLECTION&&Y.addFallback(0,"REFLECTION"),Q.SPECULAR&&Y.addFallback(0,"SPECULAR"),Q.BUMP&&Y.addFallback(0,"BUMP"),Q.PARALLAX&&Y.addFallback(1,"PARALLAX"),Q.PARALLAXOCCLUSION&&Y.addFallback(0,"PARALLAXOCCLUSION"),Q.SPECULAROVERALPHA&&Y.addFallback(0,"SPECULAROVERALPHA"),Q.FOG&&Y.addFallback(1,"FOG"),Q.POINTSIZE&&Y.addFallback(0,"POINTSIZE"),Q.LOGARITHMICDEPTH&&Y.addFallback(0,"LOGARITHMICDEPTH"),g.a.HandleFallbacksForShadows(Q,Y,this._maxSimultaneousLights),Q.SPECULARTERM&&Y.addFallback(0,"SPECULARTERM"),Q.DIFFUSEFRESNEL&&Y.addFallback(1,"DIFFUSEFRESNEL"),Q.OPACITYFRESNEL&&Y.addFallback(2,"OPACITYFRESNEL"),Q.REFLECTIONFRESNEL&&Y.addFallback(3,"REFLECTIONFRESNEL"),Q.EMISSIVEFRESNEL&&Y.addFallback(4,"EMISSIVEFRESNEL"),Q.FRESNEL&&Y.addFallback(4,"FRESNEL"),Q.MULTIVIEW&&Y.addFallback(0,"MULTIVIEW");var k=[C.b.PositionKind];Q.NORMAL&&k.push(C.b.NormalKind),Q.UV1&&k.push(C.b.UVKind),Q.UV2&&k.push(C.b.UV2Kind),Q.VERTEXCOLOR&&k.push(C.b.ColorKind),g.a.PrepareAttributesForBones(k,K,Q,Y),g.a.PrepareAttributesForInstances(k,Q),g.a.PrepareAttributesForMorphTargets(k,K,Q);var H="default",Z=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth"],X=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler"],q=["Material","Scene"];ne.a.AddUniforms(Z),ne.a.AddSamplers(X),m.a.AddUniforms(Z),m.a.AddSamplers(Z),c.a&&(c.a.PrepareUniforms(Z,Q),c.a.PrepareSamplers(X,Q)),g.a.PrepareUniformsAndSamplersList({uniformsNames:Z,uniformBuffersNames:q,samplers:X,defines:Q,maxSimultaneousLights:this._maxSimultaneousLights});var he={};this.customShaderNameResolve&&(H=this.customShaderNameResolve(H,Z,q,X,Q,k,he));var ge=Q.toString(),me=$.effect,_e=G.getEngine().createEffect(H,{attributes:k,uniformsNames:Z,uniformBuffersNames:q,samplers:X,defines:ge,fallbacks:Y,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:Q.NUM_MORPH_INFLUENCERS},processFinalCode:he.processFinalCode,multiTarget:Q.PREPASS},oe);if(_e)if(this._onEffectCreatedObservable&&(te.effect=_e,te.subMesh=$,this._onEffectCreatedObservable.notifyObservers(te)),this.allowShaderHotSwapping&&me&&!_e.isReady()){if(_e=me,this._rebuildInParallel=!0,Q.markAsUnprocessed(),re)return Q._areLightsDisposed=!0,!1}else this._rebuildInParallel=!1,G.resetCachedMaterial(),$.setEffect(_e,Q),this.buildUniformLayout()}return!(!$.effect||!$.effect.isReady())&&(Q._renderId=G.getRenderId(),$.effect._wasPreviouslyReady=!0,!0)},ee.prototype.buildUniformLayout=function(){var K=this._uniformBuffer;K.addUniform("diffuseLeftColor",4),K.addUniform("diffuseRightColor",4),K.addUniform("opacityParts",4),K.addUniform("reflectionLeftColor",4),K.addUniform("reflectionRightColor",4),K.addUniform("refractionLeftColor",4),K.addUniform("refractionRightColor",4),K.addUniform("emissiveLeftColor",4),K.addUniform("emissiveRightColor",4),K.addUniform("vDiffuseInfos",2),K.addUniform("vAmbientInfos",2),K.addUniform("vOpacityInfos",2),K.addUniform("vReflectionInfos",2),K.addUniform("vReflectionPosition",3),K.addUniform("vReflectionSize",3),K.addUniform("vEmissiveInfos",2),K.addUniform("vLightmapInfos",2),K.addUniform("vSpecularInfos",2),K.addUniform("vBumpInfos",3),K.addUniform("diffuseMatrix",16),K.addUniform("ambientMatrix",16),K.addUniform("opacityMatrix",16),K.addUniform("reflectionMatrix",16),K.addUniform("emissiveMatrix",16),K.addUniform("lightmapMatrix",16),K.addUniform("specularMatrix",16),K.addUniform("bumpMatrix",16),K.addUniform("vTangentSpaceParams",2),K.addUniform("pointSize",1),K.addUniform("refractionMatrix",16),K.addUniform("vRefractionInfos",4),K.addUniform("vSpecularColor",4),K.addUniform("vEmissiveColor",3),K.addUniform("visibility",1),K.addUniform("vDiffuseColor",4),ne.a.PrepareUniformBuffer(K),K.create()},ee.prototype.unbind=function(){if(this._activeEffect){var K=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),K=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),K=!0),K&&this._markAllSubMeshesAsTexturesDirty()}ae.prototype.unbind.call(this)},ee.prototype.bindForSubMesh=function(K,$,L){var G=this.getScene(),Q=L._materialDefines;if(Q){var oe=L.effect;if(oe){this._activeEffect=oe,Q.INSTANCES&&!Q.THIN_INSTANCES||this.bindOnlyWorldMatrix(K),this.prePassConfiguration.bindForSubMesh(this._activeEffect,G,$,K,this.isFrozen),Q.OBJECTSPACE_NORMALMAP&&(K.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var re=this._mustRebind(G,oe,$.visibility);g.a.BindBonesParameters($,oe);var Y=this._uniformBuffer;if(re){if(Y.bindToEffect(oe,"Material"),this.bindViewProjection(oe),!Y.useUbo||!this.isFrozen||!Y.isSync){if(ee.FresnelEnabled&&Q.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(Y.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),Y.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&Y.updateColor4("opacityParts",new R.a(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(Y.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),Y.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(Y.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),Y.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(Y.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),Y.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),G.texturesEnabled){if(this._diffuseTexture&&ee.DiffuseTextureEnabled&&(Y.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),g.a.BindTextureMatrix(this._diffuseTexture,Y,"diffuse")),this._ambientTexture&&ee.AmbientTextureEnabled&&(Y.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),g.a.BindTextureMatrix(this._ambientTexture,Y,"ambient")),this._opacityTexture&&ee.OpacityTextureEnabled&&(Y.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),g.a.BindTextureMatrix(this._opacityTexture,Y,"opacity")),this._hasAlphaChannel()&&oe.setFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&ee.ReflectionTextureEnabled&&(Y.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),Y.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var k=this._reflectionTexture;Y.updateVector3("vReflectionPosition",k.boundingBoxPosition),Y.updateVector3("vReflectionSize",k.boundingBoxSize)}if(this._emissiveTexture&&ee.EmissiveTextureEnabled&&(Y.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),g.a.BindTextureMatrix(this._emissiveTexture,Y,"emissive")),this._lightmapTexture&&ee.LightmapTextureEnabled&&(Y.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),g.a.BindTextureMatrix(this._lightmapTexture,Y,"lightmap")),this._specularTexture&&ee.SpecularTextureEnabled&&(Y.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),g.a.BindTextureMatrix(this._specularTexture,Y,"specular")),this._bumpTexture&&G.getEngine().getCaps().standardDerivatives&&ee.BumpTextureEnabled&&(Y.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),g.a.BindTextureMatrix(this._bumpTexture,Y,"bump"),G._mirroredCameraPosition?Y.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):Y.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&ee.RefractionTextureEnabled){var H=1;this._refractionTexture.isCube||(Y.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(H=this._refractionTexture.depth)),Y.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,H,this.invertRefractionY?-1:1)}}this.pointsCloud&&Y.updateFloat("pointSize",this.pointSize),Q.SPECULARTERM&&Y.updateColor4("vSpecularColor",this.specularColor,this.specularPower),Y.updateColor3("vEmissiveColor",ee.EmissiveTextureEnabled?this.emissiveColor:R.a.BlackReadOnly),Y.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha)}Y.updateFloat("visibility",$.visibility),G.texturesEnabled&&(this._diffuseTexture&&ee.DiffuseTextureEnabled&&oe.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&ee.AmbientTextureEnabled&&oe.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ee.OpacityTextureEnabled&&oe.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&ee.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?oe.setTexture("reflectionCubeSampler",this._reflectionTexture):oe.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&ee.EmissiveTextureEnabled&&oe.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ee.LightmapTextureEnabled&&oe.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&ee.SpecularTextureEnabled&&oe.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&G.getEngine().getCaps().standardDerivatives&&ee.BumpTextureEnabled&&oe.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&ee.RefractionTextureEnabled)&&(H=1,this._refractionTexture.isCube?oe.setTexture("refractionCubeSampler",this._refractionTexture):oe.setTexture("refraction2DSampler",this._refractionTexture)),this.detailMap.bindForSubMesh(Y,G,this.isFrozen),g.a.BindClipPlane(oe,G),G.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),g.a.BindEyePosition(oe,G),oe.setColor3("vAmbientColor",this._globalAmbientColor)}!re&&this.isFrozen||(G.lightsEnabled&&!this._disableLighting&&g.a.BindLights(G,$,oe,Q,this._maxSimultaneousLights,this._rebuildInParallel),(G.fogEnabled&&$.applyFog&&G.fogMode!==u.a.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(oe),g.a.BindFogParameters(G,$,oe),Q.NUM_MORPH_INFLUENCERS&&g.a.BindMorphTargetParameters($,oe),this.useLogarithmicDepth&&g.a.BindLogDepth(Q,oe,G),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),Y.update(),this._afterBind($,this._activeEffect)}}},ee.prototype.getAnimatables=function(){var K=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&K.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&K.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&K.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&K.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&K.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&K.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&K.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&K.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&K.push(this._refractionTexture),this.detailMap.getAnimatables(K),K},ee.prototype.getActiveTextures=function(){var K=ae.prototype.getActiveTextures.call(this);return this._diffuseTexture&&K.push(this._diffuseTexture),this._ambientTexture&&K.push(this._ambientTexture),this._opacityTexture&&K.push(this._opacityTexture),this._reflectionTexture&&K.push(this._reflectionTexture),this._emissiveTexture&&K.push(this._emissiveTexture),this._specularTexture&&K.push(this._specularTexture),this._bumpTexture&&K.push(this._bumpTexture),this._lightmapTexture&&K.push(this._lightmapTexture),this._refractionTexture&&K.push(this._refractionTexture),this.detailMap.getActiveTextures(K),K},ee.prototype.hasTexture=function(K){return!!ae.prototype.hasTexture.call(this,K)||this._diffuseTexture===K||this._ambientTexture===K||this._opacityTexture===K||this._reflectionTexture===K||this._emissiveTexture===K||this._specularTexture===K||this._bumpTexture===K||this._lightmapTexture===K||this._refractionTexture===K||this.detailMap.hasTexture(K)},ee.prototype.dispose=function(K,$){var L,G,Q,oe,re,Y,k,H,Z;$&&((L=this._diffuseTexture)===null||L===void 0||L.dispose(),(G=this._ambientTexture)===null||G===void 0||G.dispose(),(Q=this._opacityTexture)===null||Q===void 0||Q.dispose(),(oe=this._reflectionTexture)===null||oe===void 0||oe.dispose(),(re=this._emissiveTexture)===null||re===void 0||re.dispose(),(Y=this._specularTexture)===null||Y===void 0||Y.dispose(),(k=this._bumpTexture)===null||k===void 0||k.dispose(),(H=this._lightmapTexture)===null||H===void 0||H.dispose(),(Z=this._refractionTexture)===null||Z===void 0||Z.dispose()),this.detailMap.dispose($),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),ae.prototype.dispose.call(this,K,$)},ee.prototype.clone=function(K){var $=this,L=_.a.Clone(function(){return new ee(K,$.getScene())},this);return L.name=K,L.id=K,L},ee.prototype.serialize=function(){return _.a.Serialize(this)},ee.Parse=function(K,$,L){return _.a.Parse(function(){return new ee(K.name,$)},K,$,L)},Object.defineProperty(ee,"DiffuseTextureEnabled",{get:function(){return b.a.DiffuseTextureEnabled},set:function(K){b.a.DiffuseTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"DetailTextureEnabled",{get:function(){return b.a.DetailTextureEnabled},set:function(K){b.a.DetailTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"AmbientTextureEnabled",{get:function(){return b.a.AmbientTextureEnabled},set:function(K){b.a.AmbientTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"OpacityTextureEnabled",{get:function(){return b.a.OpacityTextureEnabled},set:function(K){b.a.OpacityTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"ReflectionTextureEnabled",{get:function(){return b.a.ReflectionTextureEnabled},set:function(K){b.a.ReflectionTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"EmissiveTextureEnabled",{get:function(){return b.a.EmissiveTextureEnabled},set:function(K){b.a.EmissiveTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"SpecularTextureEnabled",{get:function(){return b.a.SpecularTextureEnabled},set:function(K){b.a.SpecularTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"BumpTextureEnabled",{get:function(){return b.a.BumpTextureEnabled},set:function(K){b.a.BumpTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"LightmapTextureEnabled",{get:function(){return b.a.LightmapTextureEnabled},set:function(K){b.a.LightmapTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"RefractionTextureEnabled",{get:function(){return b.a.RefractionTextureEnabled},set:function(K){b.a.RefractionTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"ColorGradingTextureEnabled",{get:function(){return b.a.ColorGradingTextureEnabled},set:function(K){b.a.ColorGradingTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"FresnelEnabled",{get:function(){return b.a.FresnelEnabled},set:function(K){b.a.FresnelEnabled=K},enumerable:!1,configurable:!0}),Object(B.c)([Object(_.m)("diffuseTexture")],ee.prototype,"_diffuseTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"diffuseTexture",void 0),Object(B.c)([Object(_.m)("ambientTexture")],ee.prototype,"_ambientTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"ambientTexture",void 0),Object(B.c)([Object(_.m)("opacityTexture")],ee.prototype,"_opacityTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"opacityTexture",void 0),Object(B.c)([Object(_.m)("reflectionTexture")],ee.prototype,"_reflectionTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"reflectionTexture",void 0),Object(B.c)([Object(_.m)("emissiveTexture")],ee.prototype,"_emissiveTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"emissiveTexture",void 0),Object(B.c)([Object(_.m)("specularTexture")],ee.prototype,"_specularTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"specularTexture",void 0),Object(B.c)([Object(_.m)("bumpTexture")],ee.prototype,"_bumpTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"bumpTexture",void 0),Object(B.c)([Object(_.m)("lightmapTexture")],ee.prototype,"_lightmapTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"lightmapTexture",void 0),Object(B.c)([Object(_.m)("refractionTexture")],ee.prototype,"_refractionTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"refractionTexture",void 0),Object(B.c)([Object(_.e)("ambient")],ee.prototype,"ambientColor",void 0),Object(B.c)([Object(_.e)("diffuse")],ee.prototype,"diffuseColor",void 0),Object(B.c)([Object(_.e)("specular")],ee.prototype,"specularColor",void 0),Object(B.c)([Object(_.e)("emissive")],ee.prototype,"emissiveColor",void 0),Object(B.c)([Object(_.c)()],ee.prototype,"specularPower",void 0),Object(B.c)([Object(_.c)("useAlphaFromDiffuseTexture")],ee.prototype,"_useAlphaFromDiffuseTexture",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"useAlphaFromDiffuseTexture",void 0),Object(B.c)([Object(_.c)("useEmissiveAsIllumination")],ee.prototype,"_useEmissiveAsIllumination",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useEmissiveAsIllumination",void 0),Object(B.c)([Object(_.c)("linkEmissiveWithDiffuse")],ee.prototype,"_linkEmissiveWithDiffuse",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"linkEmissiveWithDiffuse",void 0),Object(B.c)([Object(_.c)("useSpecularOverAlpha")],ee.prototype,"_useSpecularOverAlpha",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useSpecularOverAlpha",void 0),Object(B.c)([Object(_.c)("useReflectionOverAlpha")],ee.prototype,"_useReflectionOverAlpha",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useReflectionOverAlpha",void 0),Object(B.c)([Object(_.c)("disableLighting")],ee.prototype,"_disableLighting",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsLightsDirty")],ee.prototype,"disableLighting",void 0),Object(B.c)([Object(_.c)("useObjectSpaceNormalMap")],ee.prototype,"_useObjectSpaceNormalMap",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useObjectSpaceNormalMap",void 0),Object(B.c)([Object(_.c)("useParallax")],ee.prototype,"_useParallax",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useParallax",void 0),Object(B.c)([Object(_.c)("useParallaxOcclusion")],ee.prototype,"_useParallaxOcclusion",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useParallaxOcclusion",void 0),Object(B.c)([Object(_.c)()],ee.prototype,"parallaxScaleBias",void 0),Object(B.c)([Object(_.c)("roughness")],ee.prototype,"_roughness",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"roughness",void 0),Object(B.c)([Object(_.c)()],ee.prototype,"indexOfRefraction",void 0),Object(B.c)([Object(_.c)()],ee.prototype,"invertRefractionY",void 0),Object(B.c)([Object(_.c)()],ee.prototype,"alphaCutOff",void 0),Object(B.c)([Object(_.c)("useLightmapAsShadowmap")],ee.prototype,"_useLightmapAsShadowmap",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useLightmapAsShadowmap",void 0),Object(B.c)([Object(_.h)("diffuseFresnelParameters")],ee.prototype,"_diffuseFresnelParameters",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"diffuseFresnelParameters",void 0),Object(B.c)([Object(_.h)("opacityFresnelParameters")],ee.prototype,"_opacityFresnelParameters",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsFresnelAndMiscDirty")],ee.prototype,"opacityFresnelParameters",void 0),Object(B.c)([Object(_.h)("reflectionFresnelParameters")],ee.prototype,"_reflectionFresnelParameters",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"reflectionFresnelParameters",void 0),Object(B.c)([Object(_.h)("refractionFresnelParameters")],ee.prototype,"_refractionFresnelParameters",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"refractionFresnelParameters",void 0),Object(B.c)([Object(_.h)("emissiveFresnelParameters")],ee.prototype,"_emissiveFresnelParameters",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"emissiveFresnelParameters",void 0),Object(B.c)([Object(_.c)("useReflectionFresnelFromSpecular")],ee.prototype,"_useReflectionFresnelFromSpecular",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"useReflectionFresnelFromSpecular",void 0),Object(B.c)([Object(_.c)("useGlossinessFromSpecularMapAlpha")],ee.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useGlossinessFromSpecularMapAlpha",void 0),Object(B.c)([Object(_.c)("maxSimultaneousLights")],ee.prototype,"_maxSimultaneousLights",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsLightsDirty")],ee.prototype,"maxSimultaneousLights",void 0),Object(B.c)([Object(_.c)("invertNormalMapX")],ee.prototype,"_invertNormalMapX",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"invertNormalMapX",void 0),Object(B.c)([Object(_.c)("invertNormalMapY")],ee.prototype,"_invertNormalMapY",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"invertNormalMapY",void 0),Object(B.c)([Object(_.c)("twoSidedLighting")],ee.prototype,"_twoSidedLighting",void 0),Object(B.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"twoSidedLighting",void 0),Object(B.c)([Object(_.c)()],ee.prototype,"useLogarithmicDepth",null),ee}(S.a);h.a.RegisteredTypes["BABYLON.StandardMaterial"]=pe,u.a.DefaultMaterialFactory=function(ae){return new pe("default material",ae)}},function(Ae,v,f){f.d(v,"a",function(){return I});var B=f(1),_=f(12),x=f(6),u=f(0),M=f(13),R=f(4),C=f(16),m=f(46),c=f(54),E=f(43),A=f(2),S=f(147),g=f(21),l=f(101),h=f(9),b=f(28),T=f(23),D=f(11),w=function(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=u.e.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1},N=function(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new w,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},I=function(V){function W(j,ne){ne===void 0&&(ne=null);var te=V.call(this,j,ne,!1)||this;return te._internalAbstractMeshDataInfo=new N,te.cullingStrategy=W.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,te.onCollideObservable=new x.c,te.onCollisionPositionChangeObservable=new x.c,te.onMaterialChangedObservable=new x.c,te.definedFacingForward=!0,te._occlusionQuery=null,te._renderingGroup=null,te.alphaIndex=Number.MAX_VALUE,te.isVisible=!0,te.isPickable=!0,te.showSubMeshesBoundingBox=!1,te.isBlocker=!1,te.enablePointerMoveEvents=!1,te._renderingGroupId=0,te._material=null,te.outlineColor=h.a.Red(),te.outlineWidth=.02,te.overlayColor=h.a.Red(),te.overlayAlpha=.5,te.useOctreeForRenderingSelection=!0,te.useOctreeForPicking=!0,te.useOctreeForCollisions=!0,te.alwaysSelectAsActiveMesh=!1,te.doNotSyncBoundingInfo=!1,te.actionManager=null,te._meshCollisionData=new S.a,te.ellipsoid=new u.e(.5,1,.5),te.ellipsoidOffset=new u.e(0,0,0),te.edgesWidth=1,te.edgesColor=new h.b(1,0,0,1),te._edgesRenderer=null,te._masterMesh=null,te._boundingInfo=null,te._renderId=0,te._intersectionsInProgress=new Array,te._unIndexed=!1,te._lightSources=new Array,te._waitingData={lods:null,actions:null,freezeWorldMatrix:null},te._bonesTransformMatrices=null,te._transformMatrixTexture=null,te.onRebuildObservable=new x.c,te._onCollisionPositionChange=function(de,pe,ae){ae===void 0&&(ae=null),pe.subtractToRef(te._meshCollisionData._oldPositionForCollisions,te._meshCollisionData._diffPositionForCollisions),te._meshCollisionData._diffPositionForCollisions.length()>M.a.CollisionsEpsilon&&te.position.addInPlace(te._meshCollisionData._diffPositionForCollisions),ae&&te.onCollideObservable.notifyObservers(ae),te.onCollisionPositionChangeObservable.notifyObservers(te.position)},te.getScene().addMesh(te),te._resyncLightSources(),te}return Object(B.d)(W,V),Object.defineProperty(W,"BILLBOARDMODE_NONE",{get:function(){return m.a.BILLBOARDMODE_NONE},enumerable:!1,configurable:!0}),Object.defineProperty(W,"BILLBOARDMODE_X",{get:function(){return m.a.BILLBOARDMODE_X},enumerable:!1,configurable:!0}),Object.defineProperty(W,"BILLBOARDMODE_Y",{get:function(){return m.a.BILLBOARDMODE_Y},enumerable:!1,configurable:!0}),Object.defineProperty(W,"BILLBOARDMODE_Z",{get:function(){return m.a.BILLBOARDMODE_Z},enumerable:!1,configurable:!0}),Object.defineProperty(W,"BILLBOARDMODE_ALL",{get:function(){return m.a.BILLBOARDMODE_ALL},enumerable:!1,configurable:!0}),Object.defineProperty(W,"BILLBOARDMODE_USE_POSITION",{get:function(){return m.a.BILLBOARDMODE_USE_POSITION},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"facetNb",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetNb},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"partitioningSubdivisions",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions},set:function(j){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"partitioningBBoxRatio",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio},set:function(j){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"mustDepthSortFacets",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort},set:function(j){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"facetDepthSortFrom",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom},set:function(j){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"isFacetDataEnabled",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled},enumerable:!1,configurable:!0}),W.prototype._updateNonUniformScalingState=function(j){return!!V.prototype._updateNonUniformScalingState.call(this,j)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(W.prototype,"onCollide",{set:function(j){this._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._meshCollisionData._onCollideObserver),this._meshCollisionData._onCollideObserver=this.onCollideObservable.add(j)},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"onCollisionPositionChange",{set:function(j){this._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._meshCollisionData._onCollisionPositionChangeObserver),this._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(j)},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"visibility",{get:function(){return this._internalAbstractMeshDataInfo._visibility},set:function(j){this._internalAbstractMeshDataInfo._visibility!==j&&(this._internalAbstractMeshDataInfo._visibility=j,this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"renderingGroupId",{get:function(){return this._renderingGroupId},set:function(j){this._renderingGroupId=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"material",{get:function(){return this._material},set:function(j){this._material!==j&&(this._material&&this._material.meshMap&&(this._material.meshMap[this.uniqueId]=void 0),this._material=j,j&&j.meshMap&&(j.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"receiveShadows",{get:function(){return this._internalAbstractMeshDataInfo._receiveShadows},set:function(j){this._internalAbstractMeshDataInfo._receiveShadows!==j&&(this._internalAbstractMeshDataInfo._receiveShadows=j,this._markSubMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"hasVertexAlpha",{get:function(){return this._internalAbstractMeshDataInfo._hasVertexAlpha},set:function(j){this._internalAbstractMeshDataInfo._hasVertexAlpha!==j&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=j,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"useVertexColors",{get:function(){return this._internalAbstractMeshDataInfo._useVertexColors},set:function(j){this._internalAbstractMeshDataInfo._useVertexColors!==j&&(this._internalAbstractMeshDataInfo._useVertexColors=j,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(j){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==j&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=j,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"numBoneInfluencers",{get:function(){return this._internalAbstractMeshDataInfo._numBoneInfluencers},set:function(j){this._internalAbstractMeshDataInfo._numBoneInfluencers!==j&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=j,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"applyFog",{get:function(){return this._internalAbstractMeshDataInfo._applyFog},set:function(j){this._internalAbstractMeshDataInfo._applyFog!==j&&(this._internalAbstractMeshDataInfo._applyFog=j,this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"layerMask",{get:function(){return this._internalAbstractMeshDataInfo._layerMask},set:function(j){j!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=j,this._resyncLightSources())},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"collisionMask",{get:function(){return this._meshCollisionData._collisionMask},set:function(j){this._meshCollisionData._collisionMask=isNaN(j)?-1:j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"collisionResponse",{get:function(){return this._meshCollisionData._collisionResponse},set:function(j){this._meshCollisionData._collisionResponse=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"collisionGroup",{get:function(){return this._meshCollisionData._collisionGroup},set:function(j){this._meshCollisionData._collisionGroup=isNaN(j)?-1:j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"surroundingMeshes",{get:function(){return this._meshCollisionData._surroundingMeshes},set:function(j){this._meshCollisionData._surroundingMeshes=j},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"lightSources",{get:function(){return this._lightSources},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"_positions",{get:function(){return null},enumerable:!1,configurable:!0}),Object.defineProperty(W.prototype,"skeleton",{get:function(){return this._internalAbstractMeshDataInfo._skeleton},set:function(j){var ne=this._internalAbstractMeshDataInfo._skeleton;ne&&ne.needInitialSkinMatrix&&ne._unregisterMeshWithPoseMatrix(this),j&&j.needInitialSkinMatrix&&j._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=j,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!1,configurable:!0}),W.prototype.getClassName=function(){return"AbstractMesh"},W.prototype.toString=function(j){var ne="Name: "+this.name+", isInstance: "+(this.getClassName()!=="InstancedMesh"?"YES":"NO");ne+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);var te=this._internalAbstractMeshDataInfo._skeleton;return te&&(ne+=", skeleton: "+te.name),j&&(ne+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],ne+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),ne},W.prototype._getEffectiveParent=function(){return this._masterMesh&&this.billboardMode!==m.a.BILLBOARDMODE_NONE?this._masterMesh:V.prototype._getEffectiveParent.call(this)},W.prototype._getActionManagerForTrigger=function(j,ne){if(ne===void 0&&(ne=!0),this.actionManager&&(ne||this.actionManager.isRecursive)){if(!j)return this.actionManager;if(this.actionManager.hasSpecificTrigger(j))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(j,!1):null},W.prototype._rebuild=function(){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes)for(var j=0,ne=this.subMeshes;j4,ae=pe?this.getVerticesData(R.b.MatricesIndicesExtraKind):null,ee=pe?this.getVerticesData(R.b.MatricesWeightsExtraKind):null;this.skeleton.prepare();for(var K=this.skeleton.getTransformMatrices(this),$=u.c.Vector3[0],L=u.c.Matrix[0],G=u.c.Matrix[1],Q=0,oe=0;oe0&&(u.a.FromFloat32ArrayToRefScaled(K,Math.floor(16*te[Q+re]),Y,G),L.addToSelf(G));if(pe)for(re=0;re<4;re++)(Y=ee[Q+re])>0&&(u.a.FromFloat32ArrayToRefScaled(K,Math.floor(16*ae[Q+re]),Y,G),L.addToSelf(G));u.e.TransformCoordinatesFromFloatsToRef(ne[oe],ne[oe+1],ne[oe+2],L,$),$.toArray(ne,oe),this._positions&&this._positions[oe/3].copyFrom($)}}}return ne},W.prototype._updateBoundingInfo=function(){var j=this._effectiveMesh;return this._boundingInfo?this._boundingInfo.update(j.worldMatrixFromCache):this._boundingInfo=new E.a(this.absolutePosition,this.absolutePosition,j.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(j.worldMatrixFromCache),this},W.prototype._updateSubMeshesBoundingInfo=function(j){if(!this.subMeshes)return this;for(var ne=this.subMeshes.length,te=0;te1||!de.IsGlobal)&&de.updateBoundingInfo(j)}return this},W.prototype._afterComputeWorldMatrix=function(){this.doNotSyncBoundingInfo||this._updateBoundingInfo()},Object.defineProperty(W.prototype,"_effectiveMesh",{get:function(){return this.skeleton&&this.skeleton.overrideMesh||this},enumerable:!1,configurable:!0}),W.prototype.isInFrustum=function(j){return this._boundingInfo!==null&&this._boundingInfo.isInFrustum(j,this.cullingStrategy)},W.prototype.isCompletelyInFrustum=function(j){return this._boundingInfo!==null&&this._boundingInfo.isCompletelyInFrustum(j)},W.prototype.intersectsMesh=function(j,ne,te){if(ne===void 0&&(ne=!1),!this._boundingInfo||!j._boundingInfo)return!1;if(this._boundingInfo.intersects(j._boundingInfo,ne))return!0;if(te){for(var de=0,pe=this.getChildMeshes();de1&&!ae._checkCollision(j)||this._collideForSubMesh(ae,ne,j)}return this},W.prototype._checkCollision=function(j){if(!this._boundingInfo||!this._boundingInfo._checkCollision(j))return this;var ne=u.c.Matrix[0],te=u.c.Matrix[1];return u.a.ScalingToRef(1/j._radius.x,1/j._radius.y,1/j._radius.z,ne),this.worldMatrixFromCache.multiplyToRef(ne,te),this._processCollisionsForSubMeshes(j,te),this},W.prototype._generatePointsArray=function(){return!1},W.prototype.intersects=function(j,ne,te,de,pe,ae){var ee;de===void 0&&(de=!1),ae===void 0&&(ae=!1);var K=new c.a,$=this.getClassName()==="InstancedLinesMesh"||this.getClassName()==="LinesMesh"?this.intersectionThreshold:0,L=this._boundingInfo;if(!this.subMeshes||!L||!(ae||j.intersectsSphere(L.boundingSphere,$)&&j.intersectsBox(L.boundingBox,$)))return K;if(de)return K.hit=!ae,K.pickedMesh=ae?null:this,K.distance=ae?0:u.e.Distance(j.origin,L.boundingSphere.center),K.subMeshId=0,K;if(!this._generatePointsArray())return K;for(var G=null,Q=this._scene.getIntersectingSubMeshCandidates(this,j),oe=Q.length,re=!1,Y=0;Y1)||H.canIntersects(j)){var Z=H.intersects(j,this._positions,this.getIndices(),ne,te);if(Z&&(ne||!G||Z.distance65535){ae=!0;break}j.depthSortedIndices=ae?new Uint32Array(te):new Uint16Array(te)}if(j.facetDepthSortFunction=function(re,Y){return Y.sqDistance-re.sqDistance},!j.facetDepthSortFrom){var K=this.getScene().activeCamera;j.facetDepthSortFrom=K?K.position:u.e.Zero()}j.depthSortedFacets=[];for(var $=0;$b.a?pe.maximum.x-pe.minimum.x:b.a,j.bbSize.y=pe.maximum.y-pe.minimum.y>b.a?pe.maximum.y-pe.minimum.y:b.a,j.bbSize.z=pe.maximum.z-pe.minimum.z>b.a?pe.maximum.z-pe.minimum.z:b.a;var G=j.bbSize.x>j.bbSize.y?j.bbSize.x:j.bbSize.y;if(G=G>j.bbSize.z?G:j.bbSize.z,j.subDiv.max=j.partitioningSubdivisions,j.subDiv.X=Math.floor(j.subDiv.max*j.bbSize.x/G),j.subDiv.Y=Math.floor(j.subDiv.max*j.bbSize.y/G),j.subDiv.Z=Math.floor(j.subDiv.max*j.bbSize.z/G),j.subDiv.X=j.subDiv.X<1?1:j.subDiv.X,j.subDiv.Y=j.subDiv.Y<1?1:j.subDiv.Y,j.subDiv.Z=j.subDiv.Z<1?1:j.subDiv.Z,j.facetParameters.facetNormals=this.getFacetLocalNormals(),j.facetParameters.facetPositions=this.getFacetLocalPositions(),j.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),j.facetParameters.bInfo=pe,j.facetParameters.bbSize=j.bbSize,j.facetParameters.subDiv=j.subDiv,j.facetParameters.ratio=this.partitioningBBoxRatio,j.facetParameters.depthSort=j.facetDepthSort,j.facetDepthSort&&j.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(j.invertedMatrix),u.e.TransformCoordinatesToRef(j.facetDepthSortFrom,j.invertedMatrix,j.facetDepthSortOrigin),j.facetParameters.distanceTo=j.facetDepthSortOrigin),j.facetParameters.depthSortedFacets=j.depthSortedFacets,C.a.ComputeNormals(ne,te,de,j.facetParameters),j.facetDepthSort&&j.facetDepthSortEnabled){j.depthSortedFacets.sort(j.facetDepthSortFunction);var Q=j.depthSortedIndices.length/3|0;for($=0;$pe.subDiv.max||ee<0||ee>pe.subDiv.max||K<0||K>pe.subDiv.max?null:pe.facetPartitioning[ae+pe.subDiv.max*ee+pe.subDiv.max*pe.subDiv.max*K]},W.prototype.getClosestFacetAtCoordinates=function(j,ne,te,de,pe,ae){pe===void 0&&(pe=!1),ae===void 0&&(ae=!0);var ee=this.getWorldMatrix(),K=u.c.Matrix[5];ee.invertToRef(K);var $=u.c.Vector3[8];u.e.TransformCoordinatesFromFloatsToRef(j,ne,te,K,$);var L=this.getClosestFacetAtLocalCoordinates($.x,$.y,$.z,de,pe,ae);return de&&u.e.TransformCoordinatesFromFloatsToRef(de.x,de.y,de.z,ee,de),L},W.prototype.getClosestFacetAtLocalCoordinates=function(j,ne,te,de,pe,ae){pe===void 0&&(pe=!1),ae===void 0&&(ae=!0);var ee=null,K=0,$=0,L=0,G=0,Q=0,oe=0,re=0,Y=0,k=this.getFacetLocalPositions(),H=this.getFacetLocalNormals(),Z=this.getFacetsAtLocalCoordinates(j,ne,te);if(!Z)return null;for(var X,q,he,ge=Number.MAX_VALUE,me=ge,_e=0;_e=0||pe&&!ae&&G<=0)&&(G=q.x*he.x+q.y*he.y+q.z*he.z,Q=-(q.x*j+q.y*ne+q.z*te-G)/(q.x*q.x+q.y*q.y+q.z*q.z),(me=(K=(oe=j+q.x*Q)-j)*K+($=(re=ne+q.y*Q)-ne)*$+(L=(Y=te+q.z*Q)-te)*L)100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=x.b.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new x.b),this._options.mass=S.mass===void 0?0:S.mass,this._options.friction=S.friction===void 0?.2:S.friction,this._options.restitution=S.restitution===void 0?.2:S.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=S.pressure===void 0?200:S.pressure,this._options.stiffness=S.stiffness===void 0?1:S.stiffness,this._options.velocityIterations=S.velocityIterations===void 0?20:S.velocityIterations,this._options.positionIterations=S.positionIterations===void 0?20:S.positionIterations,this._options.fixedPoints=S.fixedPoints===void 0?0:S.fixedPoints,this._options.margin=S.margin===void 0?0:S.margin,this._options.damping=S.damping===void 0?0:S.damping,this._options.path=S.path===void 0?null:S.path,this._options.shape=S.shape===void 0?null:S.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&B.a.Warn("You must affect impostors to children before affecting impostor to parent.")):B.a.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):B.a.Error("No object was provided. A physics object is obligatory")}return Object.defineProperty(c.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"mass",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0},set:function(E){this.setMass(E)},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"friction",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0},set:function(E){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,E)},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"restitution",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0},set:function(E){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,E)},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"pressure",{get:function(){if(!this._physicsEngine)return 0;var E=this._physicsEngine.getPhysicsPlugin();return E.setBodyPressure?E.getBodyPressure(this):0},set:function(E){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyPressure&&A.setBodyPressure(this,E)}},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"stiffness",{get:function(){if(!this._physicsEngine)return 0;var E=this._physicsEngine.getPhysicsPlugin();return E.getBodyStiffness?E.getBodyStiffness(this):0},set:function(E){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyStiffness&&A.setBodyStiffness(this,E)}},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"velocityIterations",{get:function(){if(!this._physicsEngine)return 0;var E=this._physicsEngine.getPhysicsPlugin();return E.getBodyVelocityIterations?E.getBodyVelocityIterations(this):0},set:function(E){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyVelocityIterations&&A.setBodyVelocityIterations(this,E)}},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"positionIterations",{get:function(){if(!this._physicsEngine)return 0;var E=this._physicsEngine.getPhysicsPlugin();return E.getBodyPositionIterations?E.getBodyPositionIterations(this):0},set:function(E){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyPositionIterations&&A.setBodyPositionIterations(this,E)}},enumerable:!1,configurable:!0}),c.prototype._init=function(){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))},c.prototype._getPhysicsParent=function(){return this.object.parent instanceof u.a?this.object.parent.physicsImpostor:null},c.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},c.prototype.setScalingUpdated=function(){this.forceUpdate()},c.prototype.forceUpdate=function(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()},Object.defineProperty(c.prototype,"physicsBody",{get:function(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody},set:function(E){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=E,this.resetUpdateFlags()},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"parent",{get:function(){return!this._options.ignoreParent&&this._parent?this._parent:null},set:function(E){this._parent=E},enumerable:!1,configurable:!0}),c.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},c.prototype.getObjectExtendSize=function(){if(this.object.getBoundingInfo){var E=this.object.rotationQuaternion,A=this.object.scaling.clone();this.object.rotationQuaternion=c.IDENTITY_QUATERNION;var S=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);S&&S.decompose(A,void 0,void 0);var g=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(A);return this.object.rotationQuaternion=E,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),g}return c.DEFAULT_OBJECT_SIZE},c.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position},c.prototype.getParam=function(E){return this._options[E]},c.prototype.setParam=function(E,A){this._options[E]=A,this._bodyUpdateRequired=!0},c.prototype.setMass=function(E){this.getParam("mass")!==E&&this.setParam("mass",E),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,E)},c.prototype.getLinearVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):x.e.Zero()},c.prototype.setLinearVelocity=function(E){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,E)},c.prototype.getAngularVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):x.e.Zero()},c.prototype.setAngularVelocity=function(E){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,E)},c.prototype.executeNativeFunction=function(E){this._physicsEngine&&E(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},c.prototype.registerBeforePhysicsStep=function(E){this._onBeforePhysicsStepCallbacks.push(E)},c.prototype.unregisterBeforePhysicsStep=function(E){var A=this._onBeforePhysicsStepCallbacks.indexOf(E);A>-1?this._onBeforePhysicsStepCallbacks.splice(A,1):B.a.Warn("Function to remove was not found")},c.prototype.registerAfterPhysicsStep=function(E){this._onAfterPhysicsStepCallbacks.push(E)},c.prototype.unregisterAfterPhysicsStep=function(E){var A=this._onAfterPhysicsStepCallbacks.indexOf(E);A>-1?this._onAfterPhysicsStepCallbacks.splice(A,1):B.a.Warn("Function to remove was not found")},c.prototype.registerOnPhysicsCollide=function(E,A){var S=E instanceof Array?E:[E];this._onPhysicsCollideCallbacks.push({callback:A,otherImpostors:S})},c.prototype.unregisterOnPhysicsCollide=function(E,A){var S=E instanceof Array?E:[E],g=-1;this._onPhysicsCollideCallbacks.some(function(l,h){if(l.callback===A&&l.otherImpostors.length===S.length){var b=l.otherImpostors.every(function(T){return S.indexOf(T)>-1});return b&&(g=h),b}return!1})?this._onPhysicsCollideCallbacks.splice(g,1):B.a.Warn("Function to remove was not found")},c.prototype.getParentsRotation=function(){var E=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);E;)E.rotationQuaternion?this._tmpQuat2.copyFrom(E.rotationQuaternion):x.b.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},c.prototype.applyForce=function(E,A){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,E,A),this},c.prototype.applyImpulse=function(E,A){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,E,A),this},c.prototype.createJoint=function(E,A,S){var g=new R.e(A,S);return this.addJoint(E,g),this},c.prototype.addJoint=function(E,A){return this._joints.push({otherImpostor:E,joint:A}),this._physicsEngine&&this._physicsEngine.addJoint(this,E,A),this},c.prototype.addAnchor=function(E,A,S,g,l){if(!this._physicsEngine)return this;var h=this._physicsEngine.getPhysicsPlugin();return h.appendAnchor?(this._physicsEngine&&h.appendAnchor(this,E,A,S,g,l),this):this},c.prototype.addHook=function(E,A,S,g){if(!this._physicsEngine)return this;var l=this._physicsEngine.getPhysicsPlugin();return l.appendAnchor?(this._physicsEngine&&l.appendHook(this,E,A,S,g),this):this},c.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},c.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},c.prototype.clone=function(E){return E?new c(E,this.type,this._options,this._scene):null},c.prototype.dispose=function(){var E=this;this._physicsEngine&&(this._joints.forEach(function(A){E._physicsEngine&&E._physicsEngine.removeJoint(E,A.otherImpostor,A.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},c.prototype.setDeltaPosition=function(E){this._deltaPosition.copyFrom(E)},c.prototype.setDeltaRotation=function(E){this._deltaRotation||(this._deltaRotation=new x.b),this._deltaRotation.copyFrom(E),this._deltaRotationConjugated=this._deltaRotation.conjugate()},c.prototype.getBoxSizeToRef=function(E){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,E),this},c.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},c.prototype.syncBoneWithImpostor=function(E,A,S,g,l){var h=c._tmpVecs[0],b=this.object;if(b.rotationQuaternion)if(l){var T=c._tmpQuat;b.rotationQuaternion.multiplyToRef(l,T),E.setRotationQuaternion(T,C.c.WORLD,A)}else E.setRotationQuaternion(b.rotationQuaternion,C.c.WORLD,A);h.x=0,h.y=0,h.z=0,S&&(h.x=S.x,h.y=S.y,h.z=S.z,E.getDirectionToRef(h,A,h),g==null&&(g=S.length()),h.x*=g,h.y*=g,h.z*=g),E.getParent()?(h.addInPlace(b.getAbsolutePosition()),E.setAbsolutePosition(h,A)):(A.setAbsolutePosition(b.getAbsolutePosition()),A.position.x-=h.x,A.position.y-=h.y,A.position.z-=h.z)},c.prototype.syncImpostorWithBone=function(E,A,S,g,l,h){var b=this.object;if(b.rotationQuaternion)if(l){var T=c._tmpQuat;E.getRotationQuaternionToRef(C.c.WORLD,A,T),T.multiplyToRef(l,b.rotationQuaternion)}else E.getRotationQuaternionToRef(C.c.WORLD,A,b.rotationQuaternion);var D=c._tmpVecs[0],w=c._tmpVecs[1];h||((h=c._tmpVecs[2]).x=0,h.y=1,h.z=0),E.getDirectionToRef(h,A,w),E.getAbsolutePositionToRef(A,D),g==null&&S&&(g=S.length()),g!=null&&(D.x+=w.x*g,D.y+=w.y*g,D.z+=w.z*g),b.setAbsolutePosition(D)},c.DEFAULT_OBJECT_SIZE=new x.e(1,1,1),c.IDENTITY_QUATERNION=x.b.Identity(),c._tmpVecs=_.a.BuildArray(3,x.e.Zero),c._tmpQuat=x.b.Identity(),c.NoImpostor=0,c.SphereImpostor=1,c.BoxImpostor=2,c.PlaneImpostor=3,c.MeshImpostor=4,c.CapsuleImpostor=6,c.CylinderImpostor=7,c.ParticleImpostor=8,c.HeightmapImpostor=9,c.ConvexHullImpostor=10,c.CustomImpostor=100,c.RopeImpostor=101,c.ClothImpostor=102,c.SoftbodyImpostor=103,c}()},function(Ae,v,f){f.d(v,"a",function(){return _}),f.d(v,"b",function(){return x});var B=f(1),_=function(){function u(M){this.length=0,this.data=new Array(M),this._id=u._GlobalId++}return u.prototype.push=function(M){this.data[this.length++]=M,this.length>this.data.length&&(this.data.length*=2)},u.prototype.forEach=function(M){for(var R=0;Rthis.data.length&&(this.data.length=2*(this.length+M.length));for(var R=0;R=this.length?-1:R},u.prototype.contains=function(M){return this.indexOf(M)!==-1},u._GlobalId=0,u}(),x=function(u){function M(){var R=u!==null&&u.apply(this,arguments)||this;return R._duplicateId=0,R}return Object(B.d)(M,u),M.prototype.push=function(R){u.prototype.push.call(this,R),R.__smartArrayFlags||(R.__smartArrayFlags={}),R.__smartArrayFlags[this._id]=this._duplicateId},M.prototype.pushNoDuplicate=function(R){return(!R.__smartArrayFlags||R.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(R),!0)},M.prototype.reset=function(){u.prototype.reset.call(this),this._duplicateId++},M.prototype.concatWithNoDuplicate=function(R){if(R.length!==0){this.length+R.length>this.data.length&&(this.data.length=2*(this.length+R.length));for(var C=0;C>2,m=(3&u)<<4|(M=g>4,c=(15&M)<<2|(R=g>6,E=63&R,isNaN(M)?c=E=64:isNaN(R)&&(E=64),S+=A.charAt(C)+A.charAt(m)+A.charAt(c)+A.charAt(E);return S},_.PadNumber=function(x,u){for(var M=String(x);M.length0)):!S._pointerCaptures[D.pointerId]&&b.distance>T.distance&&(S.mainSceneTrackerPredicate&&S.mainSceneTrackerPredicate(T.pickedMesh)?(S._notifyObservers(g,T,D),g.skipOnPointerObservable=!0):S._lastPointerEvents[D.pointerId]&&(S.onPointerOutObservable.notifyObservers(D.pointerId),delete S._lastPointerEvents[D.pointerId])),g.type===x.a.POINTERUP&&S._pointerCaptures[D.pointerId]&&(S._pointerCaptures[D.pointerId]=!1))}}}}),this._originalPointerObserver&&E.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterCameraRenderObservable.add(function(g){S.shouldRender&&g==S.getRenderCamera()&&S.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(function(){S.dispose()}),this._updateCamera()}return c.prototype.getRenderCamera=function(E){if(this._renderCamera)return this._renderCamera;var A=void 0;return A=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,E&&A&&A.isRigCamera?A.rigParent:A},c.prototype.setRenderCamera=function(E){this._renderCamera=E},c.prototype._getSharedGizmoLight=function(){return this._sharedGizmoLight||(this._sharedGizmoLight=new M.a("shared gizmo light",new R.e(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=C.a.Gray()),this._sharedGizmoLight},Object.defineProperty(c,"DefaultUtilityLayer",{get:function(){return c._DefaultUtilityLayer==null&&(c._DefaultUtilityLayer=new c(u.a.LastCreatedScene),c._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){c._DefaultUtilityLayer=null})),c._DefaultUtilityLayer},enumerable:!1,configurable:!0}),Object.defineProperty(c,"DefaultKeepDepthUtilityLayer",{get:function(){return c._DefaultKeepDepthUtilityLayer==null&&(c._DefaultKeepDepthUtilityLayer=new c(u.a.LastCreatedScene),c._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,c._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){c._DefaultKeepDepthUtilityLayer=null})),c._DefaultKeepDepthUtilityLayer},enumerable:!1,configurable:!0}),c.prototype._notifyObservers=function(E,A,S){E.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new x.b(E.type,E.event,A),E.type),this._lastPointerEvents[S.pointerId]=!0)},c.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var E=this.utilityLayerScene.activeCamera.getScene(),A=this.utilityLayerScene.activeCamera;A._scene=this.utilityLayerScene,A.leftCamera&&(A.leftCamera._scene=this.utilityLayerScene),A.rightCamera&&(A.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),A._scene=E,A.leftCamera&&(A.leftCamera._scene=E),A.rightCamera&&(A.rightCamera._scene=E)}},c.prototype.dispose=function(){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()},c.prototype._updateCamera=function(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()},c._DefaultUtilityLayer=null,c._DefaultKeepDepthUtilityLayer=null,c}()},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(139),_=function(){function x(){}return x.EnableFor=function(u){u._tags=u._tags||{},u.hasTags=function(){return x.HasTags(u)},u.addTags=function(M){return x.AddTagsTo(u,M)},u.removeTags=function(M){return x.RemoveTagsFrom(u,M)},u.matchesTagsQuery=function(M){return x.MatchesQuery(u,M)}},x.DisableFor=function(u){delete u._tags,delete u.hasTags,delete u.addTags,delete u.removeTags,delete u.matchesTagsQuery},x.HasTags=function(u){if(!u._tags)return!1;var M=u._tags;for(var R in M)if(M.hasOwnProperty(R))return!0;return!1},x.GetTags=function(u,M){if(M===void 0&&(M=!0),!u._tags)return null;if(M){var R=[];for(var C in u._tags)u._tags.hasOwnProperty(C)&&u._tags[C]===!0&&R.push(C);return R.join(" ")}return u._tags},x.AddTagsTo=function(u,M){M&&typeof M=="string"&&M.split(" ").forEach(function(R,C,m){x._AddTagTo(u,R)})},x._AddTagTo=function(u,M){(M=M.trim())!==""&&M!=="true"&&M!=="false"&&(M.match(/[\s]/)||M.match(/^([!]|([|]|[&]){2})/)||(x.EnableFor(u),u._tags[M]=!0))},x.RemoveTagsFrom=function(u,M){if(x.HasTags(u)){var R=M.split(" ");for(var C in R)x._RemoveTagFrom(u,R[C])}},x._RemoveTagFrom=function(u,M){delete u._tags[M]},x.MatchesQuery=function(u,M){return M===void 0||(M===""?x.HasTags(u):B.a.Eval(M,function(R){return x.HasTags(u)&&u._tags[R]}))},x}()},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){}return _.IsWindowObjectExist=function(){return typeof window<"u"},_.IsNavigatorAvailable=function(){return typeof navigator<"u"},_.IsDocumentAvailable=function(){return typeof document<"u"},_.GetDOMTextContent=function(x){for(var u="",M=x.firstChild;M;)M.nodeType===3&&(u+=M.textContent),M=M.nextSibling;return u},_}()},function(Ae,v,f){f.d(v,"a",function(){return C});var B=f(44),_=f(0),x=f(54),u=f(114),M=f(20),R=f(24),C=function(){function m(c,E,A){A===void 0&&(A=Number.MAX_VALUE),this.origin=c,this.direction=E,this.length=A}return m.prototype.intersectsBoxMinMax=function(c,E,A){A===void 0&&(A=0);var S,g,l,h,b=m._TmpVector3[0].copyFromFloats(c.x-A,c.y-A,c.z-A),T=m._TmpVector3[1].copyFromFloats(E.x+A,E.y+A,E.z+A),D=0,w=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xT.x)return!1}else if(S=1/this.direction.x,g=(b.x-this.origin.x)*S,(l=(T.x-this.origin.x)*S)===-1/0&&(l=1/0),g>l&&(h=g,g=l,l=h),(D=Math.max(g,D))>(w=Math.min(l,w)))return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yT.y)return!1}else if(S=1/this.direction.y,g=(b.y-this.origin.y)*S,(l=(T.y-this.origin.y)*S)===-1/0&&(l=1/0),g>l&&(h=g,g=l,l=h),(D=Math.max(g,D))>(w=Math.min(l,w)))return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zT.z)return!1}else if(S=1/this.direction.z,g=(b.z-this.origin.z)*S,(l=(T.z-this.origin.z)*S)===-1/0&&(l=1/0),g>l&&(h=g,g=l,l=h),(D=Math.max(g,D))>(w=Math.min(l,w)))return!1;return!0},m.prototype.intersectsBox=function(c,E){return E===void 0&&(E=0),this.intersectsBoxMinMax(c.minimum,c.maximum,E)},m.prototype.intersectsSphere=function(c,E){E===void 0&&(E=0);var A=c.center.x-this.origin.x,S=c.center.y-this.origin.y,g=c.center.z-this.origin.z,l=A*A+S*S+g*g,h=c.radius+E,b=h*h;if(l<=b)return!0;var T=A*this.direction.x+S*this.direction.y+g*this.direction.z;return!(T<0)&&l-T*T<=b},m.prototype.intersectsTriangle=function(c,E,A){var S=m._TmpVector3[0],g=m._TmpVector3[1],l=m._TmpVector3[2],h=m._TmpVector3[3],b=m._TmpVector3[4];E.subtractToRef(c,S),A.subtractToRef(c,g),_.e.CrossToRef(this.direction,g,l);var T=_.e.Dot(S,l);if(T===0)return null;var D=1/T;this.origin.subtractToRef(c,h);var w=_.e.Dot(h,l)*D;if(w<0||w>1)return null;_.e.CrossToRef(h,S,b);var N=_.e.Dot(this.direction,b)*D;if(N<0||w+N>1)return null;var I=_.e.Dot(g,b)*D;return I>this.length?null:new u.a(1-w-N,w,I)},m.prototype.intersectsPlane=function(c){var E,A=_.e.Dot(c.normal,this.direction);if(Math.abs(A)<999999997475243e-21)return null;var S=_.e.Dot(c.normal,this.origin);return(E=(-c.d-S)/A)<0?E<-999999997475243e-21?null:0:E},m.prototype.intersectsAxis=function(c,E){switch(E===void 0&&(E=0),c){case"y":return(A=(this.origin.y-E)/this.direction.y)>0?null:new _.e(this.origin.x+this.direction.x*-A,E,this.origin.z+this.direction.z*-A);case"x":return(A=(this.origin.x-E)/this.direction.x)>0?null:new _.e(E,this.origin.y+this.direction.y*-A,this.origin.z+this.direction.z*-A);case"z":var A;return(A=(this.origin.z-E)/this.direction.z)>0?null:new _.e(this.origin.x+this.direction.x*-A,this.origin.y+this.direction.y*-A,E);default:return null}},m.prototype.intersectsMesh=function(c,E){var A=_.c.Matrix[0];return c.getWorldMatrix().invertToRef(A),this._tmpRay?m.TransformToRef(this,A,this._tmpRay):this._tmpRay=m.Transform(this,A),c.intersects(this._tmpRay,E)},m.prototype.intersectsMeshes=function(c,E,A){A?A.length=0:A=[];for(var S=0;SE.distance?1:0},m.prototype.intersectionSegment=function(c,E,A){var S=this.origin,g=_.c.Vector3[0],l=_.c.Vector3[1],h=_.c.Vector3[2],b=_.c.Vector3[3];E.subtractToRef(c,g),this.direction.scaleToRef(m.rayl,h),S.addToRef(h,l),c.subtractToRef(S,b);var T,D,w,N,I=_.e.Dot(g,g),V=_.e.Dot(g,h),W=_.e.Dot(h,h),j=_.e.Dot(g,b),ne=_.e.Dot(h,b),te=I*W-V*V,de=te,pe=te;tede&&(D=de,N=ne+V,pe=W)),N<0?(N=0,-j<0?D=0:-j>I?D=de:(D=-j,de=I)):N>pe&&(N=pe,-j+V<0?D=0:-j+V>I?D=de:(D=-j+V,de=I)),T=Math.abs(D)0&&w<=this.length&&K.lengthSquared()=m.distance?null:T:null},M.a.prototype._internalPick=function(m,c,E,A,S){if(!x.a)return null;for(var g=null,l=0;l0&&(m.push(g-1),m.push(g)),g++}var D=new x.a;return D.indices=m,D.positions=c,A&&(D.colors=S),D},x.a.CreateDashedLines=function(C){var m,c,E=C.dashSize||3,A=C.gapSize||1,S=C.dashNb||200,g=C.points,l=new Array,h=new Array,b=B.e.Zero(),T=0,D=0,w=0,N=0,I=0;for(I=0;I0)if(typeof g[0]=="object")for(var h=0;hC.max||C.min>R.max)},E=function(){function A(S,g,l){this._isLocked=!1,this.boundingBox=new u.a(S,g,l),this.boundingSphere=new M.a(S,g,l)}return A.prototype.reConstruct=function(S,g,l){this.boundingBox.reConstruct(S,g,l),this.boundingSphere.reConstruct(S,g,l)},Object.defineProperty(A.prototype,"minimum",{get:function(){return this.boundingBox.minimum},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"maximum",{get:function(){return this.boundingBox.maximum},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"isLocked",{get:function(){return this._isLocked},set:function(S){this._isLocked=S},enumerable:!1,configurable:!0}),A.prototype.update=function(S){this._isLocked||(this.boundingBox._update(S),this.boundingSphere._update(S))},A.prototype.centerOn=function(S,g){var l=A.TmpVector3[0].copyFrom(S).subtractInPlace(g),h=A.TmpVector3[1].copyFrom(S).addInPlace(g);return this.boundingBox.reConstruct(l,h,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(l,h,this.boundingBox.getWorldMatrix()),this},A.prototype.scale=function(S){return this.boundingBox.scale(S),this.boundingSphere.scale(S),this},A.prototype.isInFrustum=function(S,g){return g===void 0&&(g=x.a.MESHES_CULLINGSTRATEGY_STANDARD),!(g!==x.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION&&g!==x.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY||!this.boundingSphere.isCenterInFrustum(S))||!!this.boundingSphere.isInFrustum(S)&&(!(g!==x.a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&g!==x.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(S))},Object.defineProperty(A.prototype,"diagonalLength",{get:function(){var S=this.boundingBox;return S.maximumWorld.subtractToRef(S.minimumWorld,A.TmpVector3[0]).length()},enumerable:!1,configurable:!0}),A.prototype.isCompletelyInFrustum=function(S){return this.boundingBox.isCompletelyInFrustum(S)},A.prototype._checkCollision=function(S){return S._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},A.prototype.intersectsPoint=function(S){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(S)&&!!this.boundingBox.intersectsPoint(S)},A.prototype.intersects=function(S,g){if(!M.a.Intersects(this.boundingSphere,S.boundingSphere)||!u.a.Intersects(this.boundingBox,S.boundingBox))return!1;if(!g)return!0;var l=this.boundingBox,h=S.boundingBox;return!!c(l.directions[0],l,h)&&!!c(l.directions[1],l,h)&&!!c(l.directions[2],l,h)&&!!c(h.directions[0],l,h)&&!!c(h.directions[1],l,h)&&!!c(h.directions[2],l,h)&&!!c(_.e.Cross(l.directions[0],h.directions[0]),l,h)&&!!c(_.e.Cross(l.directions[0],h.directions[1]),l,h)&&!!c(_.e.Cross(l.directions[0],h.directions[2]),l,h)&&!!c(_.e.Cross(l.directions[1],h.directions[0]),l,h)&&!!c(_.e.Cross(l.directions[1],h.directions[1]),l,h)&&!!c(_.e.Cross(l.directions[1],h.directions[2]),l,h)&&!!c(_.e.Cross(l.directions[2],h.directions[0]),l,h)&&!!c(_.e.Cross(l.directions[2],h.directions[1]),l,h)&&!!c(_.e.Cross(l.directions[2],h.directions[2]),l,h)},A.TmpVector3=B.a.BuildArray(2,_.e.Zero),A}()},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){}return _.BuildArray=function(x,u){for(var M=[],R=0;R1)?1:M.arc||1,A=M.slice&&M.slice<=0?1:M.slice||1,S=M.sideOrientation===0?0:M.sideOrientation||x.a.DEFAULTSIDE,g=!!M.dedupTopBottomIndices,l=new B.e(C/2,m/2,c/2),h=2+R,b=2*h,T=[],D=[],w=[],N=[],I=0;I<=h;I++){for(var V=I/h,W=V*Math.PI*A,j=0;j<=b;j++){var ne=j/b,te=ne*Math.PI*2*E,de=B.a.RotationZ(-W),pe=B.a.RotationY(te),ae=B.e.TransformCoordinates(B.e.Up(),de),ee=B.e.TransformCoordinates(ae,pe),K=ee.multiply(l),$=ee.divide(l).normalize();D.push(K.x,K.y,K.z),w.push($.x,$.y,$.z),N.push(ne,V)}if(I>0)for(var L=D.length/3,G=L-2*(b+1);G+b+21&&(T.push(G),T.push(G+1),T.push(G+b+1)),(I0&&this.includedOnlyMeshes.indexOf(A)===-1)&&!(this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(A)!==-1)&&(this.includeOnlyWithLayerMask===0||(this.includeOnlyWithLayerMask&A.layerMask)!=0)&&!(this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&A.layerMask)},E.CompareLightsPriority=function(A,S){return A.shadowEnabled!==S.shadowEnabled?(S.shadowEnabled?1:0)-(A.shadowEnabled?1:0):S.renderPriority-A.renderPriority},E.prototype.dispose=function(A,S){S===void 0&&(S=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var g=0,l=this.getScene().meshes;g0&&(A.excludedMeshesIds=[],this.excludedMeshes.forEach(function(S){A.excludedMeshesIds.push(S.id)})),this.includedOnlyMeshes.length>0&&(A.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(function(S){A.includedOnlyMeshesIds.push(S.id)})),_.a.AppendSerializedAnimations(this,A),A.ranges=this.serializeAnimationRanges(),A},E.GetConstructorFromName=function(A,S,g){var l=M.a.Construct("Light_Type_"+A,S,g);return l||null},E.Parse=function(A,S){var g=E.GetConstructorFromName(A.type,A.name,S);if(!g)return null;var l=_.a.Parse(g,A,S);if(A.excludedMeshesIds&&(l._excludedMeshesIds=A.excludedMeshesIds),A.includedOnlyMeshesIds&&(l._includedOnlyMeshesIds=A.includedOnlyMeshesIds),A.parentId&&(l._waitingParentId=A.parentId),A.falloffType!==void 0&&(l.falloffType=A.falloffType),A.lightmapMode!==void 0&&(l.lightmapMode=A.lightmapMode),A.animations){for(var h=0;h=0&&this._scene.textures.splice(S,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),E.prototype.dispose.call(this)},A.prototype.serialize=function(){if(!this.name)return null;var S=_.a.Serialize(this);return _.a.AppendSerializedAnimations(this,S),S},A.WhenAllReady=function(S,g){var l=S.length;if(l!==0)for(var h=0;h1)?1:m.arc||1,w=m.sideOrientation===0?0:m.sideOrientation||u.a.DEFAULTSIDE,N=m.faceUV||new Array(3),I=m.faceColors,V=2+(1+(D!==1&&b?2:0))*(h?l:1);for(S=0;S1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=u,this._lastSecAccumulated=0,this._lastSecValueCount=0)},x.Enabled=!0,x}()},function(Ae,v,f){f.d(v,"b",function(){return A}),f.d(v,"d",function(){return S}),f.d(v,"c",function(){return g}),f.d(v,"a",function(){return l});var B=f(1),_=f(49),x=f(38),u=f(6),M=f(83),R=f(140),C=function(h){function b(){return h!==null&&h.apply(this,arguments)||this}return Object(B.d)(b,h),b._setPrototypeOf=Object.setPrototypeOf||function(T,D){return T.__proto__=D,T},b}(Error),m=f(34),c=f(26),E=f(128),A=function(h){function b(T,D){var w=h.call(this,T)||this;return w.name="LoadFileError",C._setPrototypeOf(w,b.prototype),D instanceof _.a?w.request=D:w.file=D,w}return Object(B.d)(b,h),b}(C),S=function(h){function b(T,D){var w=h.call(this,T)||this;return w.request=D,w.name="RequestFileError",C._setPrototypeOf(w,b.prototype),w}return Object(B.d)(b,h),b}(C),g=function(h){function b(T,D){var w=h.call(this,T)||this;return w.file=D,w.name="ReadFileError",C._setPrototypeOf(w,b.prototype),w}return Object(B.d)(b,h),b}(C),l=function(){function h(){}return h._CleanUrl=function(b){return b=b.replace(/#/gm,"%23")},h.SetCorsBehavior=function(b,T){if((!b||b.indexOf("data:")!==0)&&h.CorsBehavior)if(typeof h.CorsBehavior=="string"||this.CorsBehavior instanceof String)T.crossOrigin=h.CorsBehavior;else{var D=h.CorsBehavior(b);D&&(T.crossOrigin=D)}},h.LoadImage=function(b,T,D,w,N){var I;N===void 0&&(N="");var V=!1;if(b instanceof ArrayBuffer||ArrayBuffer.isView(b)?typeof Blob<"u"?(I=URL.createObjectURL(new Blob([b],{type:N})),V=!0):I="data:"+N+";base64,"+m.a.EncodeArrayBufferToBase64(b):b instanceof Blob?(I=URL.createObjectURL(b),V=!0):(I=h._CleanUrl(b),I=h.PreprocessUrl(b)),typeof Image>"u")return h.LoadFile(I,function(ae){createImageBitmap(new Blob([ae],{type:N})).then(function(ee){T(ee),V&&URL.revokeObjectURL(I)}).catch(function(ee){D&&D("Error while trying to load image: "+b,ee)})},void 0,w||void 0,!0,function(ae,ee){D&&D("Error while trying to load image: "+b,ee)}),null;var W=new Image;h.SetCorsBehavior(I,W);var j=function(){W.removeEventListener("load",j),W.removeEventListener("error",ne),T(W),V&&W.src&&URL.revokeObjectURL(W.src)},ne=function(ae){if(W.removeEventListener("load",j),W.removeEventListener("error",ne),D){var ee=b.toString();D("Error while trying to load image: "+(ee.length<32?ee:ee.slice(0,32)+"..."),ae)}V&&W.src&&URL.revokeObjectURL(W.src)};W.addEventListener("load",j),W.addEventListener("error",ne);var te=function(){W.src=I};if(I.substr(0,5)!=="data:"&&w&&w.enableTexturesOffline)w.open(function(){w&&w.loadImage(I,W)},te);else{if(I.indexOf("file:")!==-1){var de=decodeURIComponent(I.substring(5).toLowerCase());if(M.a.FilesToLoad[de]){try{var pe;try{pe=URL.createObjectURL(M.a.FilesToLoad[de])}catch{pe=URL.createObjectURL(M.a.FilesToLoad[de])}W.src=pe,V=!0}catch{W.src=""}return W}}te()}return W},h.ReadFile=function(b,T,D,w,N){var I=new FileReader,V={onCompleteObservable:new u.c,abort:function(){return I.abort()}};return I.onloadend=function(W){return V.onCompleteObservable.notifyObservers(V)},N&&(I.onerror=function(W){N(new g("Unable to read "+b.name,b))}),I.onload=function(W){T(W.target.result)},D&&(I.onprogress=D),w?I.readAsArrayBuffer(b):I.readAsText(b),V},h.LoadFile=function(b,T,D,w,N,I){if(b.indexOf("file:")!==-1){var V=decodeURIComponent(b.substring(5).toLowerCase());V.indexOf("./")===0&&(V=V.substring(2));var W=M.a.FilesToLoad[V];if(W)return h.ReadFile(W,T,D,N,I?function(j){return I(void 0,new A(j.message,j.file))}:void 0)}return h.RequestFile(b,function(j,ne){T(j,ne?ne.responseURL:void 0)},D,w,N,I?function(j){I(j.request,new A(j.message,j.request))}:void 0)},h.RequestFile=function(b,T,D,w,N,I,V){b=h._CleanUrl(b),b=h.PreprocessUrl(b);var W=h.BaseUrl+b,j=!1,ne={onCompleteObservable:new u.c,abort:function(){return j=!0}},te=function(){var pe=new _.a,ae=null;ne.abort=function(){j=!0,pe.readyState!==(XMLHttpRequest.DONE||4)&&pe.abort(),ae!==null&&(clearTimeout(ae),ae=null)};var ee=function(K){pe.open("GET",W),V&&V(pe),N&&(pe.responseType="arraybuffer"),D&&pe.addEventListener("progress",D);var $=function(){pe.removeEventListener("loadend",$),ne.onCompleteObservable.notifyObservers(ne),ne.onCompleteObservable.clear()};pe.addEventListener("loadend",$);var L=function(){if(!j&&pe.readyState===(XMLHttpRequest.DONE||4)){if(pe.removeEventListener("readystatechange",L),pe.status>=200&&pe.status<300||pe.status===0&&(!x.a.IsWindowObjectExist()||h.IsFileURL()))return void T(N?pe.response:pe.responseText,pe);var G=h.DefaultRetryStrategy;if(G){var Q=G(W,pe,K);if(Q!==-1)return pe.removeEventListener("loadend",$),pe=new _.a,void(ae=setTimeout(function(){return ee(K+1)},Q))}var oe=new S("Error status: "+pe.status+" "+pe.statusText+" - Unable to load "+W,pe);I&&I(oe)}};pe.addEventListener("readystatechange",L),pe.send()};ee(0)};if(w&&w.enableSceneOffline){var de=function(pe){pe&&pe.status>400?I&&I(pe):te()};w.open(function(){w&&w.loadFile(h.BaseUrl+b,function(pe){j||T(pe),ne.onCompleteObservable.notifyObservers(ne)},D?function(pe){j||D(pe)}:void 0,de,N)},de)}else te();return ne},h.IsFileURL=function(){return typeof location<"u"&&location.protocol==="file:"},h.DefaultRetryStrategy=R.a.ExponentialBackoff(),h.BaseUrl="",h.CorsBehavior="anonymous",h.PreprocessUrl=function(b){return b},h}();c.a._FileToolsLoadImage=l.LoadImage.bind(l),c.a._FileToolsLoadFile=l.LoadFile.bind(l),E.a._FileToolsLoadFile=l.LoadFile.bind(l)},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(38),_=function(){function x(){}return Object.defineProperty(x,"Now",{get:function(){return B.a.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!1,configurable:!0}),x}()},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(x,u,M,R){this.x=x,this.y=u,this.width=M,this.height=R}return _.prototype.toGlobal=function(x,u){return new _(this.x*x,this.y*u,this.width*x,this.height*u)},_.prototype.toGlobalToRef=function(x,u,M){return M.x=this.x*x,M.y=this.y*u,M.width=this.width*x,M.height=this.height*u,this},_.prototype.clone=function(){return new _(this.x,this.y,this.width,this.height)},_}()},function(Ae,v,f){var B="helperFunctions",_=`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; -} -float toLinearSpace(float color) -{ -return pow(color,LinearEncodePowerApprox); -} -vec3 toLinearSpace(vec3 color) -{ -return pow(color,vec3(LinearEncodePowerApprox)); -} -vec4 toLinearSpace(vec4 color) -{ -return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); -} -vec3 toGammaSpace(vec3 color) -{ -return pow(color,vec3(GammaEncodePowerApprox)); -} -vec4 toGammaSpace(vec4 color) -{ -return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); -} -float toGammaSpace(float color) -{ -return pow(color,GammaEncodePowerApprox); -} -float square(float 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 dither=mix(-varianceAmount/255.0,varianceAmount/255.0,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(rgb,D); -} -vec3 fromRGBD(vec4 rgbd) { - -rgbd.rgb=toLinearSpace(rgbd.rgb); - -return rgbd.rgb/rgbd.a; -} -`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(0),_=function(){function x(){}return x._RemoveAndStorePivotPoint=function(u){u&&x._PivotCached===0&&(u.getPivotPointToRef(x._OldPivotPoint),x._PivotPostMultiplyPivotMatrix=u._postMultiplyPivotMatrix,x._OldPivotPoint.equalsToFloats(0,0,0)||(u.setPivotMatrix(B.a.IdentityReadOnly),x._OldPivotPoint.subtractToRef(u.getPivotPoint(),x._PivotTranslation),x._PivotTmpVector.copyFromFloats(1,1,1),x._PivotTmpVector.subtractInPlace(u.scaling),x._PivotTmpVector.multiplyInPlace(x._PivotTranslation),u.position.addInPlace(x._PivotTmpVector))),x._PivotCached++},x._RestorePivotPoint=function(u){u&&!x._OldPivotPoint.equalsToFloats(0,0,0)&&x._PivotCached===1&&(u.setPivotPoint(x._OldPivotPoint),u._postMultiplyPivotMatrix=x._PivotPostMultiplyPivotMatrix,x._PivotTmpVector.copyFromFloats(1,1,1),x._PivotTmpVector.subtractInPlace(u.scaling),x._PivotTmpVector.multiplyInPlace(x._PivotTranslation),u.position.subtractInPlace(x._PivotTmpVector)),this._PivotCached--},x._PivotCached=0,x._OldPivotPoint=new B.e,x._PivotTranslation=new B.e,x._PivotTmpVector=new B.e,x._PivotPostMultiplyPivotMatrix=!1,x}()},function(Ae,v,f){f.d(v,"a",function(){return R});var B=f(4),_=f(114),x=f(43),u=f(2),M=f(101),R=function(){function C(m,c,E,A,S,g,l,h,b){h===void 0&&(h=!0),b===void 0&&(b=!0),this.materialIndex=m,this.verticesStart=c,this.verticesCount=E,this.indexStart=A,this.indexCount=S,this._materialDefines=null,this._materialEffect=null,this._effectOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=g,this._renderingMesh=l||g,b&&g.subMeshes.push(this),this._trianglePlanes=[],this._id=g.subMeshes.length-1,h&&(this.refreshBoundingInfo(),g.computeWorldMatrix(!0))}return Object.defineProperty(C.prototype,"materialDefines",{get:function(){return this._materialDefines},set:function(m){this._materialDefines=m},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"effect",{get:function(){var m;return(m=this._effectOverride)!==null&&m!==void 0?m:this._materialEffect},enumerable:!1,configurable:!0}),C.prototype.setEffect=function(m,c){c===void 0&&(c=null),this._materialEffect!==m?(this._materialDefines=c,this._materialEffect=m):m||(this._materialDefines=null)},C.AddToMesh=function(m,c,E,A,S,g,l,h){return h===void 0&&(h=!0),new C(m,c,E,A,S,g,l,h)},Object.defineProperty(C.prototype,"IsGlobal",{get:function(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()},enumerable:!1,configurable:!0}),C.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},C.prototype.setBoundingInfo=function(m){return this._boundingInfo=m,this},C.prototype.getMesh=function(){return this._mesh},C.prototype.getRenderingMesh=function(){return this._renderingMesh},C.prototype.getReplacementMesh=function(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null},C.prototype.getEffectiveMesh=function(){var m=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return m||this._renderingMesh},C.prototype.getMaterial=function(){var m=this._renderingMesh.material;if(m==null)return this._mesh.getScene().defaultMaterial;if(this._IsMultiMaterial(m)){var c=m.getSubMaterial(this.materialIndex);return this._currentMaterial!==c&&(this._currentMaterial=c,this._materialDefines=null),c}return m},C.prototype._IsMultiMaterial=function(m){return m.getSubMaterial!==void 0},C.prototype.refreshBoundingInfo=function(m){if(m===void 0&&(m=null),this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(m||(m=this._renderingMesh.getVerticesData(B.b.PositionKind)),!m)return this._boundingInfo=this._mesh.getBoundingInfo(),this;var c,E=this._renderingMesh.getIndices();if(this.indexStart===0&&this.indexCount===E.length){var A=this._renderingMesh.getBoundingInfo();c={minimum:A.minimum.clone(),maximum:A.maximum.clone()}}else c=Object(M.b)(m,E,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(c.minimum,c.maximum):this._boundingInfo=new x.a(c.minimum,c.maximum),this},C.prototype._checkCollision=function(m){return this.getBoundingInfo()._checkCollision(m)},C.prototype.updateBoundingInfo=function(m){var c=this.getBoundingInfo();return c||(this.refreshBoundingInfo(),c=this.getBoundingInfo()),c&&c.update(m),this},C.prototype.isInFrustum=function(m){var c=this.getBoundingInfo();return!!c&&c.isInFrustum(m,this._mesh.cullingStrategy)},C.prototype.isCompletelyInFrustum=function(m){var c=this.getBoundingInfo();return!!c&&c.isCompletelyInFrustum(m)},C.prototype.render=function(m){return this._renderingMesh.render(this,m,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this},C.prototype._getLinesIndexBuffer=function(m,c){if(!this._linesIndexBuffer){for(var E=[],A=this.indexStart;Al&&(l=T)}return new C(m,g,l-g+1,c,E,A,S)},C}()},function(Ae,v,f){f.d(v,"a",function(){return R});var B=f(1),_=f(8),x=f(10),u=f(2),M=(f(126),f(70)),R=function(C){function m(c,E,A,S,g,l,h){A===void 0&&(A=null),g===void 0&&(g=u.a.TEXTURE_TRILINEAR_SAMPLINGMODE),l===void 0&&(l=u.a.TEXTUREFORMAT_RGBA);var b=C.call(this,null,A,!S,h,g,void 0,void 0,void 0,void 0,l)||this;b.name=c,b.wrapU=x.a.CLAMP_ADDRESSMODE,b.wrapV=x.a.CLAMP_ADDRESSMODE,b._generateMipMaps=S;var T=b._getEngine();if(!T)return b;E.getContext?(b._canvas=E,b._texture=T.createDynamicTexture(E.width,E.height,S,g)):(b._canvas=M.a.CreateCanvas(1,1),E.width||E.width===0?b._texture=T.createDynamicTexture(E.width,E.height,S,g):b._texture=T.createDynamicTexture(E,E,S,g));var D=b.getSize();return b._canvas.width=D.width,b._canvas.height=D.height,b._context=b._canvas.getContext("2d"),b}return Object(B.d)(m,C),m.prototype.getClassName=function(){return"DynamicTexture"},Object.defineProperty(m.prototype,"canRescale",{get:function(){return!0},enumerable:!1,configurable:!0}),m.prototype._recreate=function(c){this._canvas.width=c.width,this._canvas.height=c.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(c.width,c.height,this._generateMipMaps,this.samplingMode)},m.prototype.scale=function(c){var E=this.getSize();E.width*=c,E.height*=c,this._recreate(E)},m.prototype.scaleTo=function(c,E){var A=this.getSize();A.width=c,A.height=E,this._recreate(A)},m.prototype.getContext=function(){return this._context},m.prototype.clear=function(){var c=this.getSize();this._context.fillRect(0,0,c.width,c.height)},m.prototype.update=function(c,E){E===void 0&&(E=!1),this._getEngine().updateDynamicTexture(this._texture,this._canvas,c===void 0||c,E,this._format||void 0)},m.prototype.drawText=function(c,E,A,S,g,l,h,b){b===void 0&&(b=!0);var T=this.getSize();if(l&&(this._context.fillStyle=l,this._context.fillRect(0,0,T.width,T.height)),this._context.font=S,E==null){var D=this._context.measureText(c);E=(T.width-D.width)/2}if(A==null){var w=parseInt(S.replace(/\D/g,""));A=T.height/2+w/3.65}this._context.fillStyle=g||"",this._context.fillText(c,E,A),b&&this.update(h)},m.prototype.clone=function(){var c=this.getScene();if(!c)return this;var E=this.getSize(),A=new m(this.name,E,c,this._generateMipMaps);return A.hasAlpha=this.hasAlpha,A.level=this.level,A.wrapU=this.wrapU,A.wrapV=this.wrapV,A},m.prototype.serialize=function(){var c=this.getScene();c&&!c.isReady()&&_.a.Warn("The scene must be ready before serializing the dynamic texture");var E=C.prototype.serialize.call(this);return this._IsCanvasElement(this._canvas)&&(E.base64String=this._canvas.toDataURL()),E.invertY=this._invertY,E.samplingMode=this.samplingMode,E},m.prototype._IsCanvasElement=function(c){return c.toDataURL!==void 0},m.prototype._rebuild=function(){this.update()},m}(x.a)},function(Ae,v,f){f.d(v,"a",function(){return M});var B=f(0),_=f(9),x=f(7),u=f(16);u.a.CreateBox=function(R){var C,m=[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],c=[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],E=[],A=R.width||R.size||1,S=R.height||R.size||1,g=R.depth||R.size||1,l=R.wrap||!1,h=R.topBaseAt===void 0?1:R.topBaseAt,b=R.bottomBaseAt===void 0?0:R.bottomBaseAt,T=[2,0,3,1][h=(h+4)%4],D=[2,0,1,3][b=(b+4)%4],w=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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){m=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],w=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];for(var N=[[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]],V=[17,18,19,16],W=[22,23,20,21];T>0;)N.unshift(N.pop()),V.unshift(V.pop()),T--;for(;D>0;)I.unshift(I.pop()),W.unshift(W.pop()),D--;N=N.flat(),I=I.flat(),w=w.concat(N).concat(I),m.push(V[0],V[2],V[3],V[0],V[1],V[2]),m.push(W[0],W[2],W[3],W[0],W[1],W[2])}var j=[A/2,S/2,g/2];C=w.reduce(function(G,Q,oe){return G.concat(Q*j[oe%3])},[]);for(var ne=R.sideOrientation===0?0:R.sideOrientation||u.a.DEFAULTSIDE,te=R.faceUV||new Array(6),de=R.faceColors,pe=[],ae=0;ae<6;ae++)te[ae]===void 0&&(te[ae]=new B.f(0,0,1,1)),de&&de[ae]===void 0&&(de[ae]=new _.b(1,1,1,1));for(var ee=0;ee<6;ee++)if(E.push(te[ee].z,te[ee].w),E.push(te[ee].x,te[ee].w),E.push(te[ee].x,te[ee].y),E.push(te[ee].z,te[ee].y),de)for(var K=0;K<4;K++)pe.push(de[ee].r,de[ee].g,de[ee].b,de[ee].a);u.a._ComputeSides(ne,C,m,c,E,R.frontUVs,R.backUVs);var $=new u.a;if($.indices=m,$.positions=C,$.normals=c,$.uvs=E,de){var L=ne===u.a.DOUBLESIDE?pe.concat(pe):pe;$.colors=L}return $},x.a.CreateBox=function(R,C,m,c,E){m===void 0&&(m=null);var A={size:C,sideOrientation:E,updatable:c};return M.CreateBox(R,A,m)};var M=function(){function R(){}return R.CreateBox=function(C,m,c){c===void 0&&(c=null);var E=new x.a(C,c);return m.sideOrientation=x.a._GetDefaultSideOrientation(m.sideOrientation),E._originalBuilderSideOrientation=m.sideOrientation,u.a.CreateBox(m).applyToMesh(E,m.updatable),E},R}()},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(0),_=function(){function x(u,M,R,C){this.normal=new B.e(u,M,R),this.d=C}return x.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},x.prototype.clone=function(){return new x(this.normal.x,this.normal.y,this.normal.z,this.d)},x.prototype.getClassName=function(){return"Plane"},x.prototype.getHashCode=function(){var u=this.normal.getHashCode();return u=397*u^(0|this.d)},x.prototype.normalize=function(){var u=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),M=0;return u!==0&&(M=1/u),this.normal.x*=M,this.normal.y*=M,this.normal.z*=M,this.d*=M,this},x.prototype.transform=function(u){var M=x._TmpMatrix;u.invertToRef(M);var R=M.m,C=this.normal.x,m=this.normal.y,c=this.normal.z,E=this.d;return new x(C*R[0]+m*R[1]+c*R[2]+E*R[3],C*R[4]+m*R[5]+c*R[6]+E*R[7],C*R[8]+m*R[9]+c*R[10]+E*R[11],C*R[12]+m*R[13]+c*R[14]+E*R[15])},x.prototype.dotCoordinate=function(u){return this.normal.x*u.x+this.normal.y*u.y+this.normal.z*u.z+this.d},x.prototype.copyFromPoints=function(u,M,R){var C,m=M.x-u.x,c=M.y-u.y,E=M.z-u.z,A=R.x-u.x,S=R.y-u.y,g=R.z-u.z,l=c*g-E*S,h=E*A-m*g,b=m*S-c*A,T=Math.sqrt(l*l+h*h+b*b);return C=T!==0?1/T:0,this.normal.x=l*C,this.normal.y=h*C,this.normal.z=b*C,this.d=-(this.normal.x*u.x+this.normal.y*u.y+this.normal.z*u.z),this},x.prototype.isFrontFacingTo=function(u,M){return B.e.Dot(this.normal,u)<=M},x.prototype.signedDistanceTo=function(u){return B.e.Dot(u,this.normal)+this.d},x.FromArray=function(u){return new x(u[0],u[1],u[2],u[3])},x.FromPoints=function(u,M,R){var C=new x(0,0,0,0);return C.copyFromPoints(u,M,R),C},x.FromPositionAndNormal=function(u,M){var R=new x(0,0,0,0);return M.normalize(),R.normal=M,R.d=-(M.x*u.x+M.y*u.y+M.z*u.z),R},x.SignedDistanceToPlaneFromPositionAndNormal=function(u,M,R){var C=-(M.x*u.x+M.y*u.y+M.z*u.z);return B.e.Dot(R,M)+C},x._TmpMatrix=B.a.Identity(),x}()},function(Ae,v,f){f.d(v,"a",function(){return m});var B=f(7),_=f(20),x=f(6),u=f(0),M=f(18),R=f(39),C=f(60),m=(f(84),function(){function c(E){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new x.c,this.onDragStartObservable=new x.c,this.onDragEndObservable=new x.c,this.moveAttached=!0,this.enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=function(S){return!0},this._tmpVector=new u.e(0,0,0),this._alternatePickedPoint=new u.e(0,0,0),this._worldDragAxis=new u.e(0,0,0),this._targetPosition=new u.e(0,0,0),this._attachedToElement=!1,this._startDragRay=new R.a(new u.e,new u.e),this._lastPointerRay={},this._dragDelta=new u.e,this._pointA=new u.e(0,0,0),this._pointC=new u.e(0,0,0),this._localAxis=new u.e(0,0,0),this._lookAt=new u.e(0,0,0),this._options=E||{};var A=0;if(this._options.dragAxis&&A++,this._options.dragPlaneNormal&&A++,A>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(c.prototype,"options",{get:function(){return this._options},set:function(E){this._options=E},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!1,configurable:!0}),c.prototype.init=function(){},c.prototype.attach=function(E,A){var S=this;this._scene=E.getScene(),this.attachedNode=E,c._planeScene||(this._debugMode?c._planeScene=this._scene:(c._planeScene=new _.a(this._scene.getEngine(),{virtual:!0}),c._planeScene.detachControl(),this._scene.onDisposeObservable.addOnce(function(){c._planeScene.dispose(),c._planeScene=null}))),this._dragPlane=B.a.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,c._planeScene,!1,B.a.DOUBLESIDE),this.lastDragPosition=new u.e(0,0,0);var g=A||function(l){return S.attachedNode==l||l.isDescendantOf(S.attachedNode)};this._pointerObserver=this._scene.onPointerObservable.add(function(l,h){if(S.enabled){if(l.type==M.a.POINTERDOWN)S.startAndReleaseDragOnPointerEvents&&!S.dragging&&l.pickInfo&&l.pickInfo.hit&&l.pickInfo.pickedMesh&&l.pickInfo.pickedPoint&&l.pickInfo.ray&&g(l.pickInfo.pickedMesh)&&S._startDrag(l.event.pointerId,l.pickInfo.ray,l.pickInfo.pickedPoint);else if(l.type==M.a.POINTERUP)S.startAndReleaseDragOnPointerEvents&&S.currentDraggingPointerID==l.event.pointerId&&S.releaseDrag();else if(l.type==M.a.POINTERMOVE){var b=l.event.pointerId;if(S.currentDraggingPointerID===c._AnyMouseID&&b!==c._AnyMouseID){var T=l.event;(T.pointerType==="mouse"||!S._scene.getEngine().hostInformation.isMobile&&T instanceof MouseEvent)&&(S._lastPointerRay[S.currentDraggingPointerID]&&(S._lastPointerRay[b]=S._lastPointerRay[S.currentDraggingPointerID],delete S._lastPointerRay[S.currentDraggingPointerID]),S.currentDraggingPointerID=b)}S._lastPointerRay[b]||(S._lastPointerRay[b]=new R.a(new u.e,new u.e)),l.pickInfo&&l.pickInfo.ray&&(S._lastPointerRay[b].origin.copyFrom(l.pickInfo.ray.origin),S._lastPointerRay[b].direction.copyFrom(l.pickInfo.ray.direction),S.currentDraggingPointerID==b&&S.dragging&&S._moveDrag(l.pickInfo.ray))}}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(function(){S._moving&&S.moveAttached&&(C.a._RemoveAndStorePivotPoint(S.attachedNode),S._targetPosition.subtractToRef(S.attachedNode.absolutePosition,S._tmpVector),S._tmpVector.scaleInPlace(S.dragDeltaRatio),S.attachedNode.getAbsolutePosition().addToRef(S._tmpVector,S._tmpVector),S.validateDrag(S._tmpVector)&&S.attachedNode.setAbsolutePosition(S._tmpVector),C.a._RestorePivotPoint(S.attachedNode))})},c.prototype.releaseDrag=function(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID})),this.currentDraggingPointerID=-1,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if(this._scene.activeCamera.getClassName()==="ArcRotateCamera"){var 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}},c.prototype.startDrag=function(E,A,S){E===void 0&&(E=c._AnyMouseID),this._startDrag(E,A,S);var g=this._lastPointerRay[E];E===c._AnyMouseID&&(g=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),g&&this._moveDrag(g)},c.prototype._startDrag=function(E,A,S){if(this._scene.activeCamera&&!this.dragging&&this.attachedNode){C.a._RemoveAndStorePivotPoint(this.attachedNode),A?(this._startDragRay.direction.copyFrom(A.direction),this._startDragRay.origin.copyFrom(A.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,S||this._tmpVector);var g=this._pickWithRayOnDragPlane(this._startDragRay);g&&(this.dragging=!0,this.currentDraggingPointerID=E,this.lastDragPosition.copyFrom(g),this.onDragStartObservable.notifyObservers({dragPlanePoint:g,pointerId:this.currentDraggingPointerID}),this._targetPosition.copyFrom(this.attachedNode.absolutePosition),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)),C.a._RestorePivotPoint(this.attachedNode)}},c.prototype._moveDrag=function(E){this._moving=!0;var A=this._pickWithRayOnDragPlane(E);if(A){this.updateDragPlane&&this._updateDragPlanePosition(E,A);var S=0;this._options.dragAxis?(this.useObjectOrientationForDragging?u.e.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),A.subtractToRef(this.lastDragPosition,this._tmpVector),S=u.e.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(S,this._dragDelta)):(S=this._dragDelta.length(),A.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:S,delta:this._dragDelta,dragPlanePoint:A,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerID}),this.lastDragPosition.copyFrom(A)}},c.prototype._pickWithRayOnDragPlane=function(E){var A=this;if(!E)return null;var S=Math.acos(u.e.Dot(this._dragPlane.forward,E.direction));if(S>Math.PI/2&&(S=Math.PI-S),this.maxDragAngle>0&&S>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(E.direction),this.attachedNode.absolutePosition.subtractToRef(E.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*u.e.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var g=u.e.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-g,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}var l=c._planeScene.pickWithRay(E,function(h){return h==A._dragPlane});return l&&l.hit&&l.pickedMesh&&l.pickedPoint?l.pickedPoint:null},c.prototype._updateDragPlanePosition=function(E,A){this._pointA.copyFrom(A),this._options.dragAxis?(this.useObjectOrientationForDragging?u.e.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(u.e.Dot(this._localAxis,this._pointC))>.999?Math.abs(u.e.Dot(u.e.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(u.e.Right()):this._lookAt.copyFrom(u.e.UpReadOnly):(u.e.CrossToRef(this._localAxis,this._pointC,this._lookAt),u.e.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?u.e.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.absolutePosition),this._dragPlane.computeWorldMatrix(!0)},c.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this.releaseDrag()},c._AnyMouseID=-2,c}())},function(Ae,v,f){f.d(v,"a",function(){return _}),f.d(v,"b",function(){return x}),f.d(v,"c",function(){return u});var B=f(1),_=function(){function M(){}return M.KEYDOWN=1,M.KEYUP=2,M}(),x=function(M,R){this.type=M,this.event=R},u=function(M){function R(C,m){var c=M.call(this,C,m)||this;return c.type=C,c.event=m,c.skipOnPointerObservable=!1,c}return Object(B.d)(R,M),R}(x)},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}return _.prototype.unBindMesh=function(){this._mesh=null},_.prototype.addFallback=function(x,u){this._defines[x]||(xthis._maxRank&&(this._maxRank=x),this._defines[x]=new Array),this._defines[x].push(u)},_.prototype.addCPUSkinningFallback=function(x,u){this._mesh=u,xthis._maxRank&&(this._maxRank=x)},Object.defineProperty(_.prototype,"hasMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!1,configurable:!0}),_.prototype.reduce=function(x,u){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,x=x.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),u._bonesComputationForcedToCPU=!0;for(var M=this._mesh.getScene(),R=0;R0&&(C.computeBonesUsingShaders=!1)}}else{var E=this._defines[this._currentRank];if(E)for(R=0;R=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[m]},C.prototype.getActiveTextures=function(){var m;return(m=R.prototype.getActiveTextures.call(this)).concat.apply(m,this.subMaterials.map(function(c){return c?c.getActiveTextures():[]}))},C.prototype.hasTexture=function(m){var c;if(R.prototype.hasTexture.call(this,m))return!0;for(var E=0;E=0&&A.multiMaterials.splice(S,1),R.prototype.dispose.call(this,m,c)}},C.ParseMultiMaterial=function(m,c){var E=new C(m.name,c);E.id=m.id,x.a&&x.a.AddTagsTo(E,m.tags);for(var A=0;A"u")return new OffscreenCanvas(x,u);var M=document.createElement("canvas");return M.width=x,M.height=u,M},_}()},function(Ae,v,f){f.d(v,"a",function(){return S});var B=f(0),_=f(9),x=f(16),u=f(4),M=f(61),R=f(69),C=f(43),m=f(2),c=f(12),E=f(37),A=f(101),S=function(){function g(l,h,b,T,D){T===void 0&&(T=!1),D===void 0&&(D=null),this.delayLoadState=m.a.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this.useBoundingInfoFromGeometry=!1,this.id=l,this.uniqueId=h.getUniqueId(),this._engine=h.getEngine(),this._meshes=[],this._scene=h,this._vertexBuffers={},this._indices=[],this._updatable=T,b?this.setAllVerticesData(b,T):(this._totalVertices=0,this._indices=[]),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),D&&(this.applyToMesh(D),D.computeWorldMatrix(!0))}return Object.defineProperty(g.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(l){this._boundingBias?this._boundingBias.copyFrom(l):this._boundingBias=l.clone(),this._updateBoundingInfo(!0,null)},enumerable:!1,configurable:!0}),g.CreateGeometryForMesh=function(l){var h=new g(g.RandomId(),l.getScene());return h.applyToMesh(l),h},Object.defineProperty(g.prototype,"meshes",{get:function(){return this._meshes},enumerable:!1,configurable:!0}),Object.defineProperty(g.prototype,"extend",{get:function(){return this._extend},enumerable:!1,configurable:!0}),g.prototype.getScene=function(){return this._scene},g.prototype.getEngine=function(){return this._engine},g.prototype.isReady=function(){return this.delayLoadState===m.a.DELAYLOADSTATE_LOADED||this.delayLoadState===m.a.DELAYLOADSTATE_NONE},Object.defineProperty(g.prototype,"doNotSerialize",{get:function(){for(var l=0;l0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=h),l._syncGeometryWithMorphTargetManager(),l.synchronizeInstances()},g.prototype.notifyUpdate=function(l){this.onGeometryUpdated&&this.onGeometryUpdated(this,l);for(var h=0,b=this._meshes;h0){for(var h=0;h0){for(h=0;h0){for(h=0;h0){var N=new Float32Array(l,w.positionsAttrDesc.offset,w.positionsAttrDesc.count);h.setVerticesData(u.b.PositionKind,N,!1)}if(w.normalsAttrDesc&&w.normalsAttrDesc.count>0){var I=new Float32Array(l,w.normalsAttrDesc.offset,w.normalsAttrDesc.count);h.setVerticesData(u.b.NormalKind,I,!1)}if(w.tangetsAttrDesc&&w.tangetsAttrDesc.count>0){var V=new Float32Array(l,w.tangetsAttrDesc.offset,w.tangetsAttrDesc.count);h.setVerticesData(u.b.TangentKind,V,!1)}if(w.uvsAttrDesc&&w.uvsAttrDesc.count>0){var W=new Float32Array(l,w.uvsAttrDesc.offset,w.uvsAttrDesc.count);h.setVerticesData(u.b.UVKind,W,!1)}if(w.uvs2AttrDesc&&w.uvs2AttrDesc.count>0){var j=new Float32Array(l,w.uvs2AttrDesc.offset,w.uvs2AttrDesc.count);h.setVerticesData(u.b.UV2Kind,j,!1)}if(w.uvs3AttrDesc&&w.uvs3AttrDesc.count>0){var ne=new Float32Array(l,w.uvs3AttrDesc.offset,w.uvs3AttrDesc.count);h.setVerticesData(u.b.UV3Kind,ne,!1)}if(w.uvs4AttrDesc&&w.uvs4AttrDesc.count>0){var te=new Float32Array(l,w.uvs4AttrDesc.offset,w.uvs4AttrDesc.count);h.setVerticesData(u.b.UV4Kind,te,!1)}if(w.uvs5AttrDesc&&w.uvs5AttrDesc.count>0){var de=new Float32Array(l,w.uvs5AttrDesc.offset,w.uvs5AttrDesc.count);h.setVerticesData(u.b.UV5Kind,de,!1)}if(w.uvs6AttrDesc&&w.uvs6AttrDesc.count>0){var pe=new Float32Array(l,w.uvs6AttrDesc.offset,w.uvs6AttrDesc.count);h.setVerticesData(u.b.UV6Kind,pe,!1)}if(w.colorsAttrDesc&&w.colorsAttrDesc.count>0){var ae=new Float32Array(l,w.colorsAttrDesc.offset,w.colorsAttrDesc.count);h.setVerticesData(u.b.ColorKind,ae,!1,w.colorsAttrDesc.stride)}if(w.matricesIndicesAttrDesc&&w.matricesIndicesAttrDesc.count>0){for(var ee=new Int32Array(l,w.matricesIndicesAttrDesc.offset,w.matricesIndicesAttrDesc.count),K=[],$=0;$>8),K.push((16711680&L)>>16),K.push(L>>24&255)}h.setVerticesData(u.b.MatricesIndicesKind,K,!1)}if(w.matricesIndicesExtraAttrDesc&&w.matricesIndicesExtraAttrDesc.count>0){for(ee=new Int32Array(l,w.matricesIndicesExtraAttrDesc.offset,w.matricesIndicesExtraAttrDesc.count),K=[],$=0;$>8),K.push((16711680&L)>>16),K.push(L>>24&255);h.setVerticesData(u.b.MatricesIndicesExtraKind,K,!1)}if(w.matricesWeightsAttrDesc&&w.matricesWeightsAttrDesc.count>0){var G=new Float32Array(l,w.matricesWeightsAttrDesc.offset,w.matricesWeightsAttrDesc.count);h.setVerticesData(u.b.MatricesWeightsKind,G,!1)}if(w.indicesAttrDesc&&w.indicesAttrDesc.count>0){var Q=new Int32Array(l,w.indicesAttrDesc.offset,w.indicesAttrDesc.count);h.setIndices(Q,null)}if(w.subMeshesAttrDesc&&w.subMeshesAttrDesc.count>0){var oe=new Int32Array(l,w.subMeshesAttrDesc.offset,5*w.subMeshesAttrDesc.count);for(h.subMeshes=[],$=0;$>8),K.push((16711680&X)>>16),K.push(X>>24&255)}h.setVerticesData(u.b.MatricesIndicesKind,K,l.matricesIndices._updatable)}if(l.matricesIndicesExtra)if(l.matricesIndicesExtra._isExpanded)delete l.matricesIndices._isExpanded,h.setVerticesData(u.b.MatricesIndicesExtraKind,l.matricesIndicesExtra,l.matricesIndicesExtra._updatable);else{for(K=[],$=0;$>8),K.push((16711680&X)>>16),K.push(X>>24&255);h.setVerticesData(u.b.MatricesIndicesExtraKind,K,l.matricesIndicesExtra._updatable)}l.matricesWeights&&(g._CleanMatricesWeights(l,h),h.setVerticesData(u.b.MatricesWeightsKind,l.matricesWeights,l.matricesWeights._updatable)),l.matricesWeightsExtra&&h.setVerticesData(u.b.MatricesWeightsExtraKind,l.matricesWeightsExtra,l.matricesWeights._updatable),h.setIndices(l.indices,null)}if(l.subMeshes){h.subMeshes=[];for(var q=0;q-1){var T=h.getScene().getLastSkeletonByID(l.skeletonId);if(T){b=T.bones.length;for(var D=h.getVerticesData(u.b.MatricesIndicesKind),w=h.getVerticesData(u.b.MatricesIndicesExtraKind),N=l.matricesWeights,I=l.matricesWeightsExtra,V=l.numBoneInfluencer,W=N.length,j=0;jV-1)&&(te=V-1),ne>.001){var ae=1/ne;for(de=0;de<4;de++)N[j+de]*=ae;if(I)for(de=0;de<4;de++)I[j+de]*=ae}else te>=4?(I[j+te-4]=1-ne,w[j+te-4]=b):(N[j+te]=1-ne,D[j+te]=b)}h.setVerticesData(u.b.MatricesIndicesKind,D),l.matricesWeightsExtra&&h.setVerticesData(u.b.MatricesIndicesExtraKind,w)}}}},g.Parse=function(l,h,b){if(h.getGeometryByID(l.id))return null;var T=new g(l.id,h,void 0,l.updatable);return E.a&&E.a.AddTagsTo(T,l.tags),l.delayLoadingFile?(T.delayLoadState=m.a.DELAYLOADSTATE_NOTLOADED,T.delayLoadingFile=b+l.delayLoadingFile,T._boundingInfo=new C.a(B.e.FromArray(l.boundingBoxMinimum),B.e.FromArray(l.boundingBoxMaximum)),T._delayInfo=[],l.hasUVs&&T._delayInfo.push(u.b.UVKind),l.hasUVs2&&T._delayInfo.push(u.b.UV2Kind),l.hasUVs3&&T._delayInfo.push(u.b.UV3Kind),l.hasUVs4&&T._delayInfo.push(u.b.UV4Kind),l.hasUVs5&&T._delayInfo.push(u.b.UV5Kind),l.hasUVs6&&T._delayInfo.push(u.b.UV6Kind),l.hasColors&&T._delayInfo.push(u.b.ColorKind),l.hasMatricesIndices&&T._delayInfo.push(u.b.MatricesIndicesKind),l.hasMatricesWeights&&T._delayInfo.push(u.b.MatricesWeightsKind),T._delayLoadingFunction=x.a.ImportVertexData):x.a.ImportVertexData(l,T),h.pushGeometry(T,!0),T},g}()},function(Ae,v,f){f.d(v,"e",function(){return B}),f.d(v,"c",function(){return M}),f.d(v,"a",function(){return R}),f.d(v,"b",function(){return C}),f.d(v,"f",function(){return m}),f.d(v,"g",function(){return c}),f.d(v,"d",function(){return E});var B,_=f(14),x=f(0),u=f(28);(function(A){A[A.CW=0]="CW",A[A.CCW=1]="CCW"})(B||(B={}));var M=function(){function A(){}return A.Interpolate=function(S,g,l,h,b){for(var T=1-3*h+3*g,D=3*h-6*g,w=3*g,N=S,I=0;I<5;I++){var V=N*N;N-=(T*(V*N)+D*V+w*N-S)*(1/(3*T*V+2*D*N+w)),N=Math.min(1,Math.max(0,N))}return 3*Math.pow(1-N,2)*N*l+3*(1-N)*Math.pow(N,2)*b+Math.pow(N,3)},A}(),R=function(){function A(S){this._radians=S,this._radians<0&&(this._radians+=2*Math.PI)}return A.prototype.degrees=function(){return 180*this._radians/Math.PI},A.prototype.radians=function(){return this._radians},A.BetweenTwoPoints=function(S,g){var l=g.subtract(S);return new A(Math.atan2(l.y,l.x))},A.FromRadians=function(S){return new A(S)},A.FromDegrees=function(S){return new A(S*Math.PI/180)},A}(),C=function(A,S,g){this.startPoint=A,this.midPoint=S,this.endPoint=g;var l=Math.pow(S.x,2)+Math.pow(S.y,2),h=(Math.pow(A.x,2)+Math.pow(A.y,2)-l)/2,b=(l-Math.pow(g.x,2)-Math.pow(g.y,2))/2,T=(A.x-S.x)*(S.y-g.y)-(S.x-g.x)*(A.y-S.y);this.centerPoint=new x.d((h*(S.y-g.y)-b*(A.y-S.y))/T,((A.x-S.x)*b-(S.x-g.x)*h)/T),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=R.BetweenTwoPoints(this.centerPoint,this.startPoint);var D=this.startAngle.degrees(),w=R.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),N=R.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();w-D>180&&(w-=360),w-D<-180&&(w+=360),N-w>180&&(N-=360),N-w<-180&&(N+=360),this.orientation=w-D<0?B.CW:B.CCW,this.angle=R.FromDegrees(this.orientation===B.CW?D-N:N-D)},m=function(){function A(S,g){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new x.d(S,g))}return A.prototype.addLineTo=function(S,g){if(this.closed)return this;var l=new x.d(S,g),h=this._points[this._points.length-1];return this._points.push(l),this._length+=l.subtract(h).length(),this},A.prototype.addArcTo=function(S,g,l,h,b){if(b===void 0&&(b=36),this.closed)return this;var T=this._points[this._points.length-1],D=new x.d(S,g),w=new x.d(l,h),N=new C(T,D,w),I=N.angle.radians()/b;N.orientation===B.CW&&(I*=-1);for(var V=N.startAngle.radians()+I,W=0;W1)return x.d.Zero();for(var g=S*this.length(),l=0,h=0;h=l&&g<=w){var N=D.normalize(),I=g-l;return new x.d(T.x+N.x*I,T.y+N.y*I)}l=w}return x.d.Zero()},A.StartingAt=function(S,g){return new A(S,g)},A}(),c=function(){function A(S,g,l,h){g===void 0&&(g=null),h===void 0&&(h=!1),this.path=S,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:x.e.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:x.a.Identity()};for(var b=0;bg){var l=S;S=g,g=l}var h=this.getCurve(),b=this.getPointAt(S),T=this.getPreviousPointIndexAt(S),D=this.getPointAt(g),w=this.getPreviousPointIndexAt(g)+1,N=[];return S!==0&&(T++,N.push(b)),N.push.apply(N,h.slice(T,w)),g===1&&S!==1||N.push(D),new A(N,this.getNormalAt(S),this._raw,this._alignTangentsWithPath)},A.prototype.update=function(S,g,l){g===void 0&&(g=null),l===void 0&&(l=!1);for(var h=0;hg+1;)g++,l=this._curve[S].subtract(this._curve[S-g]);return l},A.prototype._normalVector=function(S,g){var l,h,b=S.length();return b===0&&(b=1),g==null?(h=_.a.WithinEpsilon(Math.abs(S.y)/b,1,u.a)?_.a.WithinEpsilon(Math.abs(S.x)/b,1,u.a)?_.a.WithinEpsilon(Math.abs(S.z)/b,1,u.a)?x.e.Zero():new x.e(0,0,1):new x.e(1,0,0):new x.e(0,-1,0),l=x.e.Cross(S,h)):(l=x.e.Cross(S,g),x.e.CrossToRef(l,S,l)),l.normalize(),l},A.prototype._updatePointAtData=function(S,g){if(g===void 0&&(g=!1),this._pointAtData.id===S)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=S;var l=this.getPoints();if(S<=0)return this._setPointAtData(0,0,l[0],0,g);if(S>=1)return this._setPointAtData(1,1,l[l.length-1],l.length-1,g);for(var h,b=l[0],T=0,D=S*this.length(),w=1;wD){var I=(T-D)/N,V=b.subtract(h),W=h.add(V.scaleInPlace(I));return this._setPointAtData(S,1-I,W,w-1,g)}b=h}return this._pointAtData},A.prototype._setPointAtData=function(S,g,l,h,b){return this._pointAtData.point=l,this._pointAtData.position=S,this._pointAtData.subPosition=g,this._pointAtData.previousPointArrayIndex=h,this._pointAtData.interpolateReady=b,b&&this._updateInterpolationMatrix(),this._pointAtData},A.prototype._updateInterpolationMatrix=function(){this._pointAtData.interpolationMatrix=x.a.Identity();var S=this._pointAtData.previousPointArrayIndex;if(S!==this._tangents.length-1){var g=S+1,l=this._tangents[S].clone(),h=this._normals[S].clone(),b=this._binormals[S].clone(),T=this._tangents[g].clone(),D=this._normals[g].clone(),w=this._binormals[g].clone(),N=x.b.RotationQuaternionFromAxis(h,b,l),I=x.b.RotationQuaternionFromAxis(D,w,T);x.b.Slerp(N,I,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}},A}(),E=function(){function A(S){this._length=0,this._points=S,this._length=this._computeLength(S)}return A.CreateQuadraticBezier=function(S,g,l,h){h=h>2?h:3;for(var b=new Array,T=function(w,N,I,V){return(1-w)*(1-w)*N+2*w*(1-w)*I+w*w*V},D=0;D<=h;D++)b.push(new x.e(T(D/h,S.x,g.x,l.x),T(D/h,S.y,g.y,l.y),T(D/h,S.z,g.z,l.z)));return new A(b)},A.CreateCubicBezier=function(S,g,l,h,b){b=b>3?b:4;for(var T=new Array,D=function(N,I,V,W,j){return(1-N)*(1-N)*(1-N)*I+3*N*(1-N)*(1-N)*V+3*N*N*(1-N)*W+N*N*N*j},w=0;w<=b;w++)T.push(new x.e(D(w/b,S.x,g.x,l.x,h.x),D(w/b,S.y,g.y,l.y,h.y),D(w/b,S.z,g.z,l.z,h.z)));return new A(T)},A.CreateHermiteSpline=function(S,g,l,h,b){for(var T=new Array,D=1/b,w=0;w<=b;w++)T.push(x.e.Hermite(S,g,l,h,w*D));return new A(T)},A.CreateCatmullRomSpline=function(S,g,l){var h=new Array,b=1/g,T=0;if(l){for(var D=S.length,w=0;w1&&(this._multiview=!0,W.push("#define MULTIVIEW"),this._options.uniforms.indexOf("viewProjection")!==-1&&this._options.uniforms.push("viewProjectionR")===-1&&this._options.uniforms.push("viewProjectionR"));for(var te=0;te4&&(j.push(u.b.MatricesIndicesExtraKind),j.push(u.b.MatricesWeightsExtraKind));var pe=T.skeleton;de=T.numBoneInfluencers,W.push("#define NUM_BONE_INFLUENCERS "+de),ne.addCPUSkinningFallback(0,T),pe.isUsingTextureForMatrices?(W.push("#define BONETEXTURE"),this._options.uniforms.indexOf("boneTextureWidth")===-1&&this._options.uniforms.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(W.push("#define BonesPerMesh "+(pe.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else W.push("#define NUM_BONE_INFLUENCERS 0");for(var ae in this._textures)if(!this._textures[ae].isReady())return!1;T&&this._shouldTurnAlphaTestOn(T)&&W.push("#define ALPHATEST");var ee=this._shaderPath,K=this._options.uniforms,$=this._options.uniformBuffers,L=this._options.samplers;this.customShaderNameResolve&&(K=K.slice(),$=$.slice(),L=L.slice(),ee=this.customShaderNameResolve(ee,K,$,L,W,j));var G=this._effect,Q=W.join(` -`);return this._cachedDefines!==Q&&(this._cachedDefines=Q,this._effect=V.createEffect(ee,{attributes:j,uniformsNames:K,uniformBuffersNames:$,samplers:L,defines:Q,fallbacks:ne,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:de}},V),this._onEffectCreatedObservable&&(g.effect=this._effect,this._onEffectCreatedObservable.notifyObservers(g))),(N=!(!((w=this._effect)===null||w===void 0)&&w.isReady()))!==null&&N!==void 0&&!N&&(G!==this._effect&&I.resetCachedMaterial(),this._renderId=I.getRenderId(),this._effect._wasPreviouslyReady=!0,!0)},b.prototype.bindOnlyWorldMatrix=function(T,D){var w=this.getScene(),N=D??this._effect;N&&(this._options.uniforms.indexOf("world")!==-1&&N.setMatrix("world",T),this._options.uniforms.indexOf("worldView")!==-1&&(T.multiplyToRef(w.getViewMatrix(),this._cachedWorldViewMatrix),N.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(T.multiplyToRef(w.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),N.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))},b.prototype.bindForSubMesh=function(T,D,w){this.bind(T,D,w._effectOverride)},b.prototype.bind=function(T,D,w){this.bindOnlyWorldMatrix(T,w);var N=w??this._effect;if(N&&this.getScene().getCachedMaterial()!==this){var I;for(I in this._options.uniforms.indexOf("view")!==-1&&N.setMatrix("view",this.getScene().getViewMatrix()),this._options.uniforms.indexOf("projection")!==-1&&N.setMatrix("projection",this.getScene().getProjectionMatrix()),this._options.uniforms.indexOf("viewProjection")!==-1&&(N.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&N.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&this._options.uniforms.indexOf("cameraPosition")!==-1&&N.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),R.a.BindBonesParameters(D,N),this._textures)N.setTexture(I,this._textures[I]);for(I in this._textureArrays)N.setTextureArray(I,this._textureArrays[I]);for(I in this._ints)N.setInt(I,this._ints[I]);for(I in this._floats)N.setFloat(I,this._floats[I]);for(I in this._floatsArrays)N.setArray(I,this._floatsArrays[I]);for(I in this._colors3)N.setColor3(I,this._colors3[I]);for(I in this._colors3Arrays)N.setArray3(I,this._colors3Arrays[I]);for(I in this._colors4){var V=this._colors4[I];N.setFloat4(I,V.r,V.g,V.b,V.a)}for(I in this._colors4Arrays)N.setArray4(I,this._colors4Arrays[I]);for(I in this._vectors2)N.setVector2(I,this._vectors2[I]);for(I in this._vectors3)N.setVector3(I,this._vectors3[I]);for(I in this._vectors4)N.setVector4(I,this._vectors4[I]);for(I in this._matrices)N.setMatrix(I,this._matrices[I]);for(I in this._matrixArrays)N.setMatrices(I,this._matrixArrays[I]);for(I in this._matrices3x3)N.setMatrix3x3(I,this._matrices3x3[I]);for(I in this._matrices2x2)N.setMatrix2x2(I,this._matrices2x2[I]);for(I in this._vectors2Arrays)N.setArray2(I,this._vectors2Arrays[I]);for(I in this._vectors3Arrays)N.setArray3(I,this._vectors3Arrays[I]);for(I in this._vectors4Arrays)N.setArray4(I,this._vectors4Arrays[I])}var W=this._effect;this._effect=N,this._afterBind(D),this._effect=W},b.prototype._afterBind=function(T){h.prototype._afterBind.call(this,T),this.getScene()._cachedEffect=this._effect},b.prototype.getActiveTextures=function(){var T=h.prototype.getActiveTextures.call(this);for(var D in this._textures)T.push(this._textures[D]);for(var D in this._textureArrays)for(var w=this._textureArrays[D],N=0;NI.snapDistance){var ee=Math.floor(Math.abs(j)/I.snapDistance);j%=I.snapDistance,ae.delta.normalizeToRef(ne),ne.scaleInPlace(I.snapDistance*ee),I.attachedNode.getWorldMatrix().addTranslationFromFloats(ne.x,ne.y,ne.z),I.attachedNode.updateCache(),te.snapDistance=I.snapDistance*ee,I.onSnapObservable.notifyObservers(te)}I._matrixChanged()}}),I.dragBehavior.onDragStartObservable.add(function(){I._dragging=!0}),I.dragBehavior.onDragEndObservable.add(function(){I._dragging=!1});var de=T._getSharedGizmoLight();de.includedOnlyMeshes=de.includedOnlyMeshes.concat(I._rootMesh.getChildMeshes(!1));var pe={gizmoMeshes:V.getChildMeshes(),colliderMeshes:W.getChildMeshes(),material:I._coloredMaterial,hoverMaterial:I._hoverMaterial,disableMaterial:I._disableMaterial,active:!1};return(N=I._parent)===null||N===void 0||N.addToAxisCache(W,pe),I._pointerObserver=T.utilityLayerScene.onPointerObservable.add(function(ae){var ee;if(!I._customMeshSet&&(I._isHovered=pe.colliderMeshes.indexOf((ee=ae?.pickInfo)===null||ee===void 0?void 0:ee.pickedMesh)!=-1,!I._parent)){var K=I._isHovered||I._dragging?I._hoverMaterial:I._coloredMaterial;pe.gizmoMeshes.forEach(function($){$.material=K,$.color&&($.color=K.diffuseColor)})}}),I}return Object(B.d)(l,g),l._CreateArrow=function(h,b,T,D){T===void 0&&(T=1),D===void 0&&(D=!1);var w=new u.a("arrow",h),N=R.a.CreateCylinder("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(T-1)/4),tessellation:96},h),I=R.a.CreateCylinder("cylinder",{diameterTop:.005*T,height:.275,diameterBottom:.005*T,tessellation:96},h);return N.parent=w,N.material=b,N.rotation.x=Math.PI/2,N.position.z+=.3,I.parent=w,I.material=b,I.position.z+=.1375,I.rotation.x=Math.PI/2,D&&(I.visibility=0,N.visibility=0),w},l._CreateArrowInstance=function(h,b){for(var T=new u.a("arrow",h),D=0,w=b.getChildMeshes();D0 -#ifdef BONETEXTURE -uniform sampler2D boneSampler; -uniform float boneTextureWidth; -#else -uniform mat4 mBones[BonesPerMesh]; -#ifdef BONES_VELOCITY_ENABLED -uniform mat4 mPreviousBones[BonesPerMesh]; -#endif -#endif -attribute vec4 matricesIndices; -attribute vec4 matricesWeights; -#if NUM_BONE_INFLUENCERS>4 -attribute vec4 matricesIndicesExtra; -attribute vec4 matricesWeightsExtra; -#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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="instancesDeclaration",_=`#ifdef INSTANCES -attribute vec4 world0; -attribute vec4 world1; -attribute vec4 world2; -attribute vec4 world3; -#ifdef THIN_INSTANCES -uniform mat4 world; -#endif -#else -uniform mat4 world; -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="instancesVertex",_=`#ifdef INSTANCES -mat4 finalWorld=mat4(world0,world1,world2,world3); -#ifdef THIN_INSTANCES -finalWorld=world*finalWorld; -#endif -#else -mat4 finalWorld=world; -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=`#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`;f(5).a.IncludesShadersStore.bonesVertex=B},function(Ae,v,f){f.d(v,"a",function(){return R});var B=f(0),_=f(7),x=f(4),u=f(16),M=f(43);u.a.CreateRibbon=function(C){var m=C.pathArray,c=C.closeArray||!1,E=C.closePath||!1,A=C.invertUV||!1,S=Math.floor(m[0].length/2),g=C.offset||S;g=g>S?S:Math.floor(g);var l,h,b,T,D=C.sideOrientation===0?0:C.sideOrientation||u.a.DEFAULTSIDE,w=C.uvs,N=C.colors,I=[],V=[],W=[],j=[],ne=[],te=[],de=[],pe=[],ae=[],ee=[];if(m.length<2){var K=[],$=[];for(b=0;b0&&(Q=L[T].subtract(L[T-1]).length()+de[h],ne[h].push(Q),de[h]=Q),T++;E&&(T--,I.push(L[0].x,L[0].y,L[0].z),Q=L[T].subtract(L[0]).length()+de[h],ne[h].push(Q),de[h]=Q),ae[h]=G+k,ee[h]=Y,Y+=G+k}var H,Z,X=null,q=null;for(b=0;b=B.a.ACTION_OnPickTrigger&&M<=B.a.ACTION_OnPickUpTrigger)return!0}return!1},enumerable:!1,configurable:!0}),x.HasSpecificTrigger=function(u){for(var M in x.Triggers)if(x.Triggers.hasOwnProperty(M)&&parseInt(M)===u)return!0;return!1},x.Triggers={},x}()},function(Ae,v,f){f.d(v,"a",function(){return R});var B=f(1),_=f(25),x=f(3),u=f(19),M=f(15),R=function(){function C(m){this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=_.a.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=m}return C.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},C.prototype.isReadyForSubMesh=function(m,c){var E=c.getEngine();return!(m._areTexturesDirty&&c.texturesEnabled&&E.getCaps().standardDerivatives&&this._texture&&u.a.DetailTextureEnabled&&!this._texture.isReady())},C.prototype.prepareDefines=function(m,c){if(this._isEnabled){m.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;var E=c.getEngine();m._areTexturesDirty&&(E.getCaps().standardDerivatives&&this._texture&&u.a.DetailTextureEnabled&&this._isEnabled?(M.a.PrepareDefinesForMergedUV(this._texture,m,"DETAIL"),m.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):m.DETAIL=!1)}else m.DETAIL=!1},C.prototype.bindForSubMesh=function(m,c,E){this._isEnabled&&(m.useUbo&&E&&m.isSync||this._texture&&u.a.DetailTextureEnabled&&(m.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),M.a.BindTextureMatrix(this._texture,m,"detail")),c.texturesEnabled&&this._texture&&u.a.DetailTextureEnabled&&m.setTexture("detailSampler",this._texture))},C.prototype.hasTexture=function(m){return this._texture===m},C.prototype.getActiveTextures=function(m){this._texture&&m.push(this._texture)},C.prototype.getAnimatables=function(m){this._texture&&this._texture.animations&&this._texture.animations.length>0&&m.push(this._texture)},C.prototype.dispose=function(m){var c;m&&((c=this._texture)===null||c===void 0||c.dispose())},C.prototype.getClassName=function(){return"DetailMap"},C.AddUniforms=function(m){m.push("vDetailInfos")},C.AddSamplers=function(m){m.push("detailSampler")},C.PrepareUniformBuffer=function(m){m.addUniform("vDetailInfos",4),m.addUniform("detailMatrix",16)},C.prototype.copyTo=function(m){x.a.Clone(function(){return m},this)},C.prototype.serialize=function(){return x.a.Serialize(this)},C.prototype.parse=function(m,c,E){var A=this;x.a.Parse(function(){return A},m,c,E)},Object(B.c)([Object(x.m)("detailTexture"),Object(x.b)("_markAllSubMeshesAsTexturesDirty")],C.prototype,"texture",void 0),Object(B.c)([Object(x.c)()],C.prototype,"diffuseBlendLevel",void 0),Object(B.c)([Object(x.c)()],C.prototype,"roughnessBlendLevel",void 0),Object(B.c)([Object(x.c)()],C.prototype,"bumpLevel",void 0),Object(B.c)([Object(x.c)(),Object(x.b)("_markAllSubMeshesAsTexturesDirty")],C.prototype,"normalBlendMethod",void 0),Object(B.c)([Object(x.c)(),Object(x.b)("_markAllSubMeshesAsTexturesDirty")],C.prototype,"isEnabled",void 0),C}()},function(Ae,v,f){var B="morphTargetsVertexGlobalDeclaration",_=`#ifdef MORPHTARGETS -uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="morphTargetsVertexDeclaration",_=`#ifdef MORPHTARGETS -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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){f.d(v,"a",function(){return u});var B=f(25),_=f(4),x=f(2),u=function(){function M(R){this._vertexBuffers={},this._scene=R}return M.prototype._prepareBuffers=function(){if(!this._vertexBuffers[_.b.PositionKind]){var R=[];R.push(1,1),R.push(-1,1),R.push(-1,-1),R.push(1,-1),this._vertexBuffers[_.b.PositionKind]=new _.b(this._scene.getEngine(),R,_.b.PositionKind,!1,!1,2),this._buildIndexBuffer()}},M.prototype._buildIndexBuffer=function(){var R=[];R.push(0),R.push(1),R.push(2),R.push(0),R.push(2),R.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(R)},M.prototype._rebuild=function(){var R=this._vertexBuffers[_.b.PositionKind];R&&(R._rebuild(),this._buildIndexBuffer())},M.prototype._prepareFrame=function(R,C){R===void 0&&(R=null),C===void 0&&(C=null);var m=this._scene.activeCamera;return!!m&&!(!(C=C||m._postProcesses.filter(function(c){return c!=null}))||C.length===0||!this._scene.postProcessesEnabled)&&(C[0].activate(m,R,C!=null),!0)},M.prototype.directRender=function(R,C,m,c,E,A){C===void 0&&(C=null),m===void 0&&(m=!1),c===void 0&&(c=0),E===void 0&&(E=0),A===void 0&&(A=!1);for(var S=this._scene.getEngine(),g=0;g3?0:b,T);var ae=x.a.CreateRibbon(C,{pathArray:te,closeArray:l,closePath:h,updatable:w,sideOrientation:N,invertUV:V,frontUVs:W||void 0,backUVs:j||void 0},D);return ae._creationDataStorage.pathArray=te,ae._creationDataStorage.path3D=ne,ae._creationDataStorage.cap=b,ae},R}()},function(Ae,v,f){f.d(v,"b",function(){return c}),f.d(v,"a",function(){return E});var B=f(1),_=f(9),x=f(4),u=f(7),M=f(151),R=f(25),C=f(73),m=f(15),c=(f(166),f(167),function(A){function S(g,l,h,b,T,D,w){l===void 0&&(l=null),h===void 0&&(h=null),b===void 0&&(b=null);var N=A.call(this,g,l,h,b,T)||this;N.useVertexColor=D,N.useVertexAlpha=w,N.color=new _.a(1,1,1),N.alpha=1,b&&(N.color=b.color.clone(),N.alpha=b.alpha,N.useVertexColor=b.useVertexColor,N.useVertexAlpha=b.useVertexAlpha),N.intersectionThreshold=.1;var I={attributes:[x.b.PositionKind,"world0","world1","world2","world3"],uniforms:["vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","world","viewProjection"],needAlphaBlending:!0,defines:[]};return w===!1&&(I.needAlphaBlending=!1),D?(I.defines.push("#define VERTEXCOLOR"),I.attributes.push(x.b.ColorKind)):(I.uniforms.push("color"),N.color4=new _.b),N._colorShader=new C.a("colorShader",N.getScene(),"color",I),N}return Object(B.d)(S,A),S.prototype._addClipPlaneDefine=function(g){var l="#define "+g;this._colorShader.options.defines.indexOf(l)===-1&&this._colorShader.options.defines.push(l)},S.prototype._removeClipPlaneDefine=function(g){var l="#define "+g,h=this._colorShader.options.defines.indexOf(l);h!==-1&&this._colorShader.options.defines.splice(h,1)},S.prototype.isReady=function(){var g=this.getScene();return g.clipPlane?this._addClipPlaneDefine("CLIPPLANE"):this._removeClipPlaneDefine("CLIPPLANE"),g.clipPlane2?this._addClipPlaneDefine("CLIPPLANE2"):this._removeClipPlaneDefine("CLIPPLANE2"),g.clipPlane3?this._addClipPlaneDefine("CLIPPLANE3"):this._removeClipPlaneDefine("CLIPPLANE3"),g.clipPlane4?this._addClipPlaneDefine("CLIPPLANE4"):this._removeClipPlaneDefine("CLIPPLANE4"),g.clipPlane5?this._addClipPlaneDefine("CLIPPLANE5"):this._removeClipPlaneDefine("CLIPPLANE5"),g.clipPlane6?this._addClipPlaneDefine("CLIPPLANE6"):this._removeClipPlaneDefine("CLIPPLANE6"),!!this._colorShader.isReady(this)&&A.prototype.isReady.call(this)},S.prototype.getClassName=function(){return"LinesMesh"},Object.defineProperty(S.prototype,"material",{get:function(){return this._colorShader},set:function(g){},enumerable:!1,configurable:!0}),Object.defineProperty(S.prototype,"checkCollisions",{get:function(){return!1},enumerable:!1,configurable:!0}),S.prototype._bind=function(g,l,h){if(!this._geometry)return this;var b=this._colorShader.getEffect(),T=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._geometry._bind(b,T),!this.useVertexColor){var D=this.color,w=D.r,N=D.g,I=D.b;this.color4.set(w,N,I,this.alpha),this._colorShader.setColor4("color",this.color4)}return m.a.BindClipPlane(b,this.getScene()),this},S.prototype._draw=function(g,l,h){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var b=this.getScene().getEngine();return this._unIndexed?b.drawArraysType(R.a.LineListDrawMode,g.verticesStart,g.verticesCount,h):b.drawElementsType(R.a.LineListDrawMode,g.indexStart,g.indexCount,h),this},S.prototype.dispose=function(g){this._colorShader.dispose(!1,!1,!0),A.prototype.dispose.call(this,g)},S.prototype.clone=function(g,l,h){return l===void 0&&(l=null),new S(g,this.getScene(),l,this,h)},S.prototype.createInstance=function(g){return new E(g,this)},S}(u.a)),E=function(A){function S(g,l){var h=A.call(this,g,l)||this;return h.intersectionThreshold=l.intersectionThreshold,h}return Object(B.d)(S,A),S.prototype.getClassName=function(){return"InstancedLinesMesh"},S}(M.a)},function(Ae,v,f){f.r(v),f.d(v,"AxesViewer",function(){return R}),f.d(v,"BoneAxesViewer",function(){return c}),f.d(v,"DebugLayerTab",function(){return B}),f.d(v,"DebugLayer",function(){return l}),f.d(v,"PhysicsViewer",function(){return V}),f.d(v,"RayHelper",function(){return j}),f.d(v,"SkeletonViewer",function(){return K});var B,_=f(0),x=f(30),u=f(75),M=f(9),R=function(){function $(L,G,Q,oe,re,Y){if(G===void 0&&(G=1),Q===void 0&&(Q=2),this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this.scaleLines=1,this.scaleLines=G,!oe){var k=new x.a("",L);k.disableLighting=!0,k.emissiveColor=M.a.Red().scale(.5),oe=u.a._CreateArrow(L,k)}if(!re){var H=new x.a("",L);H.disableLighting=!0,H.emissiveColor=M.a.Green().scale(.5),re=u.a._CreateArrow(L,H)}if(!Y){var Z=new x.a("",L);Z.disableLighting=!0,Z.emissiveColor=M.a.Blue().scale(.5),Y=u.a._CreateArrow(L,Z)}this._xAxis=oe,this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis=re,this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis=Y,this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),Q!=null&&($._SetRenderingGroupId(this._xAxis,Q),$._SetRenderingGroupId(this._yAxis,Q),$._SetRenderingGroupId(this._zAxis,Q)),this.scene=L,this.update(new _.e,_.e.Right(),_.e.Up(),_.e.Forward())}return Object.defineProperty($.prototype,"xAxis",{get:function(){return this._xAxis},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"yAxis",{get:function(){return this._yAxis},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"zAxis",{get:function(){return this._zAxis},enumerable:!1,configurable:!0}),$.prototype.update=function(L,G,Q,oe){this._xAxis.position.copyFrom(L),this._xAxis.setDirection(G),this._xAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._yAxis.position.copyFrom(L),this._yAxis.setDirection(Q),this._yAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor),this._zAxis.position.copyFrom(L),this._zAxis.setDirection(oe),this._zAxis.scaling.setAll(this.scaleLines*this._scaleLinesFactor)},$.prototype.createInstance=function(){var L=u.a._CreateArrowInstance(this.scene,this._xAxis),G=u.a._CreateArrowInstance(this.scene,this._yAxis),Q=u.a._CreateArrowInstance(this.scene,this._zAxis),oe=new $(this.scene,this.scaleLines,null,L,G,Q);return oe._instanced=!0,oe},$.prototype.dispose=function(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null},$._SetRenderingGroupId=function(L,G){L.getChildMeshes().forEach(function(Q){Q.renderingGroupId=G})},$}(),C=f(1),m=f(23),c=function($){function L(G,Q,oe,re){re===void 0&&(re=1);var Y=$.call(this,G,re)||this;return Y.pos=_.e.Zero(),Y.xaxis=_.e.Zero(),Y.yaxis=_.e.Zero(),Y.zaxis=_.e.Zero(),Y.mesh=oe,Y.bone=Q,Y}return Object(C.d)(L,$),L.prototype.update=function(){if(this.mesh&&this.bone){var G=this.bone;G._markAsDirtyAndCompose(),G.getAbsolutePositionToRef(this.mesh,this.pos),G.getDirectionToRef(m.a.X,this.mesh,this.xaxis),G.getDirectionToRef(m.a.Y,this.mesh,this.yaxis),G.getDirectionToRef(m.a.Z,this.mesh,this.zaxis),$.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},L.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,$.prototype.dispose.call(this))},L}(R),E=f(12),A=f(6),S=f(20),g=f(13);Object.defineProperty(S.a.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new l(this)),this._debugLayer},enumerable:!0,configurable:!0}),function($){$[$.Properties=0]="Properties",$[$.Debug=1]="Debug",$[$.Statistics=2]="Statistics",$[$.Tools=3]="Tools",$[$.Settings=4]="Settings"}(B||(B={}));var l=function(){function $(L){var G=this;this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=L,this._scene.onDisposeObservable.add(function(){G._scene._debugLayer&&G._scene._debugLayer.hide()})}return Object.defineProperty($.prototype,"onPropertyChangedObservable",{get:function(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new A.c),this._onPropertyChangedObservable)},enumerable:!1,configurable:!0}),$.prototype._createInspector=function(L){if(!this.isVisible()){if(this._onPropertyChangedObservable){for(var G=0,Q=this._onPropertyChangedObservable.observers;G-1&&this._debugMeshMeshes.splice(Y,1),this._numMeshes--,this._numMeshes>0?(this._meshes[oe]=this._meshes[this._numMeshes],this._impostors[oe]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),G=!0;break}G&&this._numMeshes===0&&this._scene.unregisterBeforeRender(this._renderFunction)}},$.prototype._getDebugMaterial=function(L){return this._debugMaterial||(this._debugMaterial=new x.a("",L),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=M.a.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial},$.prototype._getDebugBoxMesh=function(L){return this._debugBoxMesh||(this._debugBoxMesh=b.a.CreateBox("physicsBodyBoxViewMesh",{size:1},L),this._debugBoxMesh.rotationQuaternion=_.b.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(L),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},$.prototype._getDebugSphereMesh=function(L){return this._debugSphereMesh||(this._debugSphereMesh=T.a.CreateSphere("physicsBodySphereViewMesh",{diameter:1},L),this._debugSphereMesh.rotationQuaternion=_.b.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(L),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},$.prototype._getDebugCylinderMesh=function(L){return this._debugCylinderMesh||(this._debugCylinderMesh=I.a.CreateCylinder("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},L),this._debugCylinderMesh.rotationQuaternion=_.b.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(L),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyBoxViewInstance")},$.prototype._getDebugMeshMesh=function(L,G){var Q=new h.a(L.name,G,null,L);return Q.position=_.e.Zero(),Q.setParent(L),Q.material=this._getDebugMaterial(G),this._debugMeshMeshes.push(Q),Q},$.prototype._getDebugMesh=function(L,G){var Q=this;if(!this._utilityLayer||G&&G.parent&&G.parent.physicsImpostor)return null;var oe=null,re=this._utilityLayer.utilityLayerScene;switch(L.type){case w.a.BoxImpostor:oe=this._getDebugBoxMesh(re),L.getBoxSizeToRef(oe.scaling);break;case w.a.SphereImpostor:oe=this._getDebugSphereMesh(re);var Y=L.getRadius();oe.scaling.x=2*Y,oe.scaling.y=2*Y,oe.scaling.z=2*Y;break;case w.a.MeshImpostor:G&&(oe=this._getDebugMeshMesh(G,re));break;case w.a.NoImpostor:G&&G.getChildMeshes().filter(function(H){return H.physicsImpostor?1:0}).forEach(function(H){Q._getDebugBoxMesh(re).parent=H});break;case w.a.CylinderImpostor:oe=this._getDebugCylinderMesh(re);var k=L.object.getBoundingInfo();oe.scaling.x=k.boundingBox.maximum.x-k.boundingBox.minimum.x,oe.scaling.y=k.boundingBox.maximum.y-k.boundingBox.minimum.y,oe.scaling.z=k.boundingBox.maximum.z-k.boundingBox.minimum.z}return oe},$.prototype.dispose=function(){for(var L=this._numMeshes,G=0;G$.DISPLAY_SPHERE_AND_SPURS&&(ze=$.DISPLAY_LINES),this.displayMode=ze,this.update(),this._bindObs()}return $.CreateBoneWeightShader=function(L,G){var Q,oe,re,Y,k,H,Z=L.skeleton,X=(Q=L.colorBase)!==null&&Q!==void 0?Q:M.a.Black(),q=(oe=L.colorZero)!==null&&oe!==void 0?oe:M.a.Blue(),he=(re=L.colorQuarter)!==null&&re!==void 0?re:M.a.Green(),ge=(Y=L.colorHalf)!==null&&Y!==void 0?Y:M.a.Yellow(),me=(k=L.colorFull)!==null&&k!==void 0?k:M.a.Red(),_e=(H=L.targetBoneIndex)!==null&&H!==void 0?H:0;ae.a.ShadersStore["boneWeights:"+Z.name+"VertexShader"]=`precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - - #include - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - - #include - - 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 - #include - - 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; - }`,ae.a.ShadersStore["boneWeights:"+Z.name+"FragmentShader"]=` - precision highp float; - varying vec3 vPosition; - - varying vec3 vColor; - - void main() { - vec4 color = vec4(vColor, 1.0); - gl_FragColor = color; - } - `;var be=new te.a("boneWeight:"+Z.name,G,{vertex:"boneWeights:"+Z.name,fragment:"boneWeights:"+Z.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return be.setColor3("colorBase",X),be.setColor3("colorZero",q),be.setColor3("colorQuarter",he),be.setColor3("colorHalf",ge),be.setColor3("colorFull",me),be.setFloat("targetBoneIndex",_e),be.getClassName=function(){return"BoneWeightShader"},be.transparencyMode=ne.a.MATERIAL_OPAQUE,be},$.CreateSkeletonMapShader=function(L,G){var Q,oe=L.skeleton,re=(Q=L.colorMap)!==null&&Q!==void 0?Q:[{color:new M.a(1,.38,.18),location:0},{color:new M.a(.59,.18,1),location:.2},{color:new M.a(.59,1,.18),location:.4},{color:new M.a(1,.87,.17),location:.6},{color:new M.a(1,.17,.42),location:.8},{color:new M.a(.17,.68,1),location:1}],Y=oe.bones.length+1,k=$._CreateBoneMapColorBuffer(Y,re,G),H=new te.a("boneWeights:"+oe.name,G,{vertexSource:`precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - uniform float colorMap[`+4*oe.bones.length+`]; - - #include - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include - - varying vec3 vColor; - - void main() { - vec3 positionUpdated = position; - - #include - #include - - 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 H.setFloats("colorMap",k),H.getClassName=function(){return"SkeletonMapShader"},H.transparencyMode=ne.a.MATERIAL_OPAQUE,H},$._CreateBoneMapColorBuffer=function(L,G,Q){var oe=new de.a("temp",{width:L,height:1},Q,!1),re=oe.getContext(),Y=re.createLinearGradient(0,0,L,0);G.forEach(function(X){Y.addColorStop(X.location,X.color.toHexString())}),re.fillStyle=Y,re.fillRect(0,0,L,1),oe.update();for(var k=[],H=re.getImageData(0,0,L,1).data,Z=0;Z$.DISPLAY_SPHERE_AND_SPURS&&(L=$.DISPLAY_LINES),this.options.displayMode=L},enumerable:!1,configurable:!0}),$.prototype._bindObs=function(){var L=this;switch(this.displayMode){case $.DISPLAY_LINES:this._obs=this.scene.onBeforeRenderObservable.add(function(){L._displayLinesUpdate()})}},$.prototype.update=function(){switch(this.displayMode){case $.DISPLAY_LINES:this._displayLinesUpdate();break;case $.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case $.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()},Object.defineProperty($.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(L){this.isEnabled!==L&&(this._isEnabled=L,this.debugMesh&&this.debugMesh.setEnabled(L),L&&!this._obs?this._bindObs():!L&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))},enumerable:!1,configurable:!0}),$.prototype._getBonePosition=function(L,G,Q,oe,re,Y){oe===void 0&&(oe=0),re===void 0&&(re=0),Y===void 0&&(Y=0);var k=_.c.Matrix[0],H=G.getParent();if(k.copyFrom(G.getLocalMatrix()),oe!==0||re!==0||Y!==0){var Z=_.c.Matrix[1];_.a.IdentityToRef(Z),Z.setTranslationFromFloats(oe,re,Y),Z.multiplyToRef(k,k)}H&&k.multiplyToRef(H.getAbsoluteTransform(),k),k.multiplyToRef(Q,k),L.x=k.m[12],L.y=k.m[13],L.z=k.m[14]},$.prototype._getLinesForBonesWithLength=function(L,G){for(var Q=L.length,oe=this.mesh._effectiveMesh.position,re=0,Y=0;Y=0;Y--){var k=L[Y],H=k.getParent();if(H&&(this._boneIndices.has(k.getIndex())||this.options.useAllBones)){var Z=this._debugLines[Q];Z||(Z=[_.e.Zero(),_.e.Zero()],this._debugLines[Q]=Z),k.getAbsolutePositionToRef(oe,Z[0]),H.getAbsolutePositionToRef(oe,Z[1]),Z[0].subtractInPlace(re),Z[1].subtractInPlace(re),Q++}}},$.prototype._revert=function(L){this.options.pauseAnimations&&(this.scene.animationsEnabled=L,this.utilityLayer.utilityLayerScene.animationsEnabled=L)},$.prototype._getAbsoluteBindPoseToRef=function(L,G){L!==null&&L._index!==-1?(this._getAbsoluteBindPoseToRef(L.getParent(),G),L.getBindPose().multiplyToRef(G,G)):G.copyFrom(_.a.Identity())},$.prototype._buildSpheresAndSpurs=function(L){var G,Q;L===void 0&&(L=!0),this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;var oe=(G=this.utilityLayer)===null||G===void 0?void 0:G.utilityLayerScene,re=this.skeleton.bones,Y=[],k=[],H=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,oe.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms();for(var Z=Number.NEGATIVE_INFINITY,X=this.options.displayOptions||{},q=function(We){var Ze=re[We];if(Ze._index===-1||!he._boneIndices.has(Ze.getIndex())&&!he.options.useAllBones)return"continue";var ze=new _.a;he._getAbsoluteBindPoseToRef(Ze,ze);var it=new _.e;ze.decompose(void 0,void 0,it),Ze.children.forEach(function(It,Pt){var Ot=new _.a;It.getBindPose().multiplyToRef(ze,Ot);var on=new _.e;Ot.decompose(void 0,void 0,on);var Zt=_.e.Distance(it,on);if(Zt>Z&&(Z=Zt),!L){for(var tn=on.clone().subtract(it.clone()),De=tn.length(),Sn=tn.normalize().scale(De),nn=X.midStep||.165,An=X.midStepFactor||.215,Ue=Sn.scale(nn),Pn=ee.a.ExtrudeShapeCustom("skeletonViewer",{shape:[new _.e(1,-1,0),new _.e(1,1,0),new _.e(-1,1,0),new _.e(-1,-1,0),new _.e(1,-1,0)],path:[_.e.Zero(),Ue,Sn],scaleFunction:function(Fo){switch(Fo){case 0:case 2:return 0;case 1:return De*An}return 0},sideOrientation:h.a.DEFAULTSIDE,updatable:!1},oe),hr=Pn.getTotalVertices(),Ye=[],En=[],Zn=0;Zn9?En.push(It.getIndex(),0,0,0):En.push(Ze.getIndex(),0,0,0);Pn.position=it.clone(),Pn.setVerticesData(pe.b.MatricesWeightsKind,Ye,!1),Pn.setVerticesData(pe.b.MatricesIndicesKind,En,!1),Pn.convertToFlatShadedMesh(),k.push(Pn)}});for(var et=X.sphereBaseSize||.2,lt=T.a.CreateSphere("skeletonViewer",{segments:6,diameter:et,updatable:!0},oe),ct=lt.getTotalVertices(),mt=[],St=[],wt=0;wth-c)&&!(g-bb-E)&&!(l-TT-A)},M.prototype.intersectsSphere=function(R){return M.IntersectsSphere(this.minimumWorld,this.maximumWorld,R.centerWorld,R.radiusWorld)},M.prototype.intersectsMinMax=function(R,C){var m=this.minimumWorld,c=this.maximumWorld,E=m.x,A=m.y,S=m.z,g=c.x,l=c.y,h=c.z,b=R.x,T=R.y,D=R.z,w=C.x,N=C.y,I=C.z;return!(gw)&&!(lN)&&!(hI)},M.Intersects=function(R,C){return R.intersectsMinMax(C.minimumWorld,C.maximumWorld)},M.IntersectsSphere=function(R,C,m,c){var E=M.TmpVector3[0];return _.e.ClampToRef(m,R,C,E),_.e.DistanceSquared(m,E)<=c*c},M.IsCompletelyInFrustum=function(R,C){for(var m=0;m<6;++m)for(var c=C[m],E=0;E<8;++E)if(c.dotCoordinate(R[E])<0)return!1;return!0},M.IsInFrustum=function(R,C){for(var m=0;m<6;++m){for(var c=!0,E=C[m],A=0;A<8;++A)if(E.dotCoordinate(R[A])>=0){c=!1;break}if(c)return!1}return!0},M.TmpVector3=B.a.BuildArray(3,_.e.Zero),M}()},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(38),_=function(){function x(){}return x.SetImmediate=function(u){B.a.IsWindowObjectExist()&&window.setImmediate?window.setImmediate(u):setTimeout(u,1)},x}()},function(Ae,v,f){f.d(v,"a",function(){return x});var B=f(0),_=f(2),x=function(){function u(){this.previousWorldMatrices={},this.previousBones={}}return u.AddUniforms=function(M){M.push("previousWorld","previousViewProjection")},u.AddSamplers=function(M){},u.prototype.bindForSubMesh=function(M,R,C,m,c){R.prePassRenderer&&R.prePassRenderer.enabled&&R.prePassRenderer.getIndex(_.a.PREPASS_VELOCITY_TEXTURE_TYPE)!==-1&&(this.previousWorldMatrices[C.uniqueId]||(this.previousWorldMatrices[C.uniqueId]=B.a.Identity()),this.previousViewProjection||(this.previousViewProjection=R.getTransformMatrix()),M.setMatrix("previousWorld",this.previousWorldMatrices[C.uniqueId]),M.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[C.uniqueId]=m.clone(),this.previousViewProjection=R.getTransformMatrix().clone())},u}()},function(Ae,v,f){var B="lightFragmentDeclaration",_=`#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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="lightUboDeclaration",_=`#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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="imageProcessingDeclaration",_=`#ifdef EXPOSURE -uniform float exposureLinear; -#endif -#ifdef CONTRAST -uniform float contrast; -#endif -#ifdef VIGNETTE -uniform vec2 vInverseScreenSize; -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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="imageProcessingFunctions",_=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) - -#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 -vec4 applyImageProcessing(vec4 result) { -#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 -return result; -}`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="clipPlaneFragment",_=`#ifdef CLIPPLANE -if (fClipDistance>0.0) -{ -discard; -} -#endif -#ifdef CLIPPLANE2 -if (fClipDistance2>0.0) -{ -discard; -} -#endif -#ifdef CLIPPLANE3 -if (fClipDistance3>0.0) -{ -discard; -} -#endif -#ifdef CLIPPLANE4 -if (fClipDistance4>0.0) -{ -discard; -} -#endif -#ifdef CLIPPLANE5 -if (fClipDistance5>0.0) -{ -discard; -} -#endif -#ifdef CLIPPLANE6 -if (fClipDistance6>0.0) -{ -discard; -} -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="clipPlaneVertex",_=`#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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){this._count=0,this._data={}}return _.prototype.copyFrom=function(x){var u=this;this.clear(),x.forEach(function(M,R){return u.add(M,R)})},_.prototype.get=function(x){var u=this._data[x];if(u!==void 0)return u},_.prototype.getOrAddWithFactory=function(x,u){var M=this.get(x);return M!==void 0||(M=u(x))&&this.add(x,M),M},_.prototype.getOrAdd=function(x,u){var M=this.get(x);return M!==void 0?M:(this.add(x,u),u)},_.prototype.contains=function(x){return this._data[x]!==void 0},_.prototype.add=function(x,u){return this._data[x]===void 0&&(this._data[x]=u,++this._count,!0)},_.prototype.set=function(x,u){return this._data[x]!==void 0&&(this._data[x]=u,!0)},_.prototype.getAndRemove=function(x){var u=this.get(x);return u!==void 0?(delete this._data[x],--this._count,u):null},_.prototype.remove=function(x){return!!this.contains(x)&&(delete this._data[x],--this._count,!0)},_.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(_.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),_.prototype.forEach=function(x){for(var u in this._data)x(u,this._data[u])},_.prototype.first=function(x){for(var u in this._data){var M=x(u,this._data[u]);if(M)return M}return null},_}()},function(Ae,v,f){f.d(v,"a",function(){return x});var B=f(44),_=f(0),x=function(){function u(M,R,C){this.center=_.e.Zero(),this.centerWorld=_.e.Zero(),this.minimum=_.e.Zero(),this.maximum=_.e.Zero(),this.reConstruct(M,R,C)}return u.prototype.reConstruct=function(M,R,C){this.minimum.copyFrom(M),this.maximum.copyFrom(R);var m=_.e.Distance(M,R);R.addToRef(M,this.center).scaleInPlace(.5),this.radius=.5*m,this._update(C||_.a.IdentityReadOnly)},u.prototype.scale=function(M){var R=this.radius*M,C=u.TmpVector3,m=C[0].setAll(R),c=this.center.subtractToRef(m,C[1]),E=this.center.addToRef(m,C[2]);return this.reConstruct(c,E,this._worldMatrix),this},u.prototype.getWorldMatrix=function(){return this._worldMatrix},u.prototype._update=function(M){if(M.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{_.e.TransformCoordinatesToRef(this.center,M,this.centerWorld);var R=u.TmpVector3[0];_.e.TransformNormalFromFloatsToRef(1,1,1,M,R),this.radiusWorld=Math.max(Math.abs(R.x),Math.abs(R.y),Math.abs(R.z))*this.radius}},u.prototype.isInFrustum=function(M){for(var R=this.centerWorld,C=this.radiusWorld,m=0;m<6;m++)if(M[m].dotCoordinate(R)<=-C)return!1;return!0},u.prototype.isCenterInFrustum=function(M){for(var R=this.centerWorld,C=0;C<6;C++)if(M[C].dotCoordinate(R)<0)return!1;return!0},u.prototype.intersectsPoint=function(M){var R=_.e.DistanceSquared(this.centerWorld,M);return!(this.radiusWorld*this.radiusWorld=R&&u===0?x instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,u,new Float32Array(x)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,u,x):x instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(x).subarray(u,u+M)):(x=x instanceof ArrayBuffer?new Uint8Array(x,u,M):new Uint8Array(x.buffer,x.byteOffset+u,M),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,x)),this._resetVertexBufferBinding()}},function(Ae,v,f){var B="fogFragmentDeclaration",_=`#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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=f(26),_=f(27);B.a.prototype.createDynamicTexture=function(x,u,M,R){var C=new _.a(this,_.b.Dynamic);return C.baseWidth=x,C.baseHeight=u,M&&(x=this.needPOTTextures?B.a.GetExponentOfTwo(x,this._caps.maxTextureSize):x,u=this.needPOTTextures?B.a.GetExponentOfTwo(u,this._caps.maxTextureSize):u),C.width=x,C.height=u,C.isReady=!1,C.generateMipMaps=M,C.samplingMode=R,this.updateTextureSamplingMode(R,C),this._internalTexturesCache.push(C),C},B.a.prototype.updateDynamicTexture=function(x,u,M,R,C,m){if(R===void 0&&(R=!1),m===void 0&&(m=!1),x){var c=this._gl,E=c.TEXTURE_2D,A=this._bindTextureDirectly(E,x,!0,m);this._unpackFlipY(M===void 0?x.invertY:M),R&&c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var S=this._getWebGLTextureType(x.type),g=this._getInternalFormat(C||x.format),l=this._getRGBABufferInternalSizedFormat(x.type,g);c.texImage2D(E,0,l,g,S,u),x.generateMipMaps&&c.generateMipmap(E),A||this._bindTextureDirectly(E,null),R&&c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),x.isReady=!0}}},function(Ae,v,f){f.r(v),f.d(v,"AbstractScene",function(){return B.a}),f.d(v,"AbstractActionManager",function(){return _.a}),f.d(v,"Action",function(){return C}),f.d(v,"ActionEvent",function(){return m.a}),f.d(v,"ActionManager",function(){return pe}),f.d(v,"Condition",function(){return E}),f.d(v,"ValueCondition",function(){return A}),f.d(v,"PredicateCondition",function(){return S}),f.d(v,"StateCondition",function(){return g}),f.d(v,"SwitchBooleanAction",function(){return b}),f.d(v,"SetStateAction",function(){return T}),f.d(v,"SetValueAction",function(){return D}),f.d(v,"IncrementValueAction",function(){return w}),f.d(v,"PlayAnimationAction",function(){return N}),f.d(v,"StopAnimationAction",function(){return I}),f.d(v,"DoNothingAction",function(){return V}),f.d(v,"CombineAction",function(){return W}),f.d(v,"ExecuteCodeAction",function(){return j}),f.d(v,"SetParentAction",function(){return ne}),f.d(v,"PlaySoundAction",function(){return ae}),f.d(v,"StopSoundAction",function(){return ee}),f.d(v,"InterpolateValueAction",function(){return H}),f.d(v,"Animatable",function(){return Ge}),f.d(v,"_IAnimationState",function(){return Y}),f.d(v,"Animation",function(){return k}),f.d(v,"TargetedAnimation",function(){return Xe}),f.d(v,"AnimationGroup",function(){return He}),f.d(v,"AnimationPropertiesOverride",function(){return We}),f.d(v,"EasingFunction",function(){return ze}),f.d(v,"CircleEase",function(){return it}),f.d(v,"BackEase",function(){return et}),f.d(v,"BounceEase",function(){return lt}),f.d(v,"CubicEase",function(){return ct}),f.d(v,"ElasticEase",function(){return mt}),f.d(v,"ExponentialEase",function(){return St}),f.d(v,"PowerEase",function(){return wt}),f.d(v,"QuadraticEase",function(){return It}),f.d(v,"QuarticEase",function(){return Pt}),f.d(v,"QuinticEase",function(){return Ot}),f.d(v,"SineEase",function(){return on}),f.d(v,"BezierCurveEase",function(){return Zt}),f.d(v,"RuntimeAnimation",function(){return me}),f.d(v,"AnimationEvent",function(){return tn}),f.d(v,"AnimationKeyInterpolation",function(){return K}),f.d(v,"AnimationRange",function(){return G}),f.d(v,"KeepAssets",function(){return Sn}),f.d(v,"InstantiatedEntries",function(){return nn}),f.d(v,"AssetContainer",function(){return An}),f.d(v,"Analyser",function(){return Pn}),f.d(v,"AudioEngine",function(){return hr}),f.d(v,"AudioSceneComponent",function(){return Jn}),f.d(v,"Sound",function(){return Zn}),f.d(v,"SoundTrack",function(){return Fo}),f.d(v,"WeightedSound",function(){return $f}),f.d(v,"AutoRotationBehavior",function(){return El}),f.d(v,"BouncingBehavior",function(){return Sl}),f.d(v,"FramingBehavior",function(){return Al}),f.d(v,"AttachToBoxBehavior",function(){return ep}),f.d(v,"FadeInOutBehavior",function(){return tp}),f.d(v,"MultiPointerScaleBehavior",function(){return np}),f.d(v,"PointerDragBehavior",function(){return bi.a}),f.d(v,"SixDofDragBehavior",function(){return Pl}),f.d(v,"Bone",function(){return Be}),f.d(v,"BoneIKController",function(){return ip}),f.d(v,"BoneLookController",function(){return rp}),f.d(v,"Skeleton",function(){return Bo}),f.d(v,"ArcRotateCameraGamepadInput",function(){return Ka}),f.d(v,"ArcRotateCameraKeyboardMoveInput",function(){return Qa}),f.d(v,"ArcRotateCameraMouseWheelInput",function(){return qa}),f.d(v,"ArcRotateCameraPointersInput",function(){return Za}),f.d(v,"ArcRotateCameraVRDeviceOrientationInput",function(){return Ja}),f.d(v,"FlyCameraKeyboardInput",function(){return $a}),f.d(v,"FlyCameraMouseInput",function(){return es}),f.d(v,"FollowCameraKeyboardMoveInput",function(){return ts}),f.d(v,"FollowCameraMouseWheelInput",function(){return ns}),f.d(v,"FollowCameraPointersInput",function(){return is}),f.d(v,"FreeCameraDeviceOrientationInput",function(){return cs}),f.d(v,"FreeCameraGamepadInput",function(){return ls}),f.d(v,"FreeCameraKeyboardMoveInput",function(){return rs}),f.d(v,"FreeCameraMouseInput",function(){return os}),f.d(v,"FreeCameraMouseWheelInput",function(){return as}),f.d(v,"FreeCameraTouchInput",function(){return ss}),f.d(v,"FreeCameraVirtualJoystickInput",function(){return hs}),f.d(v,"CameraInputTypes",function(){return un}),f.d(v,"CameraInputsManager",function(){return Jr}),f.d(v,"Camera",function(){return gt.a}),f.d(v,"TargetCamera",function(){return Ii}),f.d(v,"FreeCamera",function(){return Hn}),f.d(v,"FreeCameraInputsManager",function(){return $r}),f.d(v,"TouchCamera",function(){return ds}),f.d(v,"ArcRotateCamera",function(){return Zi}),f.d(v,"ArcRotateCameraInputsManager",function(){return Uo}),f.d(v,"DeviceOrientationCamera",function(){return Vo}),f.d(v,"FlyCamera",function(){return sp}),f.d(v,"FlyCameraInputsManager",function(){return Dl}),f.d(v,"FollowCamera",function(){return Nl}),f.d(v,"ArcFollowCamera",function(){return wl}),f.d(v,"FollowCameraInputsManager",function(){return Ll}),f.d(v,"GamepadCamera",function(){return ko}),f.d(v,"AnaglyphArcRotateCamera",function(){return Gl}),f.d(v,"AnaglyphFreeCamera",function(){return zl}),f.d(v,"AnaglyphGamepadCamera",function(){return jl}),f.d(v,"AnaglyphUniversalCamera",function(){return Hl}),f.d(v,"StereoscopicArcRotateCamera",function(){return Wl}),f.d(v,"StereoscopicFreeCamera",function(){return Xl}),f.d(v,"StereoscopicGamepadCamera",function(){return Yl}),f.d(v,"StereoscopicUniversalCamera",function(){return Kl}),f.d(v,"UniversalCamera",function(){return pr}),f.d(v,"VirtualJoysticksCamera",function(){return Ql}),f.d(v,"VRCameraMetrics",function(){return _r}),f.d(v,"VRDeviceOrientationArcRotateCamera",function(){return $l}),f.d(v,"VRDeviceOrientationFreeCamera",function(){return Go}),f.d(v,"VRDeviceOrientationGamepadCamera",function(){return eu}),f.d(v,"OnAfterEnteringVRObservableEvent",function(){return gp}),f.d(v,"VRExperienceHelper",function(){return ru}),f.d(v,"WebVRFreeCamera",function(){return jo}),f.d(v,"Collider",function(){return ou}),f.d(v,"DefaultCollisionCoordinator",function(){return au}),f.d(v,"PickingInfo",function(){return tr.a}),f.d(v,"IntersectionInfo",function(){return vp.a}),f.d(v,"_MeshCollisionData",function(){return bp.a}),f.d(v,"BoundingBox",function(){return Ts.a}),f.d(v,"BoundingInfo",function(){return Fi.a}),f.d(v,"BoundingSphere",function(){return su.a}),f.d(v,"Octree",function(){return to}),f.d(v,"OctreeBlock",function(){return cu}),f.d(v,"OctreeSceneComponent",function(){return Cs}),f.d(v,"Ray",function(){return dn.a}),f.d(v,"AxesViewer",function(){return nr.AxesViewer}),f.d(v,"BoneAxesViewer",function(){return nr.BoneAxesViewer}),f.d(v,"DebugLayerTab",function(){return nr.DebugLayerTab}),f.d(v,"DebugLayer",function(){return nr.DebugLayer}),f.d(v,"PhysicsViewer",function(){return nr.PhysicsViewer}),f.d(v,"RayHelper",function(){return nr.RayHelper}),f.d(v,"SkeletonViewer",function(){return nr.SkeletonViewer}),f.d(v,"DeviceInputSystem",function(){return lu}),f.d(v,"DeviceType",function(){return Kt}),f.d(v,"PointerInput",function(){return Es}),f.d(v,"DualShockInput",function(){return Ss}),f.d(v,"XboxInput",function(){return As}),f.d(v,"SwitchInput",function(){return Ps}),f.d(v,"DeviceSource",function(){return uu}),f.d(v,"DeviceSourceManager",function(){return yp}),f.d(v,"Constants",function(){return h.a}),f.d(v,"ThinEngine",function(){return Bt.a}),f.d(v,"Engine",function(){return Ue.a}),f.d(v,"EngineStore",function(){return te.a}),f.d(v,"NullEngineOptions",function(){return hu.b}),f.d(v,"NullEngine",function(){return hu.a}),f.d(v,"_OcclusionDataStorage",function(){return fu}),f.d(v,"_forceTransformFeedbackToBundle",function(){return Tp}),f.d(v,"EngineView",function(){return Ep}),f.d(v,"WebGLPipelineContext",function(){return Ap.a}),f.d(v,"WebGL2ShaderProcessor",function(){return pu.a}),f.d(v,"NativeEngine",function(){return Op}),f.d(v,"ShaderCodeInliner",function(){return Rs}),f.d(v,"PerformanceConfigurator",function(){return Mp.a}),f.d(v,"KeyboardEventTypes",function(){return qi.a}),f.d(v,"KeyboardInfo",function(){return qi.b}),f.d(v,"KeyboardInfoPre",function(){return qi.c}),f.d(v,"PointerEventTypes",function(){return Tt.a}),f.d(v,"PointerInfoBase",function(){return Tt.c}),f.d(v,"PointerInfoPre",function(){return Tt.d}),f.d(v,"PointerInfo",function(){return Tt.b}),f.d(v,"ClipboardEventTypes",function(){return Yo}),f.d(v,"ClipboardInfo",function(){return Ip}),f.d(v,"DaydreamController",function(){return Ms}),f.d(v,"GearVRController",function(){return Is}),f.d(v,"GenericController",function(){return Ko}),f.d(v,"OculusTouchController",function(){return Ds}),f.d(v,"PoseEnabledControllerType",function(){return ei}),f.d(v,"PoseEnabledControllerHelper",function(){return Di}),f.d(v,"PoseEnabledController",function(){return fr}),f.d(v,"ViveController",function(){return vu}),f.d(v,"WebVRController",function(){return Ni}),f.d(v,"WindowsMotionController",function(){return Qo}),f.d(v,"XRWindowsMotionController",function(){return Lp}),f.d(v,"StickValues",function(){return op}),f.d(v,"Gamepad",function(){return hn}),f.d(v,"GenericPad",function(){return Ol}),f.d(v,"GamepadManager",function(){return Ul}),f.d(v,"GamepadSystemSceneComponent",function(){return Vl}),f.d(v,"Xbox360Button",function(){return Cn}),f.d(v,"Xbox360Dpad",function(){return Ji}),f.d(v,"Xbox360Pad",function(){return Fl}),f.d(v,"DualShockButton",function(){return Gn}),f.d(v,"DualShockDpad",function(){return $i}),f.d(v,"DualShockPad",function(){return Bl}),f.d(v,"AxisDragGizmo",function(){return qo.a}),f.d(v,"AxisScaleGizmo",function(){return ro}),f.d(v,"BoundingBoxGizmo",function(){return bu}),f.d(v,"Gizmo",function(){return Ln.a}),f.d(v,"GizmoManager",function(){return Np}),f.d(v,"PlaneRotationGizmo",function(){return Zo}),f.d(v,"PositionGizmo",function(){return Tu}),f.d(v,"RotationGizmo",function(){return yu}),f.d(v,"ScaleGizmo",function(){return Eu}),f.d(v,"LightGizmo",function(){return wp}),f.d(v,"CameraGizmo",function(){return Bp}),f.d(v,"PlaneDragGizmo",function(){return Jo}),f.d(v,"EnvironmentHelper",function(){return Us}),f.d(v,"PhotoDome",function(){return Qp}),f.d(v,"_forceSceneHelpersToBundle",function(){return k_}),f.d(v,"VideoDome",function(){return G_}),f.d(v,"EngineInstrumentation",function(){return z_}),f.d(v,"SceneInstrumentation",function(){return j_}),f.d(v,"_TimeToken",function(){return du}),f.d(v,"EffectLayer",function(){return fo}),f.d(v,"EffectLayerSceneComponent",function(){return Vu}),f.d(v,"GlowLayer",function(){return sa}),f.d(v,"HighlightLayer",function(){return Xs}),f.d(v,"Layer",function(){return Z_}),f.d(v,"LayerSceneComponent",function(){return Gu}),f.d(v,"LensFlare",function(){return zu}),f.d(v,"LensFlareSystem",function(){return Ys}),f.d(v,"LensFlareSystemSceneComponent",function(){return ju}),f.d(v,"Light",function(){return Ci.a}),f.d(v,"ShadowLight",function(){return $o}),f.d(v,"ShadowGenerator",function(){return Fn}),f.d(v,"CascadedShadowGenerator",function(){return Ks}),f.d(v,"ShadowGeneratorSceneComponent",function(){return qu}),f.d(v,"DirectionalLight",function(){return Ns}),f.d(v,"HemisphericLight",function(){return zo.a}),f.d(v,"PointLight",function(){return Qs}),f.d(v,"SpotLight",function(){return ws}),f.d(v,"DefaultLoadingScreen",function(){return Zu}),f.d(v,"_BabylonLoaderRegistered",function(){return mm}),f.d(v,"BabylonFileLoaderConfiguration",function(){return da}),f.d(v,"SceneLoaderAnimationGroupLoadingMode",function(){return Ai}),f.d(v,"SceneLoader",function(){return Ut}),f.d(v,"SceneLoaderFlags",function(){return Pi.a}),f.d(v,"BackgroundMaterial",function(){return ao}),f.d(v,"ColorCurves",function(){return vm.a}),f.d(v,"EffectFallbacks",function(){return Er.a}),f.d(v,"Effect",function(){return je.a}),f.d(v,"FresnelParameters",function(){return lh}),f.d(v,"ImageProcessingConfigurationDefines",function(){return vn.b}),f.d(v,"ImageProcessingConfiguration",function(){return vn.a}),f.d(v,"Material",function(){return Ht.a}),f.d(v,"MaterialDefines",function(){return ta.a}),f.d(v,"ThinMaterialHelper",function(){return uh.a}),f.d(v,"MaterialHelper",function(){return tt.a}),f.d(v,"MultiMaterial",function(){return ir.a}),f.d(v,"PBRMaterialDefines",function(){return ks}),f.d(v,"PBRBaseMaterial",function(){return pn}),f.d(v,"PBRBaseSimpleMaterial",function(){return ec}),f.d(v,"PBRMaterial",function(){return lo}),f.d(v,"PBRMetallicRoughnessMaterial",function(){return hh}),f.d(v,"PBRSpecularGlossinessMaterial",function(){return dh}),f.d(v,"PushMaterial",function(){return na.a}),f.d(v,"ShaderMaterial",function(){return fa.a}),f.d(v,"StandardMaterialDefines",function(){return Ft.b}),f.d(v,"StandardMaterial",function(){return Ft.a}),f.d(v,"BaseTexture",function(){return zn.a}),f.d(v,"ColorGradingTexture",function(){return fh}),f.d(v,"CubeTexture",function(){return ni}),f.d(v,"DynamicTexture",function(){return yi.a}),f.d(v,"EquiRectangularCubeTexture",function(){return ph}),f.d(v,"HDRFiltering",function(){return th}),f.d(v,"HDRCubeTexture",function(){return la}),f.d(v,"HtmlElementTexture",function(){return bm}),f.d(v,"InternalTextureSource",function(){return xt.b}),f.d(v,"InternalTexture",function(){return xt.a}),f.d(v,"_DDSTextureLoader",function(){return xu}),f.d(v,"_ENVTextureLoader",function(){return Ru}),f.d(v,"_KTXTextureLoader",function(){return Ou}),f.d(v,"_TGATextureLoader",function(){return _h}),f.d(v,"_BasisTextureLoader",function(){return mh}),f.d(v,"MirrorTexture",function(){return Bs}),f.d(v,"MultiRenderTarget",function(){return tc}),f.d(v,"TexturePacker",function(){return Em}),f.d(v,"TexturePackerFrame",function(){return nc}),f.d(v,"CustomProceduralTexture",function(){return Am}),f.d(v,"NoiseProceduralTexture",function(){return vh}),f.d(v,"ProceduralTexture",function(){return mo}),f.d(v,"ProceduralTextureSceneComponent",function(){return gh}),f.d(v,"RawCubeTexture",function(){return Cm}),f.d(v,"RawTexture",function(){return $n}),f.d(v,"RawTexture2DArray",function(){return xm}),f.d(v,"RawTexture3D",function(){return Rm}),f.d(v,"RefractionTexture",function(){return Om}),f.d(v,"RenderTargetTexture",function(){return sn}),f.d(v,"Texture",function(){return we.a}),f.d(v,"VideoTexture",function(){return Uu}),f.d(v,"UniformBuffer",function(){return ql.a}),f.d(v,"MaterialFlags",function(){return ht.a}),f.d(v,"NodeMaterialBlockTargets",function(){return Re}),f.d(v,"NodeMaterialBlockConnectionPointTypes",function(){return le}),f.d(v,"NodeMaterialBlockConnectionPointMode",function(){return gn}),f.d(v,"NodeMaterialSystemValues",function(){return bt}),f.d(v,"NodeMaterialModes",function(){return Rn}),f.d(v,"NodeMaterialConnectionPointCompatibilityStates",function(){return oi}),f.d(v,"NodeMaterialConnectionPointDirection",function(){return bn}),f.d(v,"NodeMaterialConnectionPoint",function(){return _a}),f.d(v,"NodeMaterialBlock",function(){return pt}),f.d(v,"NodeMaterialDefines",function(){return yo}),f.d(v,"NodeMaterial",function(){return ya}),f.d(v,"VertexOutputBlock",function(){return go}),f.d(v,"BonesBlock",function(){return Sh}),f.d(v,"InstancesBlock",function(){return Ah}),f.d(v,"MorphTargetsBlock",function(){return Ph}),f.d(v,"LightInformationBlock",function(){return Ch}),f.d(v,"FragmentOutputBlock",function(){return Dr}),f.d(v,"ImageProcessingBlock",function(){return xh}),f.d(v,"PerturbNormalBlock",function(){return Rh}),f.d(v,"DiscardBlock",function(){return Oh}),f.d(v,"FrontFacingBlock",function(){return Mh}),f.d(v,"DerivativeBlock",function(){return Ih}),f.d(v,"FragCoordBlock",function(){return Dh}),f.d(v,"ScreenSizeBlock",function(){return Lh}),f.d(v,"FogBlock",function(){return Nh}),f.d(v,"LightBlock",function(){return wh}),f.d(v,"TextureBlock",function(){return Fh}),f.d(v,"ReflectionTextureBlock",function(){return Bh}),f.d(v,"CurrentScreenBlock",function(){return rc}),f.d(v,"InputBlock",function(){return At}),f.d(v,"AnimatedInputBlockTypes",function(){return ki}),f.d(v,"MultiplyBlock",function(){return ga}),f.d(v,"AddBlock",function(){return Uh}),f.d(v,"ScaleBlock",function(){return Vh}),f.d(v,"ClampBlock",function(){return kh}),f.d(v,"CrossBlock",function(){return Gh}),f.d(v,"DotBlock",function(){return zh}),f.d(v,"TransformBlock",function(){return ma}),f.d(v,"RemapBlock",function(){return cc}),f.d(v,"NormalizeBlock",function(){return jh}),f.d(v,"TrigonometryBlockOperations",function(){return rn}),f.d(v,"TrigonometryBlock",function(){return _c}),f.d(v,"ColorMergerBlock",function(){return Hh}),f.d(v,"VectorMergerBlock",function(){return vo}),f.d(v,"ColorSplitterBlock",function(){return pc}),f.d(v,"VectorSplitterBlock",function(){return Wh}),f.d(v,"LerpBlock",function(){return Xh}),f.d(v,"DivideBlock",function(){return Yh}),f.d(v,"SubtractBlock",function(){return Kh}),f.d(v,"StepBlock",function(){return Qh}),f.d(v,"OneMinusBlock",function(){return vc}),f.d(v,"ViewDirectionBlock",function(){return bc}),f.d(v,"FresnelBlock",function(){return qh}),f.d(v,"MaxBlock",function(){return Zh}),f.d(v,"MinBlock",function(){return Jh}),f.d(v,"DistanceBlock",function(){return $h}),f.d(v,"LengthBlock",function(){return ed}),f.d(v,"NegateBlock",function(){return td}),f.d(v,"PowBlock",function(){return nd}),f.d(v,"RandomNumberBlock",function(){return id}),f.d(v,"ArcTan2Block",function(){return rd}),f.d(v,"SmoothStepBlock",function(){return od}),f.d(v,"ReciprocalBlock",function(){return ad}),f.d(v,"ReplaceColorBlock",function(){return sd}),f.d(v,"PosterizeBlock",function(){return cd}),f.d(v,"WaveBlockKind",function(){return rr}),f.d(v,"WaveBlock",function(){return ld}),f.d(v,"GradientBlockColorStep",function(){return Ta}),f.d(v,"GradientBlock",function(){return ud}),f.d(v,"NLerpBlock",function(){return hd}),f.d(v,"WorleyNoise3DBlock",function(){return dd}),f.d(v,"SimplexPerlin3DBlock",function(){return fd}),f.d(v,"NormalBlendBlock",function(){return pd}),f.d(v,"Rotate2dBlock",function(){return _d}),f.d(v,"ReflectBlock",function(){return md}),f.d(v,"RefractBlock",function(){return gd}),f.d(v,"DesaturateBlock",function(){return vd}),f.d(v,"PBRMetallicRoughnessBlock",function(){return bd}),f.d(v,"SheenBlock",function(){return yc}),f.d(v,"AnisotropyBlock",function(){return Tc}),f.d(v,"ReflectionBlock",function(){return Ec}),f.d(v,"ClearCoatBlock",function(){return Ea}),f.d(v,"RefractionBlock",function(){return Sc}),f.d(v,"SubSurfaceBlock",function(){return Sa}),f.d(v,"ParticleTextureBlock",function(){return oc}),f.d(v,"ParticleRampGradientBlock",function(){return ac}),f.d(v,"ParticleBlendMultiplyBlock",function(){return sc}),f.d(v,"ModBlock",function(){return yd}),f.d(v,"NodeMaterialOptimizer",function(){return Nm}),f.d(v,"PropertyTypeForEdition",function(){return Lt}),f.d(v,"editableInPropertyPage",function(){return Vt}),f.d(v,"EffectRenderer",function(){return $u}),f.d(v,"EffectWrapper",function(){return eh}),f.d(v,"ShadowDepthWrapper",function(){return Bm}),f.d(v,"Scalar",function(){return $.a}),f.d(v,"extractMinAndMaxIndexed",function(){return Td.b}),f.d(v,"extractMinAndMax",function(){return Td.a}),f.d(v,"Space",function(){return ye.c}),f.d(v,"Axis",function(){return ye.a}),f.d(v,"Coordinate",function(){return ye.b}),f.d(v,"Color3",function(){return M.a}),f.d(v,"Color4",function(){return M.b}),f.d(v,"TmpColors",function(){return M.c}),f.d(v,"ToGammaSpace",function(){return Gt.b}),f.d(v,"ToLinearSpace",function(){return Gt.c}),f.d(v,"Epsilon",function(){return Gt.a}),f.d(v,"Frustum",function(){return Jl.a}),f.d(v,"Orientation",function(){return Ze.e}),f.d(v,"BezierCurve",function(){return Ze.c}),f.d(v,"Angle",function(){return Ze.a}),f.d(v,"Arc2",function(){return Ze.b}),f.d(v,"Path2",function(){return Ze.f}),f.d(v,"Path3D",function(){return Ze.g}),f.d(v,"Curve3",function(){return Ze.d}),f.d(v,"Plane",function(){return gr.a}),f.d(v,"Size",function(){return oe.a}),f.d(v,"Vector2",function(){return u.d}),f.d(v,"Vector3",function(){return u.e}),f.d(v,"Vector4",function(){return u.f}),f.d(v,"Quaternion",function(){return u.b}),f.d(v,"Matrix",function(){return u.a}),f.d(v,"TmpVectors",function(){return u.c}),f.d(v,"PositionNormalVertex",function(){return Fs}),f.d(v,"PositionNormalTextureVertex",function(){return Fp}),f.d(v,"Viewport",function(){return Wn.a}),f.d(v,"SphericalHarmonics",function(){return xs}),f.d(v,"SphericalPolynomial",function(){return io}),f.d(v,"AbstractMesh",function(){return Dt.a}),f.d(v,"Buffer",function(){return Me.a}),f.d(v,"VertexBuffer",function(){return Me.b}),f.d(v,"DracoCompression",function(){return Vm}),f.d(v,"CSG",function(){return zm}),f.d(v,"Geometry",function(){return qs.a}),f.d(v,"GroundMesh",function(){return Wo}),f.d(v,"TrailMesh",function(){return jm}),f.d(v,"InstancedMesh",function(){return Hm.a}),f.d(v,"LinesMesh",function(){return Eo.b}),f.d(v,"InstancedLinesMesh",function(){return Eo.a}),f.d(v,"_CreationDataStorage",function(){return De.b}),f.d(v,"_InstancesBatch",function(){return De.c}),f.d(v,"Mesh",function(){return De.a}),f.d(v,"VertexData",function(){return ft.a}),f.d(v,"MeshBuilder",function(){return Ym}),f.d(v,"SimplificationSettings",function(){return Km}),f.d(v,"SimplificationQueue",function(){return xd}),f.d(v,"SimplificationType",function(){return Po}),f.d(v,"QuadraticErrorSimplification",function(){return Od}),f.d(v,"SimplicationQueueSceneComponent",function(){return Md}),f.d(v,"Polygon",function(){return Xm}),f.d(v,"PolygonMeshBuilder",function(){return Pd}),f.d(v,"SubMesh",function(){return To.a}),f.d(v,"MeshLODLevel",function(){return Jm.a}),f.d(v,"TransformNode",function(){return Tr.a}),f.d(v,"BoxBuilder",function(){return yr.a}),f.d(v,"TiledBoxBuilder",function(){return Ad}),f.d(v,"DiscBuilder",function(){return Aa}),f.d(v,"RibbonBuilder",function(){return So.a}),f.d(v,"SphereBuilder",function(){return Nn.a}),f.d(v,"HemisphereBuilder",function(){return ea}),f.d(v,"CylinderBuilder",function(){return ui.a}),f.d(v,"TorusBuilder",function(){return mr}),f.d(v,"TorusKnotBuilder",function(){return Cc}),f.d(v,"LinesBuilder",function(){return cn.a}),f.d(v,"PolygonBuilder",function(){return Ao}),f.d(v,"ShapeBuilder",function(){return ha.a}),f.d(v,"LatheBuilder",function(){return Rc}),f.d(v,"PlaneBuilder",function(){return Ls.a}),f.d(v,"TiledPlaneBuilder",function(){return Cd}),f.d(v,"GroundBuilder",function(){return wi}),f.d(v,"TubeBuilder",function(){return Oc}),f.d(v,"PolyhedronBuilder",function(){return oo}),f.d(v,"IcoSphereBuilder",function(){return Mc}),f.d(v,"DecalBuilder",function(){return Ic}),f.d(v,"CapsuleBuilder",function(){return Dc}),f.d(v,"DataBuffer",function(){return _u.a}),f.d(v,"WebGLDataBuffer",function(){return $m.a}),f.d(v,"MorphTarget",function(){return nh}),f.d(v,"MorphTargetManager",function(){return ua}),f.d(v,"RecastJSPlugin",function(){return eg}),f.d(v,"RecastJSCrowd",function(){return Id}),f.d(v,"Node",function(){return Q.a}),f.d(v,"Database",function(){return Dd}),f.d(v,"BaseParticleSystem",function(){return bo}),f.d(v,"BoxParticleEmitter",function(){return Lr}),f.d(v,"ConeParticleEmitter",function(){return lc}),f.d(v,"CylinderParticleEmitter",function(){return va}),f.d(v,"CylinderDirectedParticleEmitter",function(){return uc}),f.d(v,"HemisphericParticleEmitter",function(){return hc}),f.d(v,"PointParticleEmitter",function(){return dc}),f.d(v,"SphereParticleEmitter",function(){return ba}),f.d(v,"SphereDirectedParticleEmitter",function(){return fc}),f.d(v,"CustomParticleEmitter",function(){return Nr}),f.d(v,"MeshParticleEmitter",function(){return Th}),f.d(v,"GPUParticleSystem",function(){return or}),f.d(v,"Particle",function(){return Nd}),f.d(v,"ParticleHelper",function(){return cg}),f.d(v,"ParticleSystem",function(){return ln}),f.d(v,"ParticleSystemSet",function(){return Pa}),f.d(v,"SolidParticle",function(){return wc}),f.d(v,"ModelShape",function(){return Fc}),f.d(v,"DepthSortedParticle",function(){return wd}),f.d(v,"SolidParticleVertex",function(){return Fd}),f.d(v,"SolidParticleSystem",function(){return lg}),f.d(v,"CloudPoint",function(){return Bd}),f.d(v,"PointsGroup",function(){return Ca}),f.d(v,"PointColor",function(){return yn}),f.d(v,"PointsCloudSystem",function(){return ug}),f.d(v,"SubEmitterType",function(){return wr}),f.d(v,"SubEmitter",function(){return Co}),f.d(v,"PhysicsEngine",function(){return Mr}),f.d(v,"PhysicsEngineSceneComponent",function(){return Ud}),f.d(v,"PhysicsHelper",function(){return hg}),f.d(v,"PhysicsRadialExplosionEventOptions",function(){return Br}),f.d(v,"PhysicsUpdraftEventOptions",function(){return Bc}),f.d(v,"PhysicsVortexEventOptions",function(){return Uc}),f.d(v,"PhysicsRadialImpulseFalloff",function(){return xo}),f.d(v,"PhysicsUpdraftMode",function(){return Fr}),f.d(v,"PhysicsImpostor",function(){return Ct.a}),f.d(v,"PhysicsJoint",function(){return en.e}),f.d(v,"DistanceJoint",function(){return en.a}),f.d(v,"MotorEnabledJoint",function(){return en.d}),f.d(v,"HingeJoint",function(){return en.c}),f.d(v,"Hinge2Joint",function(){return en.b}),f.d(v,"CannonJSPlugin",function(){return $s}),f.d(v,"AmmoJSPlugin",function(){return rh}),f.d(v,"OimoJSPlugin",function(){return ih}),f.d(v,"AnaglyphPostProcess",function(){return ps}),f.d(v,"BlackAndWhitePostProcess",function(){return kd}),f.d(v,"BloomEffect",function(){return Gc}),f.d(v,"BloomMergePostProcess",function(){return kc}),f.d(v,"BlurPostProcess",function(){return _n}),f.d(v,"ChromaticAberrationPostProcess",function(){return zc}),f.d(v,"CircleOfConfusionPostProcess",function(){return jc}),f.d(v,"ColorCorrectionPostProcess",function(){return Gd}),f.d(v,"ConvolutionPostProcess",function(){return zd}),f.d(v,"DepthOfFieldBlurPostProcess",function(){return xa}),f.d(v,"DepthOfFieldEffectBlurLevel",function(){return ar}),f.d(v,"DepthOfFieldEffect",function(){return Hc}),f.d(v,"DepthOfFieldMergePostProcessOptions",function(){return Sg}),f.d(v,"DepthOfFieldMergePostProcess",function(){return jd}),f.d(v,"DisplayPassPostProcess",function(){return Hd}),f.d(v,"ExtractHighlightsPostProcess",function(){return Vc}),f.d(v,"FilterPostProcess",function(){return Wd}),f.d(v,"FxaaPostProcess",function(){return Ro}),f.d(v,"GrainPostProcess",function(){return Wc}),f.d(v,"HighlightsPostProcess",function(){return Mg}),f.d(v,"ImageProcessingPostProcess",function(){return Ho}),f.d(v,"MotionBlurPostProcess",function(){return Xc}),f.d(v,"PassPostProcess",function(){return Li}),f.d(v,"PassCubePostProcess",function(){return hp}),f.d(v,"PostProcess",function(){return _t}),f.d(v,"PostProcessManager",function(){return ms.a}),f.d(v,"RefractionPostProcess",function(){return Yd}),f.d(v,"DefaultRenderingPipeline",function(){return qd}),f.d(v,"LensRenderingPipeline",function(){return Vg}),f.d(v,"SSAO2RenderingPipeline",function(){return Zd}),f.d(v,"SSAORenderingPipeline",function(){return Hg}),f.d(v,"StandardRenderingPipeline",function(){return Jd}),f.d(v,"PostProcessRenderEffect",function(){return Rt}),f.d(v,"PostProcessRenderPipeline",function(){return Ur}),f.d(v,"PostProcessRenderPipelineManager",function(){return Kd}),f.d(v,"PostProcessRenderPipelineManagerSceneComponent",function(){return Qd}),f.d(v,"SharpenPostProcess",function(){return Yc}),f.d(v,"StereoscopicInterlacePostProcessI",function(){return Qg}),f.d(v,"StereoscopicInterlacePostProcess",function(){return qg}),f.d(v,"TonemappingOperator",function(){return sr}),f.d(v,"TonemapPostProcess",function(){return Jg}),f.d(v,"VolumetricLightScatteringPostProcess",function(){return $d}),f.d(v,"VRDistortionCorrectionPostProcess",function(){return _s}),f.d(v,"VRMultiviewToSingleviewPostProcess",function(){return gs}),f.d(v,"ScreenSpaceReflectionPostProcess",function(){return Kc}),f.d(v,"ScreenSpaceCurvaturePostProcess",function(){return ef}),f.d(v,"ReflectionProbe",function(){return oh}),f.d(v,"BoundingBoxRenderer",function(){return tf}),f.d(v,"DepthRenderer",function(){return ca}),f.d(v,"DepthRendererSceneComponent",function(){return nf}),f.d(v,"EdgesRenderer",function(){return Qc}),f.d(v,"LineEdgesRenderer",function(){return rf}),f.d(v,"GeometryBufferRenderer",function(){return ai}),f.d(v,"GeometryBufferRendererSceneComponent",function(){return Xd}),f.d(v,"PrePassRenderer",function(){return qc}),f.d(v,"PrePassRendererSceneComponent",function(){return of}),f.d(v,"SubSurfaceSceneComponent",function(){return sf}),f.d(v,"OutlineRenderer",function(){return cf}),f.d(v,"RenderingGroup",function(){return hv.a}),f.d(v,"RenderingGroupInfo",function(){return eo.a}),f.d(v,"RenderingManager",function(){return eo.b}),f.d(v,"UtilityLayerRenderer",function(){return xn.a}),f.d(v,"Scene",function(){return _e.a}),f.d(v,"SceneComponentConstants",function(){return st.a}),f.d(v,"Stage",function(){return st.b}),f.d(v,"Sprite",function(){return lf}),f.d(v,"SpriteManager",function(){return hf}),f.d(v,"SpriteMap",function(){return gv}),f.d(v,"SpritePackedManager",function(){return vv}),f.d(v,"SpriteSceneComponent",function(){return uf}),f.d(v,"AlphaState",function(){return bv.a}),f.d(v,"DepthCullingState",function(){return yv.a}),f.d(v,"StencilState",function(){return Tv.a}),f.d(v,"AndOrNotEvaluator",function(){return Ev.a}),f.d(v,"AssetTaskState",function(){return di}),f.d(v,"AbstractAssetTask",function(){return fi}),f.d(v,"AssetsProgressEvent",function(){return df}),f.d(v,"ContainerAssetTask",function(){return ff}),f.d(v,"MeshAssetTask",function(){return pf}),f.d(v,"TextFileAssetTask",function(){return _f}),f.d(v,"BinaryFileAssetTask",function(){return mf}),f.d(v,"ImageAssetTask",function(){return gf}),f.d(v,"TextureAssetTask",function(){return vf}),f.d(v,"CubeTextureAssetTask",function(){return bf}),f.d(v,"HDRCubeTextureAssetTask",function(){return yf}),f.d(v,"EquiRectangularCubeTextureAssetTask",function(){return Tf}),f.d(v,"AssetsManager",function(){return Sv}),f.d(v,"BasisTranscodeConfiguration",function(){return ym}),f.d(v,"BasisTools",function(){return _o}),f.d(v,"DDSTools",function(){return Ui}),f.d(v,"expandToProperty",function(){return L.b}),f.d(v,"serialize",function(){return L.c}),f.d(v,"serializeAsTexture",function(){return L.m}),f.d(v,"serializeAsColor3",function(){return L.e}),f.d(v,"serializeAsFresnelParameters",function(){return L.h}),f.d(v,"serializeAsVector2",function(){return L.n}),f.d(v,"serializeAsVector3",function(){return L.o}),f.d(v,"serializeAsMeshReference",function(){return L.k}),f.d(v,"serializeAsColorCurves",function(){return L.g}),f.d(v,"serializeAsColor4",function(){return L.f}),f.d(v,"serializeAsImageProcessingConfiguration",function(){return L.i}),f.d(v,"serializeAsQuaternion",function(){return L.l}),f.d(v,"serializeAsMatrix",function(){return L.j}),f.d(v,"serializeAsCameraReference",function(){return L.d}),f.d(v,"SerializationHelper",function(){return L.a}),f.d(v,"Deferred",function(){return Av}),f.d(v,"EnvironmentTextureTools",function(){return Si}),f.d(v,"MeshExploder",function(){return Pv}),f.d(v,"FilesInput",function(){return Cv}),f.d(v,"CubeMapToSphericalPolynomialTools",function(){return Xo}),f.d(v,"HDRTools",function(){return Ju}),f.d(v,"PanoramaToCubeMapTools",function(){return Zs}),f.d(v,"KhronosTextureContainer",function(){return aa}),f.d(v,"EventState",function(){return x.a}),f.d(v,"Observer",function(){return x.d}),f.d(v,"MultiObserver",function(){return x.b}),f.d(v,"Observable",function(){return x.c}),f.d(v,"PerformanceMonitor",function(){return Ef.a}),f.d(v,"RollingAverage",function(){return Ef.b}),f.d(v,"PromisePolyfill",function(){return xv.a}),f.d(v,"SceneOptimization",function(){return pi}),f.d(v,"TextureOptimization",function(){return Ra}),f.d(v,"HardwareScalingOptimization",function(){return Jc}),f.d(v,"ShadowsOptimization",function(){return Oa}),f.d(v,"PostProcessesOptimization",function(){return Ma}),f.d(v,"LensFlaresOptimization",function(){return Ia}),f.d(v,"CustomOptimization",function(){return Sf}),f.d(v,"ParticlesOptimization",function(){return Da}),f.d(v,"RenderTargetsOptimization",function(){return $c}),f.d(v,"MergeMeshesOptimization",function(){return La}),f.d(v,"SceneOptimizerOptions",function(){return el}),f.d(v,"SceneOptimizer",function(){return Rv}),f.d(v,"SceneSerializer",function(){return nl}),f.d(v,"SmartArray",function(){return li.a}),f.d(v,"SmartArrayNoDuplicate",function(){return li.b}),f.d(v,"StringDictionary",function(){return Il.a}),f.d(v,"Tags",function(){return Ov.a}),f.d(v,"TextureTools",function(){return Mv}),f.d(v,"TGATools",function(){return pa}),f.d(v,"Tools",function(){return Ye.b}),f.d(v,"className",function(){return Ye.c}),f.d(v,"AsyncLoop",function(){return Ye.a}),f.d(v,"VideoRecorder",function(){return Iv}),f.d(v,"JoystickAxis",function(){return an}),f.d(v,"VirtualJoystick",function(){return us}),f.d(v,"WorkerPool",function(){return zs}),f.d(v,"Logger",function(){return l.a}),f.d(v,"_TypeStore",function(){return R.a}),f.d(v,"FilesInputStore",function(){return Os.a}),f.d(v,"DeepCopier",function(){return de.a}),f.d(v,"PivotTools",function(){return kn.a}),f.d(v,"PrecisionDate",function(){return be.a}),f.d(v,"ScreenshotTools",function(){return Oo}),f.d(v,"WebRequest",function(){return re.a}),f.d(v,"InspectableType",function(){return Zc}),f.d(v,"BRDFTextureTools",function(){return ia}),f.d(v,"RGBDTextureTools",function(){return Su}),f.d(v,"ColorGradient",function(){return Lc}),f.d(v,"Color3Gradient",function(){return Ld}),f.d(v,"FactorGradient",function(){return Nc}),f.d(v,"GradientHelper",function(){return On}),f.d(v,"PerfCounter",function(){return jn.a}),f.d(v,"RetryStrategy",function(){return Dv.a}),f.d(v,"CanvasGenerator",function(){return vs.a}),f.d(v,"LoadFileError",function(){return no.b}),f.d(v,"RequestFileError",function(){return no.d}),f.d(v,"ReadFileError",function(){return no.c}),f.d(v,"FileTools",function(){return no.a}),f.d(v,"StringTools",function(){return Xn.a}),f.d(v,"DataReader",function(){return Lv}),f.d(v,"MinMaxReducer",function(){return Xu}),f.d(v,"DepthReducer",function(){return Yu}),f.d(v,"DataStorage",function(){return Nv}),f.d(v,"SceneRecorder",function(){return wv}),f.d(v,"KhronosTextureContainer2",function(){return js}),f.d(v,"Trajectory",function(){return Fv}),f.d(v,"TrajectoryClassifier",function(){return Bv}),f.d(v,"TimerState",function(){return Vi}),f.d(v,"setAndStartTimer",function(){return Ws}),f.d(v,"AdvancedTimer",function(){return U_}),f.d(v,"CopyTools",function(){return Uv.a}),f.d(v,"WebXRCamera",function(){return Mu}),f.d(v,"WebXREnterExitUIButton",function(){return wu}),f.d(v,"WebXREnterExitUIOptions",function(){return B_}),f.d(v,"WebXREnterExitUI",function(){return Fu}),f.d(v,"WebXRExperienceHelper",function(){return Iu}),f.d(v,"WebXRInput",function(){return Nu}),f.d(v,"WebXRInputSource",function(){return Lu}),f.d(v,"WebXRManagedOutputCanvasOptions",function(){return bs}),f.d(v,"WebXRManagedOutputCanvas",function(){return tu}),f.d(v,"WebXRState",function(){return fn}),f.d(v,"WebXRTrackingState",function(){return er}),f.d(v,"WebXRSessionManager",function(){return ys}),f.d(v,"WebXRDefaultExperienceOptions",function(){return V_}),f.d(v,"WebXRDefaultExperience",function(){return Bu}),f.d(v,"WebXRFeatureName",function(){return ii}),f.d(v,"WebXRFeaturesManager",function(){return Yn}),f.d(v,"WebXRAbstractFeature",function(){return ri}),f.d(v,"WebXRHitTestLegacy",function(){return wa}),f.d(v,"WebXRAnchorSystem",function(){return Fa}),f.d(v,"WebXRPlaneDetector",function(){return Ba}),f.d(v,"WebXRBackgroundRemover",function(){return Ua}),f.d(v,"WebXRMotionControllerTeleportation",function(){return ho}),f.d(v,"WebXRControllerPointerSelection",function(){return uo}),f.d(v,"IWebXRControllerPhysicsOptions",function(){return Gv}),f.d(v,"WebXRControllerPhysics",function(){return Va}),f.d(v,"WebXRHitTest",function(){return ka}),f.d(v,"WebXRFeaturePointSystem",function(){return Ga}),f.d(v,"WebXRHand",function(){return xf}),f.d(v,"WebXRHandTracking",function(){return za}),f.d(v,"WebXRAbstractMotionController",function(){return xr}),f.d(v,"WebXRControllerComponent",function(){return Cr}),f.d(v,"WebXRGenericTriggerMotionController",function(){return Hs}),f.d(v,"WebXRMicrosoftMixedRealityController",function(){return Rf}),f.d(v,"WebXRMotionControllerManager",function(){return wn}),f.d(v,"WebXROculusTouchMotionController",function(){return rl}),f.d(v,"WebXRHTCViveMotionController",function(){return Of}),f.d(v,"WebXRProfiledMotionController",function(){return Du});var B=f(35),_=f(91),x=f(6),u=f(0),M=f(9),R=f(11),C=function(){function r(t,e){this.triggerOptions=t,this.onBeforeExecuteObservable=new x.c,t.parameter?(this.trigger=t.trigger,this._triggerParameter=t.parameter):t.trigger?this.trigger=t.trigger:this.trigger=t,this._nextActiveAction=this,this._condition=e}return r.prototype._prepare=function(){},r.prototype.getTriggerParameter=function(){return this._triggerParameter},r.prototype._executeCurrent=function(t){if(this._nextActiveAction._condition){var e=this._nextActiveAction._condition,n=this._actionManager.getScene().getRenderId();if(e._evaluationId===n){if(!e._currentResult)return}else{if(e._evaluationId=n,!e.isValid())return void(e._currentResult=!1);e._currentResult=!0}}this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(t),this.skipToNextActiveAction()},r.prototype.execute=function(t){},r.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},r.prototype.then=function(t){return this._child=t,t._actionManager=this._actionManager,t._prepare(),t},r.prototype._getProperty=function(t){return this._actionManager._getProperty(t)},r.prototype._getEffectiveTarget=function(t,e){return this._actionManager._getEffectiveTarget(t,e)},r.prototype.serialize=function(t){},r.prototype._serialize=function(t,e){var n={type:1,children:[],name:t.name,properties:t.properties||[]};if(this._child&&this._child.serialize(n),this._condition){var i=this._condition.serialize();return i.children.push(n),e&&e.children.push(i),i}return e&&e.children.push(n),n},r._SerializeValueAsString=function(t){return typeof t=="number"?t.toString():typeof t=="boolean"?t?"true":"false":t instanceof u.d?t.x+", "+t.y:t instanceof u.e?t.x+", "+t.y+", "+t.z:t instanceof M.a?t.r+", "+t.g+", "+t.b:t instanceof M.b?t.r+", "+t.g+", "+t.b+", "+t.a:t},r._GetTargetProperty=function(t){return{name:"target",targetType:t._isMesh?"MeshProperties":t._isLight?"LightProperties":t._isCamera?"CameraProperties":"SceneProperties",value:t._isScene?"Scene":t.name}},r}();R.a.RegisteredTypes["BABYLON.Action"]=C;var m=f(47),c=f(1),E=function(){function r(t){this._actionManager=t}return r.prototype.isValid=function(){return!0},r.prototype._getProperty=function(t){return this._actionManager._getProperty(t)},r.prototype._getEffectiveTarget=function(t,e){return this._actionManager._getEffectiveTarget(t,e)},r.prototype.serialize=function(){},r.prototype._serialize=function(t){return{type:2,children:[],name:t.name,properties:t.properties}},r}(),A=function(r){function t(e,n,i,o,a){a===void 0&&(a=t.IsEqual);var s=r.call(this,e)||this;return s.propertyPath=i,s.value=o,s.operator=a,s._target=n,s._effectiveTarget=s._getEffectiveTarget(n,s.propertyPath),s._property=s._getProperty(s.propertyPath),s}return Object(c.d)(t,r),Object.defineProperty(t,"IsEqual",{get:function(){return t._IsEqual},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsDifferent",{get:function(){return t._IsDifferent},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsGreater",{get:function(){return t._IsGreater},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsLesser",{get:function(){return t._IsLesser},enumerable:!1,configurable:!0}),t.prototype.isValid=function(){switch(this.operator){case t.IsGreater:return this._effectiveTarget[this._property]>this.value;case t.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var n=0;n-1)return!0}return!1},t.prototype.hasSpecificTriggers2=function(e,n){for(var i=0;i=t.OnPickTrigger&&n.trigger<=t.OnPointerOutTrigger)return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e=t.OnPickTrigger&&n.trigger<=t.OnPickUpTrigger)return!0}return!1},enumerable:!1,configurable:!0}),t.prototype.registerAction=function(e){return e.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(l.a.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),t.Triggers[e.trigger]?t.Triggers[e.trigger]++:t.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)},t.prototype.unregisterAction=function(e){var n=this.actions.indexOf(e);return n!==-1&&(this.actions.splice(n,1),t.Triggers[e.trigger]-=1,t.Triggers[e.trigger]===0&&delete t.Triggers[e.trigger],e._actionManager=null,!0)},t.prototype.processTrigger=function(e,n){for(var i=0;i0;if(F.type===2?ce.push(o):ce.push(z),ve){for(var Te=new Array,Oe=0;Oe0){var P=y.properties[0].value,O=y.properties[0].targetType===null?P:i.getMeshByName(P);O._meshId&&(O.mesh=i.getMeshByID(O._meshId)),p={trigger:t[y.name],parameter:O}}else p=t[y.name];for(var U=0;U=0?e:0;var s=0,d=a._keys[0],p=a._keys.length-1,y=a._keys[p],P={referenceValue:d.value,referencePosition:u.c.Vector3[0],referenceQuaternion:u.c.Quaternion[0],referenceScaling:u.c.Vector3[1],keyPosition:u.c.Vector3[2],keyQuaternion:u.c.Quaternion[1],keyScaling:u.c.Vector3[3]},O=!1,U=d.frame,F=y.frame;if(n){var z=a.getRange(n);z&&(U=z.from,F=z.to)}var J=d.frame===U,ie=y.frame===F;if(a._keys.length===1){var se=a._getKeyValue(a._keys[0]);P.referenceValue=se.clone?se.clone():se,O=!0}else e<=d.frame?(se=a._getKeyValue(d.value),P.referenceValue=se.clone?se.clone():se,O=!0):e>=y.frame&&(se=a._getKeyValue(y.value),P.referenceValue=se.clone?se.clone():se,O=!0);for(var ce=0;!O||!J||!ie&&ce=ue.frame&&e<=fe.frame){if(se=void 0,e===ue.frame)se=a._getKeyValue(ue.value);else if(e===fe.frame)se=a._getKeyValue(fe.value);else{var ve={key:ce,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};se=a._interpolate(e,ve)}P.referenceValue=se.clone?se.clone():se,O=!0}if(!J&&U>=ue.frame&&U<=fe.frame){if(U===ue.frame)s=ce;else if(U===fe.frame)s=ce+1;else{ve={key:ce,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};var Te={frame:U,value:(se=a._interpolate(U,ve)).clone?se.clone():se};a._keys.splice(ce+1,0,Te),s=ce+1}J=!0}!ie&&F>=ue.frame&&F<=fe.frame&&(F===ue.frame?p=ce:F===fe.frame?p=ce+1:(ve={key:ce,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},Te={frame:F,value:(se=a._interpolate(F,ve)).clone?se.clone():se},a._keys.splice(ce+1,0,Te),p=ce+1),ie=!0),ce++}for(a.dataType===r.ANIMATIONTYPE_QUATERNION?P.referenceValue.normalize().conjugateInPlace():a.dataType===r.ANIMATIONTYPE_MATRIX&&(P.referenceValue.decompose(P.referenceScaling,P.referenceQuaternion,P.referencePosition),P.referenceQuaternion.normalize().conjugateInPlace()),ce=s;ce<=p;ce++)if(Te=a._keys[ce],!ce||a.dataType===r.ANIMATIONTYPE_FLOAT||Te.value!==d.value)switch(a.dataType){case r.ANIMATIONTYPE_MATRIX:Te.value.decompose(P.keyScaling,P.keyQuaternion,P.keyPosition),P.keyPosition.subtractInPlace(P.referencePosition),P.keyScaling.divideInPlace(P.referenceScaling),P.referenceQuaternion.multiplyToRef(P.keyQuaternion,P.keyQuaternion),u.a.ComposeToRef(P.keyScaling,P.keyQuaternion,P.keyPosition,Te.value);break;case r.ANIMATIONTYPE_QUATERNION:P.referenceValue.multiplyToRef(Te.value,Te.value);break;case r.ANIMATIONTYPE_VECTOR2:case r.ANIMATIONTYPE_VECTOR3:case r.ANIMATIONTYPE_COLOR3:case r.ANIMATIONTYPE_COLOR4:Te.value.subtractToRef(P.referenceValue,Te.value);break;case r.ANIMATIONTYPE_SIZE:Te.value.width-=P.referenceValue.width,Te.value.height-=P.referenceValue.height;break;default:Te.value-=P.referenceValue}return a},r.TransitionTo=function(t,e,n,i,o,a,s,d){if(d===void 0&&(d=null),s<=0)return n[t]=e,d&&d(),null;var p=o*(s/1e3);a.setKeys([{frame:0,value:n[t].clone?n[t].clone():n[t]},{frame:p,value:e}]),n.animations||(n.animations=[]),n.animations.push(a);var y=i.beginAnimation(n,0,p,!1);return y.onAnimationEnd=d,y},Object.defineProperty(r.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var t=0,e=this._runtimeAnimations;t=0;a--)this._keys[a].frame>=i&&this._keys[a].frame<=o&&this._keys.splice(a,1);this._ranges[t]=null}},r.prototype.getRange=function(t){return this._ranges[t]},r.prototype.getKeys=function(){return this._keys},r.prototype.getHighestFrame=function(){for(var t=0,e=0,n=this._keys.length;e0)return e.highLimitValue.clone?e.highLimitValue.clone():e.highLimitValue;var n=this._keys;if(n.length===1)return this._getKeyValue(n[0].value);var i=e.key;if(n[i].frame>=t)for(;i-1>=0&&n[i].frame>=t;)i--;for(var o=i;o=t){e.key=o;var s=n[o],d=this._getKeyValue(s.value);if(s.interpolation===K.STEP)return d;var p=this._getKeyValue(a.value),y=s.outTangent!==void 0&&a.inTangent!==void 0,P=a.frame-s.frame,O=(t-s.frame)/P,U=this.getEasingFunction();switch(U!=null&&(O=U.ease(O)),this.dataType){case r.ANIMATIONTYPE_FLOAT:var F=y?this.floatInterpolateFunctionWithTangents(d,s.outTangent*P,p,a.inTangent*P,O):this.floatInterpolateFunction(d,p,O);switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return F;case r.ANIMATIONLOOPMODE_RELATIVE:return e.offsetValue*e.repeatCount+F}break;case r.ANIMATIONTYPE_QUATERNION:var z=y?this.quaternionInterpolateFunctionWithTangents(d,s.outTangent.scale(P),p,a.inTangent.scale(P),O):this.quaternionInterpolateFunction(d,p,O);switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return z;case r.ANIMATIONLOOPMODE_RELATIVE:return z.addInPlace(e.offsetValue.scale(e.repeatCount))}return z;case r.ANIMATIONTYPE_VECTOR3:var J=y?this.vector3InterpolateFunctionWithTangents(d,s.outTangent.scale(P),p,a.inTangent.scale(P),O):this.vector3InterpolateFunction(d,p,O);switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return J;case r.ANIMATIONLOOPMODE_RELATIVE:return J.add(e.offsetValue.scale(e.repeatCount))}case r.ANIMATIONTYPE_VECTOR2:var ie=y?this.vector2InterpolateFunctionWithTangents(d,s.outTangent.scale(P),p,a.inTangent.scale(P),O):this.vector2InterpolateFunction(d,p,O);switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return ie;case r.ANIMATIONLOOPMODE_RELATIVE:return ie.add(e.offsetValue.scale(e.repeatCount))}case r.ANIMATIONTYPE_SIZE:switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(d,p,O);case r.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(d,p,O).add(e.offsetValue.scale(e.repeatCount))}case r.ANIMATIONTYPE_COLOR3:switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(d,p,O);case r.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(d,p,O).add(e.offsetValue.scale(e.repeatCount))}case r.ANIMATIONTYPE_COLOR4:switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:return this.color4InterpolateFunction(d,p,O);case r.ANIMATIONLOOPMODE_RELATIVE:return this.color4InterpolateFunction(d,p,O).add(e.offsetValue.scale(e.repeatCount))}case r.ANIMATIONTYPE_MATRIX:switch(e.loopMode){case r.ANIMATIONLOOPMODE_CYCLE:case r.ANIMATIONLOOPMODE_CONSTANT:if(r.AllowMatricesInterpolation)return this.matrixInterpolateFunction(d,p,O,e.workValue);case r.ANIMATIONLOOPMODE_RELATIVE:return d}}break}}return this._getKeyValue(n[n.length-1].value)},r.prototype.matrixInterpolateFunction=function(t,e,n,i){return r.AllowMatrixDecomposeForInterpolation?i?(u.a.DecomposeLerpToRef(t,e,n,i),i):u.a.DecomposeLerp(t,e,n):i?(u.a.LerpToRef(t,e,n,i),i):u.a.Lerp(t,e,n)},r.prototype.clone=function(){var t=new r(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys),this._ranges)for(var e in t._ranges={},this._ranges){var n=this._ranges[e];n&&(t._ranges[e]=n.clone())}return t},r.prototype.setKeys=function(t){this._keys=t.slice(0)},r.prototype.serialize=function(){var t={};t.name=this.name,t.property=this.targetProperty,t.framePerSecond=this.framePerSecond,t.dataType=this.dataType,t.loopBehavior=this.loopMode,t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed;var e=this.dataType;t.keys=[];for(var n=this.getKeys(),i=0;i=1&&(s=p.values[1]),p.values.length>=2&&(d=p.values[2]);break;case r.ANIMATIONTYPE_QUATERNION:if(e=u.b.FromArray(p.values),p.values.length>=8){var y=u.b.FromArray(p.values.slice(4,8));y.equals(u.b.Zero())||(s=y)}if(p.values.length>=12){var P=u.b.FromArray(p.values.slice(8,12));P.equals(u.b.Zero())||(d=P)}break;case r.ANIMATIONTYPE_MATRIX:e=u.a.FromArray(p.values);break;case r.ANIMATIONTYPE_COLOR3:e=M.a.FromArray(p.values);break;case r.ANIMATIONTYPE_COLOR4:e=M.b.FromArray(p.values);break;case r.ANIMATIONTYPE_VECTOR3:default:e=u.e.FromArray(p.values)}var O={};O.frame=p.frame,O.value=e,s!=null&&(O.inTangent=s),d!=null&&(O.outTangent=d),a.push(O)}if(i.setKeys(a),t.ranges)for(n=0;n0&&P.forEach(function(O){o._events.push(O._clone())}),this._enableBlending=t&&t.animationPropertiesOverride?t.animationPropertiesOverride.enableBlending:this._animation.enableBlending}return Object.defineProperty(r.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"weight",{get:function(){return this._weight},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"target",{get:function(){return this._currentActiveTarget},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isAdditive",{get:function(){return this._host&&this._host.isAdditive},enumerable:!1,configurable:!0}),r.prototype._preparePath=function(t,e){e===void 0&&(e=0);var n=this._animation.targetPropertyPath;if(n.length>1){for(var i=t[n[0]],o=1;o-1&&this._animation.runtimeAnimations.splice(t,1)},r.prototype.setValue=function(t,e){if(this._targetIsArray)for(var n=0;ne[e.length-1].frame&&(t=e[e.length-1].frame);var n=this._events;if(n.length)for(var i=0;ithis._maxFrame)&&(e=this._minFrame),(nthis._maxFrame)&&(n=this._maxFrame);var y,P,O=n-e,U=t*(s.framePerSecond*o)/1e3+this._ratioOffset,F=0;if(this._previousDelay=t,this._previousRatio=U,!i&&n>=e&&U>=O)p=!1,F=s._getKeyValue(this._maxValue);else if(!i&&e>=n&&U<=O)p=!1,F=s._getKeyValue(this._minValue);else if(this._animationState.loopMode!==k.ANIMATIONLOOPMODE_CYCLE){var z=n.toString()+e.toString();if(!this._offsetsCache[z]){this._animationState.repeatCount=0,this._animationState.loopMode=k.ANIMATIONLOOPMODE_CYCLE;var J=s._interpolate(e,this._animationState),ie=s._interpolate(n,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),s.dataType){case k.ANIMATIONTYPE_FLOAT:this._offsetsCache[z]=ie-J;break;case k.ANIMATIONTYPE_QUATERNION:this._offsetsCache[z]=ie.subtract(J);break;case k.ANIMATIONTYPE_VECTOR3:this._offsetsCache[z]=ie.subtract(J);case k.ANIMATIONTYPE_VECTOR2:this._offsetsCache[z]=ie.subtract(J);case k.ANIMATIONTYPE_SIZE:this._offsetsCache[z]=ie.subtract(J);case k.ANIMATIONTYPE_COLOR3:this._offsetsCache[z]=ie.subtract(J)}this._highLimitsCache[z]=ie}F=this._highLimitsCache[z],y=this._offsetsCache[z]}if(y===void 0)switch(s.dataType){case k.ANIMATIONTYPE_FLOAT:y=0;break;case k.ANIMATIONTYPE_QUATERNION:y=Z;break;case k.ANIMATIONTYPE_VECTOR3:y=X;break;case k.ANIMATIONTYPE_VECTOR2:y=q;break;case k.ANIMATIONTYPE_SIZE:y=he;break;case k.ANIMATIONTYPE_COLOR3:y=ge}if(this._host&&this._host.syncRoot){var se=this._host.syncRoot;P=e+(n-e)*((se.masterFrame-se.fromFrame)/(se.toFrame-se.fromFrame))}else P=p&&O!==0?e+U%O:n;var ce=this._events;if((O>0&&this.currentFrame>P||O<0&&this.currentFrame>0,this._animationState.highLimitValue=F,this._animationState.offsetValue=y;var fe=s._interpolate(P,this._animationState);if(this.setValue(fe,a),ce.length){for(ue=0;ue0&&P>=ce[ue].frame&&ce[ue].frame>=e||O<0&&P<=ce[ue].frame&&ce[ue].frame<=e){var ve=ce[ue];ve.isDone||(ve.onlyOnce&&(ce.splice(ue,1),ue--),ve.isDone=!0,ve.action(P))}}return p||(this._stopped=!0),p},r}(),_e=f(20),be=f(57),Ce=f(44),ye=f(23),Be=function(r){function t(e,n,i,o,a,s,d){i===void 0&&(i=null),o===void 0&&(o=null),a===void 0&&(a=null),s===void 0&&(s=null),d===void 0&&(d=null);var p=r.call(this,e,n.getScene())||this;return p.name=e,p.children=new Array,p.animations=new Array,p._index=null,p._absoluteTransform=new u.a,p._invertedAbsoluteTransform=new u.a,p._scalingDeterminant=1,p._worldTransform=new u.a,p._needToDecompose=!0,p._needToCompose=!1,p._linkedTransformNode=null,p._waitingTransformNodeId=null,p._skeleton=n,p._localMatrix=o?o.clone():u.a.Identity(),p._restPose=a||p._localMatrix.clone(),p._bindPose=p._localMatrix.clone(),p._baseMatrix=s||p._localMatrix.clone(),p._index=d,n.bones.push(p),p.setParent(i,!1),(s||o)&&p._updateDifferenceMatrix(),p}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"_matrix",{get:function(){return this._compose(),this._localMatrix},set:function(e){this._localMatrix.copyFrom(e),this._needToDecompose=!0},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"Bone"},t.prototype.getSkeleton=function(){return this._skeleton},t.prototype.getParent=function(){return this._parent},t.prototype.getChildren=function(){return this.children},t.prototype.getIndex=function(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index},t.prototype.setParent=function(e,n){if(n===void 0&&(n=!0),this._parent!==e){if(this._parent){var i=this._parent.children.indexOf(this);i!==-1&&this._parent.children.splice(i,1)}this._parent=e,this._parent&&this._parent.children.push(this),n&&this._updateDifferenceMatrix(),this.markAsDirty()}},t.prototype.getLocalMatrix=function(){return this._compose(),this._localMatrix},t.prototype.getBaseMatrix=function(){return this._baseMatrix},t.prototype.getRestPose=function(){return this._restPose},t.prototype.setRestPose=function(e){this._restPose.copyFrom(e)},t.prototype.getBindPose=function(){return this._bindPose},t.prototype.setBindPose=function(e){this._bindPose.copyFrom(e)},t.prototype.getWorldMatrix=function(){return this._worldTransform},t.prototype.returnToRest=function(){this._skeleton._numBonesWithLinkedTransformNode>0?this.updateMatrix(this._restPose,!1,!1):this.updateMatrix(this._restPose,!1,!0)},t.prototype.getInvertedAbsoluteTransform=function(){return this._invertedAbsoluteTransform},t.prototype.getAbsoluteTransform=function(){return this._absoluteTransform},t.prototype.linkTransformNode=function(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++},t.prototype.getTransformNode=function(){return this._linkedTransformNode},Object.defineProperty(t.prototype,"position",{get:function(){return this._decompose(),this._localPosition},set:function(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this.getRotation()},set:function(e){this.setRotation(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._decompose(),this._localRotation},set:function(e){this.setRotationQuaternion(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this.getScale()},set:function(e){this.setScale(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._skeleton.animationPropertiesOverride},enumerable:!1,configurable:!0}),t.prototype._decompose=function(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=u.e.Zero(),this._localRotation=u.b.Zero(),this._localPosition=u.e.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))},t.prototype._compose=function(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,u.a.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)},t.prototype.updateMatrix=function(e,n,i){n===void 0&&(n=!0),i===void 0&&(i=!0),this._baseMatrix.copyFrom(e),n&&this._updateDifferenceMatrix(),i?(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose()):this.markAsDirty()},t.prototype._updateDifferenceMatrix=function(e,n){if(n===void 0&&(n=!0),e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),n)for(var i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this},r.prototype.getAnimations=function(){return this._runtimeAnimations},r.prototype.appendAnimations=function(t,e){for(var n=this,i=0;i-1){for(var i=(a=this._runtimeAnimations).length-1;i>=0;i--){var o=a[i];t&&o.animation.name!=t||e&&!e(o.target)||(o.dispose(),a.splice(i,1))}a.length==0&&(this._scene._activeAnimatables.splice(n,1),this._raiseOnAnimationEnd())}}else if((i=this._scene._activeAnimatables.indexOf(this))>-1){this._scene._activeAnimatables.splice(i,1);var a=this._runtimeAnimations;for(i=0;i0)return;this._animationTimeLast=r}this.deltaTime=this.useConstantAnimationDeltaTime?16:(r-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=r;var t=this._activeAnimatables;if(t.length!==0){this._animationTime+=this.deltaTime;for(var e=this._animationTime,n=0;ne&&i>0&&(i*=-1),s&&this.stopAnimation(r,void 0,d),a||(a=new Ge(this,r,t,e,n,i,o,void 0,p,y));var P=!d||d(r);if(r.animations&&P&&a.appendAnimations(r,r.animations),r.getAnimatables)for(var O=r.getAnimatables(),U=0;Un&&o>0&&(o*=-1),new Ge(this,r,e,n,i,o,a,t,s,d)},_e.a.prototype.beginDirectHierarchyAnimation=function(r,t,e,n,i,o,a,s,d,p){p===void 0&&(p=!1);var y=r.getDescendants(t),P=[];P.push(this.beginDirectAnimation(r,e,n,i,o,a,s,d,p));for(var O=0,U=y;O0)i.copyFrom(n);else if(r.animations.length===1){if(u.b.SlerpToRef(n,e.currentValue,Math.min(1,r.totalWeight),i),r.totalAdditiveWeight===0)return i}else if(r.animations.length>1){var o=1,a=void 0,s=void 0;if(r.totalWeight<1){var d=1-r.totalWeight;s=[],(a=[]).push(n),s.push(d)}else{if(r.animations.length===2&&(u.b.SlerpToRef(r.animations[0].currentValue,r.animations[1].currentValue,r.animations[1].weight/r.totalWeight,t),r.totalAdditiveWeight===0))return t;a=[],s=[],o=r.totalWeight}for(var p=0;p=p&&a.frame<=y&&(n?(d=a.value.clone(),z?(s=d.getTranslation(),d.setTranslation(s.scaleInPlace(J))):ie&&i?(s=d.getTranslation(),d.setTranslation(s.multiplyInPlace(i))):d=a.value):d=a.value,se.push({frame:a.frame+e,value:d}));return this.animations[0].createRange(t,p+e,y+e),!0};var Xe=function(){function r(){}return r.prototype.getClassName=function(){return"TargetedAnimation"},r.prototype.serialize=function(){var t={};return t.animation=this.animation.serialize(),t.targetId=this.target.id,t},r}(),He=function(){function r(t,e){e===void 0&&(e=null),this.name=t,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this.onAnimationEndObservable=new x.c,this.onAnimationLoopObservable=new x.c,this.onAnimationGroupLoopObservable=new x.c,this.onAnimationGroupEndObservable=new x.c,this.onAnimationGroupPauseObservable=new x.c,this.onAnimationGroupPlayObservable=new x.c,this._scene=e||te.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}return Object.defineProperty(r.prototype,"from",{get:function(){return this._from},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"to",{get:function(){return this._to},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isStarted",{get:function(){return this._isStarted},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isPlaying",{get:function(){return this._isStarted&&!this._isPaused},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(t){if(this._speedRatio!==t){this._speedRatio=t;for(var e=0;ei[0].frame&&(this._from=i[0].frame),this._tot){var s={frame:t,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};i.splice(0,0,s)}a.framei&&this._speedRatio>0&&(this._speedRatio=-e);return this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this},r.prototype.pause=function(){if(!this._isStarted)return this;this._isPaused=!0;for(var t=0;t-1&&this._scene.animationGroups.splice(t,1),this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()},r.prototype._checkAnimationGroupEnded=function(t){var e=this._animatables.indexOf(t);e>-1&&this._animatables.splice(e,1),this._animatables.length===0&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},r.prototype.clone=function(t,e){for(var n=new r(t||this.name,this._scene),i=0,o=this._targetedAnimations;i=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},r.EASINGMODE_EASEIN=0,r.EASINGMODE_EASEOUT=1,r.EASINGMODE_EASEINOUT=2,r}(),it=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t}(ze),et=function(r){function t(e){e===void 0&&(e=1);var n=r.call(this)||this;return n.amplitude=e,n}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){var n=Math.max(0,this.amplitude);return Math.pow(e,3)-e*n*Math.sin(3.141592653589793*e)},t}(ze),lt=function(r){function t(e,n){e===void 0&&(e=3),n===void 0&&(n=2);var i=r.call(this)||this;return i.bounces=e,i.bounciness=n,i}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){var n=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var o=Math.pow(i,n),a=1-i,s=(1-o)/a+.5*o,d=e*s,p=Math.log(-d*(1-i)+1)/Math.log(i),y=Math.floor(p),P=y+1,O=(1-Math.pow(i,y))/(a*s),U=.5*(O+(1-Math.pow(i,P))/(a*s)),F=e-U,z=U-O;return-Math.pow(1/i,n-y)/(z*z)*(F-z)*(F+z)},t}(ze),ct=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return e*e*e},t}(ze),mt=function(r){function t(e,n){e===void 0&&(e=3),n===void 0&&(n=3);var i=r.call(this)||this;return i.oscillations=e,i.springiness=n,i}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){var n=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(i==0?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*n+1.5707963267948966)*e)},t}(ze),St=function(r){function t(e){e===void 0&&(e=2);var n=r.call(this)||this;return n.exponent=e,n}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t}(ze),wt=function(r){function t(e){e===void 0&&(e=2);var n=r.call(this)||this;return n.power=e,n}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){var n=Math.max(0,this.power);return Math.pow(e,n)},t}(ze),It=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return e*e},t}(ze),Pt=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return e*e*e*e},t}(ze),Ot=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return e*e*e*e*e},t}(ze),on=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t}(ze),Zt=function(r){function t(e,n,i,o){e===void 0&&(e=0),n===void 0&&(n=0),i===void 0&&(i=1),o===void 0&&(o=1);var a=r.call(this)||this;return a.x1=e,a.y1=n,a.x2=i,a.y2=o,a}return Object(c.d)(t,r),t.prototype.easeInCore=function(e){return Ze.c.Interpolate(e,this.x1,this.y1,this.x2,this.y2)},t}(ze),tn=function(){function r(t,e,n){this.frame=t,this.action=e,this.onlyOnce=n,this.isDone=!1}return r.prototype._clone=function(){return new r(this.frame,this.action,this.onlyOnce)},r}(),De=f(7),Sn=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t}(B.a),nn=function(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]},An=function(r){function t(e){var n=r.call(this)||this;return n._wasAddedToScene=!1,n.scene=e,n.sounds=[],n.effectLayers=[],n.layers=[],n.lensFlareSystems=[],n.proceduralTextures=[],n.reflectionProbes=[],e.onDisposeObservable.add(function(){n._wasAddedToScene||n.dispose()}),n}return Object(c.d)(t,r),t.prototype.instantiateModelsToScene=function(e,n){var i=this;n===void 0&&(n=!1);var o={},a={},s=new nn,d=[],p=[],y={doNotInstantiate:!0},P=function(O,U){if(o[O.uniqueId]=U.uniqueId,a[U.uniqueId]=U,e&&(U.name=e(O.name)),U instanceof De.a){var F=U;if(F.morphTargetManager){var z=O.morphTargetManager;F.morphTargetManager=z.clone();for(var J=0;J-1&&d.animations.splice(J,1)}},y=0,P=s.animations;y0&&(U=!0,this._soundLoaded(e));break;case"String":O.push(e);case"Array":O.length===0&&(O=e);for(var F=0;F0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(Ue.a.audioEngine.audioContext&&this._soundSource){var n=t?Ue.a.audioEngine.audioContext.currentTime+t:Ue.a.audioEngine.audioContext.currentTime;this._soundSource.stop(n),this._soundSource.onended=function(){e.isPlaying=!1},this.isPaused||(this._startOffset=0)}}},r.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():Ue.a.audioEngine.audioContext&&(this.stop(0),this._startOffset+=Ue.a.audioEngine.audioContext.currentTime-this._startTime))},r.prototype.setVolume=function(t,e){Ue.a.audioEngine.canUseWebAudio&&this._soundGain&&(e&&Ue.a.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Ue.a.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Ue.a.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,Ue.a.audioEngine.audioContext.currentTime+e)):this._soundGain.gain.value=t),this._volume=t},r.prototype.setPlaybackRate=function(t){this._playbackRate=t,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},r.prototype.getVolume=function(){return this._volume},r.prototype.attachToMesh=function(t){var e=this;this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=t,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=function(n){return e._onRegisterAfterWorldMatrixUpdate(n)},this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)},r.prototype.detachFromMesh=function(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)},r.prototype._onRegisterAfterWorldMatrixUpdate=function(t){if(this._positionInEmitterSpace)t.worldMatrixFromCache.invertToRef(u.c.Matrix[0]),this.setPosition(u.c.Matrix[0].getTranslation());else if(t.getBoundingInfo){var e=t.getBoundingInfo();this.setPosition(e.boundingSphere.centerWorld)}else this.setPosition(t.absolutePosition);Ue.a.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()},r.prototype.clone=function(){var t=this;if(this._streaming)return null;var e=function(){t._isReadyToPlay?(i._audioBuffer=t.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,t._offset,t._length)):window.setTimeout(e,300)},n={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 r(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,n);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i},r.prototype.getAudioBuffer=function(){return this._audioBuffer},r.prototype.getSoundSource=function(){return this._soundSource},r.prototype.getSoundGain=function(){return this._soundGain},r.prototype.serialize=function(){var t={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&&(t.connectedMeshId=this._connectedTransformNode.id),t.position=this._position.asArray(),t.refDistance=this.refDistance,t.distanceModel=this.distanceModel,t.isDirectional=this._isDirectional,t.localDirectionToMesh=this._localDirection.asArray(),t.coneInnerAngle=this._coneInnerAngle,t.coneOuterAngle=this._coneOuterAngle,t.coneOuterGain=this._coneOuterGain),t},r.Parse=function(t,e,n,i){var o,a=t.name;o=t.url?n+t.url:n+a;var s,d={autoplay:t.autoplay,loop:t.loop,volume:t.volume,spatialSound:t.spatialSound,maxDistance:t.maxDistance,rolloffFactor:t.rolloffFactor,refDistance:t.refDistance,distanceModel:t.distanceModel,playbackRate:t.playbackRate};if(i){var p=function(){i._isReadyToPlay?(s._audioBuffer=i.getAudioBuffer(),s._isReadyToPlay=!0,s.autoplay&&s.play(0,s._offset,s._length)):window.setTimeout(p,300)};s=new r(a,new ArrayBuffer(0),e,null,d),p()}else s=new r(a,o,e,function(){e._removePendingData(s)},d),e._addPendingData(s);if(t.position){var y=u.e.FromArray(t.position);s.setPosition(y)}if(t.isDirectional&&(s.setDirectionalCone(t.coneInnerAngle||360,t.coneOuterAngle||360,t.coneOuterGain||0),t.localDirectionToMesh)){var P=u.e.FromArray(t.localDirectionToMesh);s.setLocalDirectionToMesh(P)}if(t.connectedMeshId){var O=e.getMeshByID(t.connectedMeshId);O&&s.attachToMesh(O)}return t.metadata&&(s.metadata=t.metadata),s},r._SceneComponentInitialization=function(t){throw En.a.WarnImport("AudioSceneComponent")},r}(),Fo=function(){function r(t,e){e===void 0&&(e={}),this.id=-1,this._isInitialized=!1,this._scene=t,this.soundCollection=new Array,this._options=e,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return r.prototype._initializeSoundTrackAudioGraph=function(){Ue.a.audioEngine.canUseWebAudio&&Ue.a.audioEngine.audioContext&&(this._outputAudioNode=Ue.a.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Ue.a.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)},r.prototype.dispose=function(){if(Ue.a.audioEngine&&Ue.a.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},r.prototype.addSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),Ue.a.audioEngine.canUseWebAudio&&this._outputAudioNode&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(t.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(t):this._scene.soundTracks&&this._scene.soundTracks[t.soundTrackId].removeSound(t)),this.soundCollection.push(t),t.soundTrackId=this.id},r.prototype.removeSound=function(t){var e=this.soundCollection.indexOf(t);e!==-1&&this.soundCollection.splice(e,1)},r.prototype.setVolume=function(t){Ue.a.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=t)},r.prototype.switchPanningModelToHRTF=function(){if(Ue.a.audioEngine.canUseWebAudio)for(var t=0;t0?e.activeCameras[0]:e.activeCamera){this._cachedCameraPosition.equals(o.globalPosition)||(this._cachedCameraPosition.copyFrom(o.globalPosition),n.audioContext.listener.setPosition(o.globalPosition.x,o.globalPosition.y,o.globalPosition.z)),o.rigCameras&&o.rigCameras.length>0&&(o=o.rigCameras[0]);var a=u.a.Invert(o.getViewMatrix()),s=u.e.TransformNormal(e.useRightHandedSystem?r._CameraDirectionRH:r._CameraDirectionLH,a);s.normalize(),isNaN(s.x)||isNaN(s.y)||isNaN(s.z)||this._cachedCameraDirection.equals(s)||(this._cachedCameraDirection.copyFrom(s),n.audioContext.listener.setOrientation(s.x,s.y,s.z,0,1,0))}else n.audioContext.listener.setPosition(0,0,0)}var d;for(d=0;d0?1/o:0,p=0;p0},enumerable:!1,configurable:!0}),r.prototype.init=function(){},r.prototype.attach=function(t){var e=this;this._attachedCamera=t;var n=this._attachedCamera.getScene();this._onPrePointerObservableObserver=n.onPrePointerObservable.add(function(i){i.type!==Tt.a.POINTERDOWN?i.type===Tt.a.POINTERUP&&(e._isPointerDown=!1):e._isPointerDown=!0}),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add(function(){var i=be.a.Now,o=0;e._lastFrameTime!=null&&(o=i-e._lastFrameTime),e._lastFrameTime=i,e._applyUserInteraction();var a=i-e._lastInteractionTime-e._idleRotationWaitTime,s=Math.max(Math.min(a/e._idleRotationSpinupTime,1),0);e._cameraRotationSpeed=e._idleRotationSpeed*s,e._attachedCamera&&(e._attachedCamera.alpha-=e._cameraRotationSpeed*(o/1e3))})},r.prototype.detach=function(){if(this._attachedCamera){var t=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&t.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},r.prototype._userIsZooming=function(){return!!this._attachedCamera&&this._attachedCamera.inertialRadiusOffset!==0},r.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var t=!1;return this._lastFrameRadius===this._attachedCamera.radius&&this._attachedCamera.inertialRadiusOffset!==0&&(t=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?t:this._userIsZooming()},r.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=be.a.Now)},r.prototype._userIsMoving=function(){return!!this._attachedCamera&&(this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown)},r}(),Sl=function(){function r(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(r.prototype,"name",{get:function(){return"Bouncing"},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(t){var e=this;if(this._autoTransitionRange!==t){this._autoTransitionRange=t;var n=this._attachedCamera;n&&(t?this._onMeshTargetChangedObserver=n.onMeshTargetChangedObservable.add(function(i){if(i){i.computeWorldMatrix(!0);var o=i.getBoundingInfo().diagonalLength;e.lowerRadiusTransitionRange=.05*o,e.upperRadiusTransitionRange=.05*o}}):this._onMeshTargetChangedObserver&&n.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!1,configurable:!0}),r.prototype.init=function(){},r.prototype.attach=function(t){var e=this;this._attachedCamera=t,this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add(function(){e._attachedCamera&&(e._isRadiusAtLimit(e._attachedCamera.lowerRadiusLimit)&&e._applyBoundRadiusAnimation(e.lowerRadiusTransitionRange),e._isRadiusAtLimit(e._attachedCamera.upperRadiusLimit)&&e._applyBoundRadiusAnimation(e.upperRadiusTransitionRange))})},r.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},r.prototype._isRadiusAtLimit=function(t){return!!this._attachedCamera&&this._attachedCamera.radius===t&&!this._radiusIsAnimating},r.prototype._applyBoundRadiusAnimation=function(t){var e=this;if(this._attachedCamera){this._radiusBounceTransition||(r.EasingFunction.setEasingMode(r.EasingMode),this._radiusBounceTransition=k.CreateAnimation("radius",k.ANIMATIONTYPE_FLOAT,60,r.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=k.TransitionTo("radius",this._attachedCamera.radius+t,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,function(){return e._clearAnimationLocks()});n&&this._animatables.push(n)}},r.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},r.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},r.EasingFunction=new et(.3),r.EasingMode=ze.EASINGMODE_EASEOUT,r}(),Al=function(){function r(){this._mode=r.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}return Object.defineProperty(r.prototype,"name",{get:function(){return"Framing"},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"mode",{get:function(){return this._mode},set:function(t){this._mode=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(t){this._radiusScale=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positionScale",{get:function(){return this._positionScale},set:function(t){this._positionScale=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(t){this._defaultElevation=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(t){this._elevationReturnTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(t){this._elevationReturnWaitTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(t){this._zoomStopsAnimation=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"framingTime",{get:function(){return this._framingTime},set:function(t){this._framingTime=t},enumerable:!1,configurable:!0}),r.prototype.init=function(){},r.prototype.attach=function(t){var e=this;this._attachedCamera=t;var n=this._attachedCamera.getScene();r.EasingFunction.setEasingMode(r.EasingMode),this._onPrePointerObservableObserver=n.onPrePointerObservable.add(function(i){i.type!==Tt.a.POINTERDOWN?i.type===Tt.a.POINTERUP&&(e._isPointerDown=!1):e._isPointerDown=!0}),this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(function(i){i&&e.zoomOnMesh(i)}),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add(function(){e._applyUserInteraction(),e._maintainCameraAboveGround()})},r.prototype.detach=function(){if(this._attachedCamera){var t=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&t.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},r.prototype.zoomOnMesh=function(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=null),t.computeWorldMatrix(!0);var i=t.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(i.minimumWorld,i.maximumWorld,e,n)},r.prototype.zoomOnMeshHierarchy=function(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=null),t.computeWorldMatrix(!0);var i=t.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(i.min,i.max,e,n)},r.prototype.zoomOnMeshesHierarchy=function(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=null);for(var i=new u.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new u.e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),a=0;ap.upperRadiusLimit?p.upperRadiusLimit:d),d):0},r.prototype._maintainCameraAboveGround=function(){var t=this;if(!(this._elevationReturnTime<0)){var e=be.a.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=k.CreateAnimation("beta",k.ANIMATIONTYPE_FLOAT,60,r.EasingFunction));var o=k.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,function(){t._clearAnimationLocks(),t.stopAllAnimations()});o&&this._animatables.push(o)}}},r.prototype._getFrustumSlope=function(){var t=this._attachedCamera;if(!t)return u.d.Zero();var e=t.getScene().getEngine().getAspectRatio(t),n=Math.tan(t.fov/2),i=n*e;return new u.d(i,n)},r.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},r.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=be.a.Now,this.stopAllAnimations(),this._clearAnimationLocks())},r.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(r.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown)},enumerable:!1,configurable:!0}),r.EasingFunction=new St,r.EasingMode=ze.EASINGMODE_EASEINOUT,r.IgnoreBoundsSizeMode=0,r.FitFrustumSidesMode=1,r}(),dr=function(r,t,e,n){t===void 0&&(t=new u.e),e===void 0&&(e=0),n===void 0&&(n=!1),this.direction=r,this.rotatedDirection=t,this.diff=e,this.ignore=n},ep=function(){function r(t){this.ui=t,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new dr(u.e.Up()),new dr(u.e.Down()),new dr(u.e.Left()),new dr(u.e.Right()),new dr(u.e.Forward()),new dr(u.e.Forward().scaleInPlace(-1))],this._tmpMatrix=new u.a,this._tmpVector=new u.e,this._zeroVector=u.e.Zero(),this._lookAtTmpMatrix=new u.a}return r.prototype.init=function(){},r.prototype._closestFace=function(t){var e=this;return this._faceVectors.forEach(function(n){e._target.rotationQuaternion||(e._target.rotationQuaternion=u.b.RotationYawPitchRoll(e._target.rotation.y,e._target.rotation.x,e._target.rotation.z)),e._target.rotationQuaternion.toRotationMatrix(e._tmpMatrix),u.e.TransformCoordinatesToRef(n.direction,e._tmpMatrix,n.rotatedDirection),n.diff=u.e.GetAngleBetweenVectors(n.rotatedDirection,t,u.e.Cross(n.rotatedDirection,t))}),this._faceVectors.reduce(function(n,i){return n.ignore?i:i.ignore||n.diff1)return t._setAllVisibility(t._ownerNode,1),void(t._hoverValue=t.fadeInTime+t.delay);if(t._ownerNode.visibility<0&&(t._setAllVisibility(t._ownerNode,0),t._hoverValue<0))return void(t._hoverValue=0);setTimeout(t._update,t._millisecondsPerFrame)}}}return Object.defineProperty(r.prototype,"name",{get:function(){return"FadeInOut"},enumerable:!1,configurable:!0}),r.prototype.init=function(){},r.prototype.attach=function(t){this._ownerNode=t,this._setAllVisibility(this._ownerNode,0)},r.prototype.detach=function(){this._ownerNode=null},r.prototype.fadeIn=function(t){this._hovered=t,this._update()},r.prototype._setAllVisibility=function(t,e){var n=this;t.visibility=e,t.getChildMeshes().forEach(function(i){n._setAllVisibility(i,e)})},r}(),bi=f(65),np=function(){function r(){this._startDistance=0,this._initialScale=new u.e(0,0,0),this._targetScale=new u.e(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new bi.a({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new bi.a({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(r.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!1,configurable:!0}),r.prototype.init=function(){},r.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},r.prototype.attach=function(t){var e=this;this._ownerNode=t,this._dragBehaviorA.onDragStartObservable.add(function(n){e._dragBehaviorA.dragging&&e._dragBehaviorB.dragging&&(e._dragBehaviorA.currentDraggingPointerID==e._dragBehaviorB.currentDraggingPointerID?e._dragBehaviorA.releaseDrag():(e._initialScale.copyFrom(t.scaling),e._startDistance=e._getCurrentDistance()))}),this._dragBehaviorB.onDragStartObservable.add(function(n){e._dragBehaviorA.dragging&&e._dragBehaviorB.dragging&&(e._dragBehaviorA.currentDraggingPointerID==e._dragBehaviorB.currentDraggingPointerID?e._dragBehaviorB.releaseDrag():(e._initialScale.copyFrom(t.scaling),e._startDistance=e._getCurrentDistance()))}),[this._dragBehaviorA,this._dragBehaviorB].forEach(function(n){n.onDragObservable.add(function(){if(e._dragBehaviorA.dragging&&e._dragBehaviorB.dragging){var i=e._getCurrentDistance()/e._startDistance;e._initialScale.scaleToRef(i,e._targetScale)}})}),t.addBehavior(this._dragBehaviorA),t.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=t.getScene().onBeforeRenderObservable.add(function(){if(e._dragBehaviorA.dragging&&e._dragBehaviorB.dragging){var n=e._targetScale.subtract(t.scaling).scaleInPlace(.1);n.length()>.01&&t.scaling.addInPlace(n)}})},r.prototype.detach=function(){var t=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach(function(e){e.onDragStartObservable.clear(),e.onDragObservable.clear(),t._ownerNode.removeBehavior(e)})},r}(),Dt=f(31),gt=f(24),kn=f(60),Pl=function(){function r(){this._sceneRenderObserver=null,this._targetPosition=new u.e(0,0,0),this._moving=!1,this._startingOrientation=new u.b,this._attachedToElement=!1,this.zDragFactor=3,this.rotateDraggedObject=!0,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0,this.onDragStartObservable=new x.c,this.onDragObservable=new x.c,this.onDragEndObservable=new x.c}return Object.defineProperty(r.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!1,configurable:!0}),r.prototype.init=function(){},Object.defineProperty(r.prototype,"_pointerCamera",{get:function(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera},enumerable:!1,configurable:!0}),r.prototype.attach=function(t){var e=this;this._ownerNode=t,this._scene=this._ownerNode.getScene(),r._virtualScene||(r._virtualScene=new _e.a(this._scene.getEngine(),{virtual:!0}),r._virtualScene.detachControl(),this._scene.getEngine().scenes.pop());var n=null,i=new u.e(0,0,0);this._virtualOriginMesh=new Dt.a("",r._virtualScene),this._virtualOriginMesh.rotationQuaternion=new u.b,this._virtualDragMesh=new Dt.a("",r._virtualScene),this._virtualDragMesh.rotationQuaternion=new u.b,this._pointerObserver=this._scene.onPointerObservable.add(function(a,s){if(a.type==Tt.a.POINTERDOWN){if(!e.dragging&&a.pickInfo&&a.pickInfo.hit&&a.pickInfo.pickedMesh&&a.pickInfo.ray&&(O=a.pickInfo.pickedMesh,e._ownerNode==O||O.isDescendantOf(e._ownerNode))){e._pointerCamera&&e._pointerCamera.cameraRigMode==gt.a.RIG_MODE_NONE&&a.pickInfo.ray.origin.copyFrom(e._pointerCamera.globalPosition),n=e._ownerNode,kn.a._RemoveAndStorePivotPoint(n),i.copyFrom(a.pickInfo.ray.origin),e._virtualOriginMesh.position.copyFrom(a.pickInfo.ray.origin),e._virtualOriginMesh.lookAt(a.pickInfo.ray.origin.add(a.pickInfo.ray.direction)),e._virtualOriginMesh.removeChild(e._virtualDragMesh),n.computeWorldMatrix(),e._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=u.b.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var d=n.parent;n.setParent(null),e._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(d),e._virtualOriginMesh.addChild(e._virtualDragMesh),e._targetPosition.copyFrom(e._virtualDragMesh.absolutePosition),e.dragging=!0,e.currentDraggingPointerID=a.event.pointerId,e.detachCameraControls&&e._pointerCamera&&!e._pointerCamera.leftCamera&&(e._pointerCamera.inputs.attachedToElement?(e._pointerCamera.detachControl(),e._attachedToElement=!0):e._attachedToElement=!1),kn.a._RestorePivotPoint(n),e.onDragStartObservable.notifyObservers({})}}else if(a.type==Tt.a.POINTERUP||a.type==Tt.a.POINTERDOUBLETAP)e.currentDraggingPointerID==a.event.pointerId&&(e.dragging=!1,e._moving=!1,e.currentDraggingPointerID=-1,n=null,e._virtualOriginMesh.removeChild(e._virtualDragMesh),e.detachCameraControls&&e._attachedToElement&&e._pointerCamera&&!e._pointerCamera.leftCamera&&(e._pointerCamera.attachControl(!0),e._attachedToElement=!1),e.onDragEndObservable.notifyObservers({}));else if(a.type==Tt.a.POINTERMOVE&&e.currentDraggingPointerID==a.event.pointerId&&e.dragging&&a.pickInfo&&a.pickInfo.ray&&n){var p=e.zDragFactor;e._pointerCamera&&e._pointerCamera.cameraRigMode==gt.a.RIG_MODE_NONE&&(a.pickInfo.ray.origin.copyFrom(e._pointerCamera.globalPosition),p=0);var y=a.pickInfo.ray.origin.subtract(i);i.copyFrom(a.pickInfo.ray.origin);var P=-u.e.Dot(y,a.pickInfo.ray.direction);e._virtualOriginMesh.addChild(e._virtualDragMesh),e._virtualDragMesh.position.z-=e._virtualDragMesh.position.z<1?P*e.zDragFactor:P*p*e._virtualDragMesh.position.z,e._virtualDragMesh.position.z<0&&(e._virtualDragMesh.position.z=0),e._virtualOriginMesh.position.copyFrom(a.pickInfo.ray.origin),e._virtualOriginMesh.lookAt(a.pickInfo.ray.origin.add(a.pickInfo.ray.direction)),e._virtualOriginMesh.removeChild(e._virtualDragMesh),e._targetPosition.copyFrom(e._virtualDragMesh.absolutePosition),n.parent&&u.e.TransformCoordinatesToRef(e._targetPosition,u.a.Invert(n.parent.getWorldMatrix()),e._targetPosition),e._moving||e._startingOrientation.copyFrom(e._virtualDragMesh.rotationQuaternion),e._moving=!0}var O});var o=new u.b;this._sceneRenderObserver=t.getScene().onBeforeRenderObservable.add(function(){if(e.dragging&&e._moving&&n){if(kn.a._RemoveAndStorePivotPoint(n),n.position.addInPlace(e._targetPosition.subtract(n.position).scale(e.dragDeltaRatio)),e.rotateDraggedObject){o.copyFrom(e._startingOrientation),o.x=-o.x,o.y=-o.y,o.z=-o.z,e._virtualDragMesh.rotationQuaternion.multiplyToRef(o,o),u.b.RotationYawPitchRollToRef(o.toEulerAngles("xyz").y,0,0,o),o.multiplyToRef(e._startingOrientation,o);var a=n.parent;(!a||a.scaling&&!a.scaling.isNonUniformWithinEpsilon(.001))&&(n.setParent(null),u.b.SlerpToRef(n.rotationQuaternion,o,e.dragDeltaRatio,n.rotationQuaternion),n.setParent(a))}kn.a._RestorePivotPoint(n),e.onDragObservable.notifyObservers()}})},r.prototype.detach=function(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.attachControl(!0),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver)),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualOriginMesh&&this._virtualOriginMesh.dispose(),this._virtualDragMesh&&this._virtualDragMesh.dispose(),this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()},r}(),ip=function(){function r(t,e,n){if(this.targetPosition=u.e.Zero(),this.poleTargetPosition=u.e.Zero(),this.poleTargetLocalOffset=u.e.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=u.b.Identity(),this._bone1Mat=u.a.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=u.e.Right(),this._slerping=!1,this._adjustRoll=0,this._bone2=e,this._bone1=e.getParent(),this._bone1){this.mesh=t;var i=e.getPosition();if(e.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,i.x>i.y&&i.x>i.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var o=this._bone1.getScale(),a=this._bone2.getScale();this._bone1Length=this._bone1.length*o.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*a.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var s=this._bone2.children[0].getAbsolutePosition(t),d=this._bone2.getAbsolutePosition(t),p=this._bone1.getAbsolutePosition(t);this._bone1Length=u.e.Distance(s,d),this._bone2Length=u.e.Distance(d,p)}this._bone1.getRotationMatrixToRef(ye.c.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,n&&(n.targetMesh&&(this.targetMesh=n.targetMesh,this.targetMesh.computeWorldMatrix(!0)),n.poleTargetMesh?(this.poleTargetMesh=n.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):n.poleTargetBone?this.poleTargetBone=n.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),n.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(n.poleTargetLocalOffset),n.poleAngle&&(this.poleAngle=n.poleAngle),n.bendAxis&&this._bendAxis.copyFrom(n.bendAxis),n.maxAngle&&(this.maxAngle=n.maxAngle),n.slerpAmount&&(this.slerpAmount=n.slerpAmount))}}return Object.defineProperty(r.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(t){this._setMaxAngle(t)},enumerable:!1,configurable:!0}),r.prototype._setMaxAngle=function(t){t<0&&(t=0),(t>Math.PI||t==null)&&(t=Math.PI),this._maxAngle=t;var e=this._bone1Length,n=this._bone2Length;this._maxReach=Math.sqrt(e*e+n*n-2*e*n*Math.cos(t))},r.prototype.update=function(){var t=this._bone1;if(t){var e=this.targetPosition,n=this.poleTargetPosition,i=r._tmpMats[0],o=r._tmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&u.e.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var a=r._tmpVecs[0],s=r._tmpVecs[1],d=r._tmpVecs[2],p=r._tmpVecs[3],y=r._tmpVecs[4],P=r._tmpQuat;t.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,y),y.x==0&&y.y==0&&y.z==0?y.y=1:y.normalize(),e.subtractToRef(a,p),p.normalize(),u.e.CrossToRef(p,y,s),s.normalize(),u.e.CrossToRef(p,s,d),d.normalize(),u.a.FromXYZAxesToRef(d,p,s,i);var O=this._bone1Length,U=this._bone2Length,F=u.e.Distance(a,e);this._maxReach>0&&(F=Math.min(this._maxReach,F));var z=(U*U+F*F-O*O)/(2*U*F),J=(F*F+O*O-U*U)/(2*F*O);z>1&&(z=1),J>1&&(J=1),z<-1&&(z=-1),J<-1&&(J=-1);var ie=Math.acos(z),se=Math.acos(J),ce=-ie-se;if(this._rightHandedSystem)u.a.RotationYawPitchRollToRef(0,0,this._adjustRoll,o),o.multiplyToRef(i,i),u.a.RotationAxisToRef(this._bendAxis,se,o),o.multiplyToRef(i,i);else{var ue=r._tmpVecs[5];ue.copyFrom(this._bendAxis),ue.x*=-1,u.a.RotationAxisToRef(ue,-se,o),o.multiplyToRef(i,i)}this.poleAngle&&(u.a.RotationAxisToRef(p,this.poleAngle,o),i.multiplyToRef(o,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||u.b.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),u.b.FromRotationMatrixToRef(i,P),u.b.SlerpToRef(this._bone1Quat,P,this.slerpAmount,this._bone1Quat),ce=this._bone2Ang*(1-this.slerpAmount)+ce*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,ye.c.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,ye.c.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,ce,ye.c.LOCAL),this._bone2Ang=ce}},r._tmpVecs=[u.e.Zero(),u.e.Zero(),u.e.Zero(),u.e.Zero(),u.e.Zero(),u.e.Zero()],r._tmpQuat=u.b.Identity(),r._tmpMats=[u.a.Identity(),u.a.Identity()],r}(),rp=function(){function r(t,e,n,i){if(this.upAxis=u.e.Up(),this.upAxisSpace=ye.c.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=u.b.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=u.e.Forward(),this.mesh=t,this.bone=e,this.target=n,i&&(i.adjustYaw&&(this.adjustYaw=i.adjustYaw),i.adjustPitch&&(this.adjustPitch=i.adjustPitch),i.adjustRoll&&(this.adjustRoll=i.adjustRoll),i.maxYaw!=null?this.maxYaw=i.maxYaw:this.maxYaw=Math.PI,i.minYaw!=null?this.minYaw=i.minYaw:this.minYaw=-Math.PI,i.maxPitch!=null?this.maxPitch=i.maxPitch:this.maxPitch=Math.PI,i.minPitch!=null?this.minPitch=i.minPitch:this.minPitch=-Math.PI,i.slerpAmount!=null&&(this.slerpAmount=i.slerpAmount),i.upAxis!=null&&(this.upAxis=i.upAxis),i.upAxisSpace!=null&&(this.upAxisSpace=i.upAxisSpace),i.yawAxis!=null||i.pitchAxis!=null)){var o=ye.a.Y,a=ye.a.X;i.yawAxis!=null&&(o=i.yawAxis.clone()).normalize(),i.pitchAxis!=null&&(a=i.pitchAxis.clone()).normalize();var s=u.e.Cross(a,o);this._transformYawPitch=u.a.Identity(),u.a.FromXYZAxesToRef(a,o,s,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}e.getParent()||this.upAxisSpace!=ye.c.BONE||(this.upAxisSpace=ye.c.LOCAL)}return Object.defineProperty(r.prototype,"minYaw",{get:function(){return this._minYaw},set:function(t){this._minYaw=t,this._minYawSin=Math.sin(t),this._minYawCos=Math.cos(t),this._maxYaw!=null&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(t){this._maxYaw=t,this._maxYawSin=Math.sin(t),this._maxYawCos=Math.cos(t),this._minYaw!=null&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"minPitch",{get:function(){return this._minPitch},set:function(t){this._minPitch=t,this._minPitchTan=Math.tan(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(t){this._maxPitch=t,this._maxPitchTan=Math.tan(t)},enumerable:!1,configurable:!0}),r.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)this._firstFrameSkipped=!0;else{var t=this.bone,e=r._tmpVecs[0];t.getAbsolutePositionToRef(this.mesh,e);var n=this.target,i=r._tmpMats[0],o=r._tmpMats[1],a=this.mesh,s=t.getParent(),d=r._tmpVecs[1];d.copyFrom(this.upAxis),this.upAxisSpace==ye.c.BONE&&s?(this._transformYawPitch&&u.e.TransformCoordinatesToRef(d,this._transformYawPitchInv,d),s.getDirectionToRef(d,this.mesh,d)):this.upAxisSpace==ye.c.LOCAL&&(a.getDirectionToRef(d,d),a.scaling.x==1&&a.scaling.y==1&&a.scaling.z==1||d.normalize());var p=!1,y=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(p=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(y=!0),p||y){var P=r._tmpMats[2],O=r._tmpMats[3];if(this.upAxisSpace==ye.c.BONE&&d.y==1&&s)s.getRotationMatrixToRef(ye.c.WORLD,this.mesh,P);else if(this.upAxisSpace!=ye.c.LOCAL||d.y!=1||s){(F=r._tmpVecs[2]).copyFrom(this._fowardAxis),this._transformYawPitch&&u.e.TransformCoordinatesToRef(F,this._transformYawPitchInv,F),s?s.getDirectionToRef(F,this.mesh,F):a.getDirectionToRef(F,F);var U=u.e.Cross(d,F);U.normalize();var F=u.e.Cross(U,d);u.a.FromXYZAxesToRef(U,d,F,P)}else P.copyFrom(a.getWorldMatrix());P.invertToRef(O);var z=null;if(y){var J=r._tmpVecs[3];n.subtractToRef(e,J),u.e.TransformCoordinatesToRef(J,O,J),z=Math.sqrt(J.x*J.x+J.z*J.z);var ie=Math.atan2(J.y,z),se=ie;ie>this._maxPitch?(J.y=this._maxPitchTan*z,se=this._maxPitch):iethis._maxYaw||ceMath.PI?this._isAngleBetween(ce,this._maxYaw,this._midYawConstraint)?(J.z=this._maxYawCos*z,J.x=this._maxYawSin*z,ue=this._maxYaw):this._isAngleBetween(ce,this._midYawConstraint,this._minYaw)&&(J.z=this._minYawCos*z,J.x=this._minYawSin*z,ue=this._minYaw):ce>this._maxYaw?(J.z=this._maxYawCos*z,J.x=this._maxYawSin*z,ue=this._maxYaw):ceMath.PI){var fe=r._tmpVecs[8];fe.copyFrom(ye.a.Z),this._transformYawPitch&&u.e.TransformCoordinatesToRef(fe,this._transformYawPitchInv,fe);var ve=r._tmpMats[4];this._boneQuat.toRotationMatrix(ve),this.mesh.getWorldMatrix().multiplyToRef(ve,ve),u.e.TransformCoordinatesToRef(fe,ve,fe),u.e.TransformCoordinatesToRef(fe,O,fe);var Te=Math.atan2(fe.x,fe.z);if(this._getAngleBetween(Te,ce)>this._getAngleBetween(Te,this._midYawConstraint)){z==null&&(z=Math.sqrt(J.x*J.x+J.z*J.z));var Oe=this._getAngleBetween(Te,this._maxYaw);this._getAngleBetween(Te,this._minYaw)Math.PI?n-=2*Math.PI:n<-Math.PI&&(n+=2*Math.PI),n},r.prototype._getAngleBetween=function(t,e){var n=0;return(n=(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)?e-t:t-e)>Math.PI&&(n=2*Math.PI-n),n},r.prototype._isAngleBetween=function(t,e,n){if(t=(t%=2*Math.PI)<0?t+2*Math.PI:t,(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(n=(n%=2*Math.PI)<0?n+2*Math.PI:n)){if(t>e&&tn&&t>Oe,Ee=0;Ee<6;Ee++){var Se=Te[Oe][Ee];ve&&(Se=Cl(Se,Pe,Pe,i)),U.texImage2D(Ee,Oe,fe,Pe,Pe,0,ue,ce,Se)}O._bindTextureDirectly(U.TEXTURE_CUBE_MAP,null)}else O.updateRawCubeTexture(F,se,n,i,P);F.isReady=!0,t?._removePendingData(F),d&&d()}})(z)},void 0,t?.offlineProvider,!0,function(z,J){t?._removePendingData(F),p&&z&&p(z.status+" "+z.statusText,J)}),F},Bt.a.prototype.createRawTexture2DArray=xl(!1),Bt.a.prototype.createRawTexture3D=xl(!0),Bt.a.prototype.updateRawTexture2DArray=Rl(!1),Bt.a.prototype.updateRawTexture3D=Rl(!0);var $n=function(r){function t(e,n,i,o,a,s,d,p,y){s===void 0&&(s=!0),d===void 0&&(d=!1),p===void 0&&(p=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),y===void 0&&(y=h.a.TEXTURETYPE_UNSIGNED_INT);var P=r.call(this,null,a,!s,d)||this;return P.format=o,P._engine&&(P._texture=P._engine.createRawTexture(e,n,i,o,s,d,p,null,y),P.wrapU=we.a.CLAMP_ADDRESSMODE,P.wrapV=we.a.CLAMP_ADDRESSMODE),P}return Object(c.d)(t,r),t.prototype.update=function(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t.CreateLuminanceTexture=function(e,n,i,o,a,s,d){return a===void 0&&(a=!0),s===void 0&&(s=!1),d===void 0&&(d=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,n,i,h.a.TEXTUREFORMAT_LUMINANCE,o,a,s,d)},t.CreateLuminanceAlphaTexture=function(e,n,i,o,a,s,d){return a===void 0&&(a=!0),s===void 0&&(s=!1),d===void 0&&(d=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,n,i,h.a.TEXTUREFORMAT_LUMINANCE_ALPHA,o,a,s,d)},t.CreateAlphaTexture=function(e,n,i,o,a,s,d){return a===void 0&&(a=!0),s===void 0&&(s=!1),d===void 0&&(d=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,n,i,h.a.TEXTUREFORMAT_ALPHA,o,a,s,d)},t.CreateRGBTexture=function(e,n,i,o,a,s,d,p){return a===void 0&&(a=!0),s===void 0&&(s=!1),d===void 0&&(d=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),p===void 0&&(p=h.a.TEXTURETYPE_UNSIGNED_INT),new t(e,n,i,h.a.TEXTUREFORMAT_RGB,o,a,s,d,p)},t.CreateRGBATexture=function(e,n,i,o,a,s,d,p){return a===void 0&&(a=!0),s===void 0&&(s=!1),d===void 0&&(d=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),p===void 0&&(p=h.a.TEXTURETYPE_UNSIGNED_INT),new t(e,n,i,h.a.TEXTUREFORMAT_RGBA,o,a,s,d,p)},t.CreateRTexture=function(e,n,i,o,a,s,d,p){return a===void 0&&(a=!0),s===void 0&&(s=!1),d===void 0&&(d=we.a.TRILINEAR_SAMPLINGMODE),p===void 0&&(p=h.a.TEXTURETYPE_FLOAT),new t(e,n,i,h.a.TEXTUREFORMAT_R,o,a,s,d,p)},t}(we.a),Bo=function(){function r(t,e,n){this.name=t,this.id=e,this.bones=new Array,this.needInitialSkinMatrix=!1,this.overrideMesh=null,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=u.a.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._waitingOverrideMeshId=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new x.c,this.bones=[],this._scene=n||te.a.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;var i=this._scene.getEngine().getCaps();this._canUseTextureForBones=i.textureFloat&&i.maxVertexTextureImageUnits>0}return Object.defineProperty(r.prototype,"useTextureToStoreBoneMatrices",{get:function(){return this._useTextureToStoreBoneMatrices},set:function(t){this._useTextureToStoreBoneMatrices=t,this._markAsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(t){this._animationPropertiesOverride=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isUsingTextureForMatrices",{get:function(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),r.prototype.getClassName=function(){return"Skeleton"},r.prototype.getChildren=function(){return this.bones.filter(function(t){return!t.getParent()})},r.prototype.getTransformMatrices=function(t){return this.needInitialSkinMatrix&&t._bonesTransformMatrices?t._bonesTransformMatrices:(this._transformMatrices||this.prepare(),this._transformMatrices)},r.prototype.getTransformMatrixTexture=function(t){return this.needInitialSkinMatrix&&t._transformMatrixTexture?t._transformMatrixTexture:this._transformMatrixTexture},r.prototype.getScene=function(){return this._scene},r.prototype.toString=function(t){var e="Name: "+this.name+", nBones: "+this.bones.length;if(e+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),t){e+=", Ranges: {";var n=!0;for(var i in this._ranges)n&&(e+=", ",n=!1),e+=i;e+="}"}return e},r.prototype.getBoneIndexByName=function(t){for(var e=0,n=this.bones.length;e-1&&this._meshesWithPoseMatrix.splice(e,1)},r.prototype._computeTransformMatrices=function(t,e){this.onBeforeComputeObservable.notifyObservers(this);for(var n=0;n0)for(var t=0,e=this.bones;t0&&(s.animation=o.animations[0].serialize()),n.ranges=[],this._ranges){var p=this._ranges[d];if(p){var y={};y.name=d,y.from=p.from,y.to=p.to,n.ranges.push(y)}}}return n},r.Parse=function(t,e){var n,i=new r(t.name,t.id,e);for(t.dimensionsAtRest&&(i.dimensionsAtRest=u.e.FromArray(t.dimensionsAtRest)),i.needInitialSkinMatrix=t.needInitialSkinMatrix,t.overrideMeshId&&(i._hasWaitingData=!0,i._waitingOverrideMeshId=t.overrideMeshId),n=0;n-1&&(s=i.bones[o.parentBoneIndex]);var d=o.rest?u.a.FromArray(o.rest):null,p=new Be(o.name,i,s,u.a.FromArray(o.matrix),d,null,a);o.id!==void 0&&o.id!==null&&(p.id=o.id),o.length&&(p.length=o.length),o.metadata&&(p.metadata=o.metadata),o.animation&&p.animations.push(k.Parse(o.animation)),o.linkedTransformNodeId!==void 0&&o.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,p._waitingTransformNodeId=o.linkedTransformNodeId)}if(t.ranges)for(n=0;n0&&(t=this._meshesWithPoseMatrix[0].getPoseMatrix()),t},r.prototype.sortBones=function(){for(var t=new Array,e=new Array(this.bones.length),n=0;n=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]})}return Object.defineProperty(r.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!1,configurable:!0}),r.prototype.onleftstickchanged=function(t){this._onleftstickchanged=t},r.prototype.onrightstickchanged=function(t){this._onrightstickchanged=t},Object.defineProperty(r.prototype,"leftStick",{get:function(){return this._leftStick},set:function(t){!this._onleftstickchanged||this._leftStick.x===t.x&&this._leftStick.y===t.y||this._onleftstickchanged(t),this._leftStick=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"rightStick",{get:function(){return this._rightStick},set:function(t){!this._onrightstickchanged||this._rightStick.x===t.x&&this._rightStick.y===t.y||this._onrightstickchanged(t),this._rightStick=t},enumerable:!1,configurable:!0}),r.prototype.update=function(){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]})},r.prototype.dispose=function(){},r.GAMEPAD=0,r.GENERIC=1,r.XBOX=2,r.POSE_ENABLED=3,r.DUALSHOCK=4,r}(),Ol=function(r){function t(e,n,i){var o=r.call(this,e,n,i)||this;return o.onButtonDownObservable=new x.c,o.onButtonUpObservable=new x.c,o.type=hn.GENERIC,o._buttons=new Array(i.buttons.length),o}return Object(c.d)(t,r),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype._setButtonValue=function(e,n,i){return e!==n&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype.update=function(){r.prototype.update.call(this);for(var e=0;e.005&&(t.inertialAlphaOffset+=n)}if(e.y!=0){var i=e.y/this.gamepadRotationSensibility*this._yAxisScale;i!=0&&Math.abs(i)>.005&&(t.inertialBetaOffset+=i)}}var o=this.gamepad.leftStick;if(o&&o.y!=0){var a=o.y/this.gamepadMoveSensibility;a!=0&&Math.abs(a)>.005&&(this.camera.inertialRadiusOffset-=a)}}},r.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},r.prototype.getSimpleName=function(){return"gamepad"},Object(c.c)([Object(L.c)()],r.prototype,"gamepadRotationSensibility",void 0),Object(c.c)([Object(L.c)()],r.prototype,"gamepadMoveSensibility",void 0),r}();un.ArcRotateCameraGamepadInput=Ka;var qi=f(66),Qa=function(){function r(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}return r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){e._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(n){var i,o=n.event;o.metaKey||(n.type===qi.a.KEYDOWN?(e._ctrlPressed=o.ctrlKey,e._altPressed=o.altKey,(e.keysUp.indexOf(o.keyCode)!==-1||e.keysDown.indexOf(o.keyCode)!==-1||e.keysLeft.indexOf(o.keyCode)!==-1||e.keysRight.indexOf(o.keyCode)!==-1||e.keysReset.indexOf(o.keyCode)!==-1)&&((i=e._keys.indexOf(o.keyCode))===-1&&e._keys.push(o.keyCode),o.preventDefault&&(t||o.preventDefault()))):e.keysUp.indexOf(o.keyCode)===-1&&e.keysDown.indexOf(o.keyCode)===-1&&e.keysLeft.indexOf(o.keyCode)===-1&&e.keysRight.indexOf(o.keyCode)===-1&&e.keysReset.indexOf(o.keyCode)===-1||((i=e._keys.indexOf(o.keyCode))>=0&&e._keys.splice(i,1),o.preventDefault&&(t||o.preventDefault())))}))},r.prototype.detachControl=function(t){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=[]},r.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,e=0;e0?n/(1+this.wheelDeltaPercentage):n*(1+this.wheelDeltaPercentage)},r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(n,i){if(n.type===Tt.a.POINTERWHEEL){var o=n.event,a=0,s=o,d=0;if(d=s.wheelDelta?s.wheelDelta:60*-(o.deltaY||o.detail),e.wheelDeltaPercentage){if((a=e.computeDeltaFromMouseWheelLegacyEvent(d,e.camera.radius))>0){for(var p=e.camera.radius,y=e.camera.inertialRadiusOffset+a,P=0;P<20&&Math.abs(y)>.001;P++)p-=y,y*=e.camera.inertia;p=$.a.Clamp(p,0,Number.MAX_VALUE),a=e.computeDeltaFromMouseWheelLegacyEvent(d,p)}}else a=d/(40*e.wheelPrecision);a&&(e.camera.inertialRadiusOffset+=a),o.preventDefault&&(t||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,Tt.a.POINTERWHEEL)},r.prototype.detachControl=function(t){this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},r.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},r.prototype.getSimpleName=function(){return"mousewheel"},Object(c.c)([Object(L.c)()],r.prototype,"wheelPrecision",void 0),Object(c.c)([Object(L.c)()],r.prototype,"wheelDeltaPercentage",void 0),r}();un.ArcRotateCameraMouseWheelInput=qa;var Ml=function(){function r(){this.buttons=[0,1,2]}return r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments);var n=this.camera.getEngine(),i=n.getInputElement(),o=0,a=null;this.pointA=null,this.pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=function(d,p){var y=d.event,P=y.pointerType==="touch";if(!n.isInVRExclusivePointerMode&&(d.type===Tt.a.POINTERMOVE||e.buttons.indexOf(y.button)!==-1)){var O=y.srcElement||y.target;if(e._altKey=y.altKey,e._ctrlKey=y.ctrlKey,e._metaKey=y.metaKey,e._shiftKey=y.shiftKey,e._buttonsPressed=y.buttons,n.isPointerLock){var U=y.movementX||y.mozMovementX||y.webkitMovementX||y.msMovementX||0,F=y.movementY||y.mozMovementY||y.webkitMovementY||y.msMovementY||0;e.onTouch(null,U,F),e.pointA=null,e.pointB=null}else if(d.type===Tt.a.POINTERDOWN&&O){try{O.setPointerCapture(y.pointerId)}catch{}e.pointA===null?e.pointA={x:y.clientX,y:y.clientY,pointerId:y.pointerId,type:y.pointerType}:e.pointB===null&&(e.pointB={x:y.clientX,y:y.clientY,pointerId:y.pointerId,type:y.pointerType}),e.onButtonDown(y),t||(y.preventDefault(),i&&i.focus())}else if(d.type===Tt.a.POINTERDOUBLETAP)e.onDoubleTap(y.pointerType);else if(d.type===Tt.a.POINTERUP&&O){try{O.releasePointerCapture(y.pointerId)}catch{}P||(e.pointB=null),n._badOS?e.pointA=e.pointB=null:e.pointB&&e.pointA&&e.pointA.pointerId==y.pointerId?(e.pointA=e.pointB,e.pointB=null):e.pointA&&e.pointB&&e.pointB.pointerId==y.pointerId?e.pointB=null:e.pointA=e.pointB=null,(o!==0||a)&&(e.onMultiTouch(e.pointA,e.pointB,o,0,a,null),o=0,a=null),e.onButtonUp(y),t||y.preventDefault()}else if(d.type===Tt.a.POINTERMOVE){if(t||y.preventDefault(),e.pointA&&e.pointB===null)U=y.clientX-e.pointA.x,F=y.clientY-e.pointA.y,e.onTouch(e.pointA,U,F),e.pointA.x=y.clientX,e.pointA.y=y.clientY;else if(e.pointA&&e.pointB){var z=e.pointA.pointerId===y.pointerId?e.pointA:e.pointB;z.x=y.clientX,z.y=y.clientY;var J=e.pointA.x-e.pointB.x,ie=e.pointA.y-e.pointB.y,se=J*J+ie*ie,ce={x:(e.pointA.x+e.pointB.x)/2,y:(e.pointA.y+e.pointB.y)/2,pointerId:y.pointerId,type:d.type};e.onMultiTouch(e.pointA,e.pointB,o,se,a,ce),a=ce,o=se}}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,Tt.a.POINTERDOWN|Tt.a.POINTERUP|Tt.a.POINTERMOVE),this._onLostFocus=function(){e.pointA=e.pointB=null,o=0,a=null,e.onLostFocus()},i&&i.addEventListener("contextmenu",this.onContextMenu.bind(this),!1);var s=this.camera.getScene().getEngine().getHostWindow();s&&Ye.b.RegisterTopRootEvents(s,[{name:"blur",handler:this._onLostFocus}])},r.prototype.detachControl=function(t){if(this._onLostFocus){var e=this.camera.getScene().getEngine().getHostWindow();e&&Ye.b.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this.onContextMenu){var n=this.camera.getScene().getEngine().getInputElement();n&&n.removeEventListener("contextmenu",this.onContextMenu)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0},r.prototype.getClassName=function(){return"BaseCameraPointersInput"},r.prototype.getSimpleName=function(){return"pointers"},r.prototype.onDoubleTap=function(t){},r.prototype.onTouch=function(t,e,n){},r.prototype.onMultiTouch=function(t,e,n,i,o,a){},r.prototype.onContextMenu=function(t){t.preventDefault()},r.prototype.onButtonDown=function(t){},r.prototype.onButtonUp=function(t){},r.prototype.onLostFocus=function(){},Object(c.c)([Object(L.c)()],r.prototype,"buttons",void 0),r}(),Za=function(r){function t(){var e=r!==null&&r.apply(this,arguments)||this;return e.buttons=[0,1,2],e.angularSensibilityX=1e3,e.angularSensibilityY=1e3,e.pinchPrecision=12,e.pinchDeltaPercentage=0,e.useNaturalPinchZoom=!1,e.panningSensibility=1e3,e.multiTouchPanning=!0,e.multiTouchPanAndZoom=!0,e.pinchInwards=!0,e._isPanClick=!1,e._twoFingerActivityCount=0,e._isPinching=!1,e}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.onTouch=function(e,n,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-n/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=n/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)},t.prototype.onDoubleTap=function(e){this.camera.useInputToRestoreState&&this.camera.restoreState()},t.prototype.onMultiTouch=function(e,n,i,o,a,s){if(!(i===0&&a===null||o===0&&s===null)){var d=this.pinchInwards?1:-1;if(this.multiTouchPanAndZoom){if(this.useNaturalPinchZoom?this.camera.radius=this.camera.radius*Math.sqrt(i)/Math.sqrt(o):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(o-i)*this.camera.radius*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(o-i)/(this.pinchPrecision*d*(this.angularSensibilityX+this.angularSensibilityY)/2),this.panningSensibility!==0&&a&&s){var p=s.x-a.x,y=s.y-a.y;this.camera.inertialPanningX+=-p/this.panningSensibility,this.camera.inertialPanningY+=y/this.panningSensibility}}else{this._twoFingerActivityCount++;var P=Math.sqrt(i),O=Math.sqrt(o);this._isPinching||this._twoFingerActivityCount<20&&Math.abs(O-P)>this.camera.pinchToPanMaxDistance?(this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(o-i)*this.camera.radius*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(o-i)/(this.pinchPrecision*d*(this.angularSensibilityX+this.angularSensibilityY)/2),this._isPinching=!0):this.panningSensibility!==0&&this.multiTouchPanning&&s&&a&&(p=s.x-a.x,y=s.y-a.y,this.camera.inertialPanningX+=-p/this.panningSensibility,this.camera.inertialPanningY+=y/this.panningSensibility)}}},t.prototype.onButtonDown=function(e){this._isPanClick=e.button===this.camera._panningMouseButton},t.prototype.onButtonUp=function(e){this._twoFingerActivityCount=0,this._isPinching=!1},t.prototype.onLostFocus=function(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1},Object(c.c)([Object(L.c)()],t.prototype,"buttons",void 0),Object(c.c)([Object(L.c)()],t.prototype,"angularSensibilityX",void 0),Object(c.c)([Object(L.c)()],t.prototype,"angularSensibilityY",void 0),Object(c.c)([Object(L.c)()],t.prototype,"pinchPrecision",void 0),Object(c.c)([Object(L.c)()],t.prototype,"pinchDeltaPercentage",void 0),Object(c.c)([Object(L.c)()],t.prototype,"useNaturalPinchZoom",void 0),Object(c.c)([Object(L.c)()],t.prototype,"panningSensibility",void 0),Object(c.c)([Object(L.c)()],t.prototype,"multiTouchPanning",void 0),Object(c.c)([Object(L.c)()],t.prototype,"multiTouchPanAndZoom",void 0),t}(Ml);un.ArcRotateCameraPointersInput=Za;var Uo=function(r){function t(e){return r.call(this,e)||this}return Object(c.d)(t,r),t.prototype.addMouseWheel=function(){return this.add(new qa),this},t.prototype.addPointers=function(){return this.add(new Za),this},t.prototype.addKeyboard=function(){return this.add(new Qa),this},t}(Jr);Uo.prototype.addVRDeviceOrientation=function(){return this.add(new Ja),this};var Ja=function(){function r(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}return r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(t);var n=this.camera.getScene().getEngine().getHostWindow();n&&(typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(function(i){i==="granted"?n.addEventListener("deviceorientation",e._deviceOrientationHandler):Ye.b.Warn("Permission not granted.")}).catch(function(i){Ye.b.Error(i)}):n.addEventListener("deviceorientation",this._deviceOrientationHandler))},r.prototype._onOrientationEvent=function(t){t.alpha!==null&&(this._alpha=(0|+t.alpha)*this.alphaCorrection),t.gamma!==null&&(this._gamma=(0|+t.gamma)*this.gammaCorrection),this._dirty=!0},r.prototype.checkInputs=function(){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)},r.prototype.detachControl=function(t){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},r.prototype.getClassName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},r.prototype.getSimpleName=function(){return"VRDeviceOrientation"},r}();un.ArcRotateCameraVRDeviceOrientationInput=Ja;var $a=function(){function r(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}return r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){e._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(n){var i,o=n.event;n.type===qi.a.KEYDOWN?e.keysForward.indexOf(o.keyCode)===-1&&e.keysBackward.indexOf(o.keyCode)===-1&&e.keysUp.indexOf(o.keyCode)===-1&&e.keysDown.indexOf(o.keyCode)===-1&&e.keysLeft.indexOf(o.keyCode)===-1&&e.keysRight.indexOf(o.keyCode)===-1||((i=e._keys.indexOf(o.keyCode))===-1&&e._keys.push(o.keyCode),t||o.preventDefault()):e.keysForward.indexOf(o.keyCode)===-1&&e.keysBackward.indexOf(o.keyCode)===-1&&e.keysUp.indexOf(o.keyCode)===-1&&e.keysDown.indexOf(o.keyCode)===-1&&e.keysLeft.indexOf(o.keyCode)===-1&&e.keysRight.indexOf(o.keyCode)===-1||((i=e._keys.indexOf(o.keyCode))>=0&&e._keys.splice(i,1),t||o.preventDefault())}))},r.prototype.detachControl=function(t){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=[]},r.prototype.getClassName=function(){return"FlyCameraKeyboardInput"},r.prototype._onLostFocus=function(t){this._keys=[]},r.prototype.getSimpleName=function(){return"keyboard"},r.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,e=0;e=0&&e._keys.splice(i,1),o.preventDefault&&(t||o.preventDefault())))}))},r.prototype.detachControl=function(t){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=[]},r.prototype.checkInputs=function(){var t=this;this._onKeyboardObserver&&this._keys.forEach(function(e){t.keysHeightOffsetIncr.indexOf(e)!==-1&&t._modifierHeightOffset()?t.camera.heightOffset+=t.heightSensibility:t.keysHeightOffsetDecr.indexOf(e)!==-1&&t._modifierHeightOffset()?t.camera.heightOffset-=t.heightSensibility:t.keysRotationOffsetIncr.indexOf(e)!==-1&&t._modifierRotationOffset()?(t.camera.rotationOffset+=t.rotationSensibility,t.camera.rotationOffset%=360):t.keysRotationOffsetDecr.indexOf(e)!==-1&&t._modifierRotationOffset()?(t.camera.rotationOffset-=t.rotationSensibility,t.camera.rotationOffset%=360):t.keysRadiusIncr.indexOf(e)!==-1&&t._modifierRadius()?t.camera.radius+=t.radiusSensibility:t.keysRadiusDecr.indexOf(e)!==-1&&t._modifierRadius()&&(t.camera.radius-=t.radiusSensibility)})},r.prototype.getClassName=function(){return"FollowCameraKeyboardMoveInput"},r.prototype.getSimpleName=function(){return"keyboard"},r.prototype._modifierHeightOffset=function(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed},r.prototype._modifierRotationOffset=function(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed},r.prototype._modifierRadius=function(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed},Object(c.c)([Object(L.c)()],r.prototype,"keysHeightOffsetIncr",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysHeightOffsetDecr",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysHeightOffsetModifierAlt",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysHeightOffsetModifierCtrl",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysHeightOffsetModifierShift",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRotationOffsetIncr",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRotationOffsetDecr",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRotationOffsetModifierAlt",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRotationOffsetModifierCtrl",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRotationOffsetModifierShift",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRadiusIncr",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRadiusDecr",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRadiusModifierAlt",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRadiusModifierCtrl",void 0),Object(c.c)([Object(L.c)()],r.prototype,"keysRadiusModifierShift",void 0),Object(c.c)([Object(L.c)()],r.prototype,"heightSensibility",void 0),Object(c.c)([Object(L.c)()],r.prototype,"rotationSensibility",void 0),Object(c.c)([Object(L.c)()],r.prototype,"radiusSensibility",void 0),r}();un.FollowCameraKeyboardMoveInput=ts;var ns=function(){function r(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}return r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(n,i){if(n.type===Tt.a.POINTERWHEEL){var o=n.event,a=0,s=Math.max(-1,Math.min(1,o.deltaY||o.wheelDelta||-o.detail));e.wheelDeltaPercentage?(console.assert(e.axisControlRadius+e.axisControlHeight+e.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controlls ONE axis. Currently enabled: axisControlRadius: "+e.axisControlRadius+", axisControlHeightOffset: "+e.axisControlHeight+", axisControlRotationOffset: "+e.axisControlRotation),e.axisControlRadius?a=.01*s*e.wheelDeltaPercentage*e.camera.radius:e.axisControlHeight?a=.01*s*e.wheelDeltaPercentage*e.camera.heightOffset:e.axisControlRotation&&(a=.01*s*e.wheelDeltaPercentage*e.camera.rotationOffset)):a=s*e.wheelPrecision,a&&(e.axisControlRadius?e.camera.radius+=a:e.axisControlHeight?e.camera.heightOffset-=a:e.axisControlRotation&&(e.camera.rotationOffset-=a)),o.preventDefault&&(t||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,Tt.a.POINTERWHEEL)},r.prototype.detachControl=function(t){this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},r.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},r.prototype.getSimpleName=function(){return"mousewheel"},Object(c.c)([Object(L.c)()],r.prototype,"axisControlRadius",void 0),Object(c.c)([Object(L.c)()],r.prototype,"axisControlHeight",void 0),Object(c.c)([Object(L.c)()],r.prototype,"axisControlRotation",void 0),Object(c.c)([Object(L.c)()],r.prototype,"wheelPrecision",void 0),Object(c.c)([Object(L.c)()],r.prototype,"wheelDeltaPercentage",void 0),r}();un.FollowCameraMouseWheelInput=ns;var is=function(r){function t(){var e=r!==null&&r.apply(this,arguments)||this;return e.angularSensibilityX=1,e.angularSensibilityY=1,e.pinchPrecision=1e4,e.pinchDeltaPercentage=0,e.axisXControlRadius=!1,e.axisXControlHeight=!1,e.axisXControlRotation=!0,e.axisYControlRadius=!1,e.axisYControlHeight=!0,e.axisYControlRotation=!1,e.axisPinchControlRadius=!0,e.axisPinchControlHeight=!1,e.axisPinchControlRotation=!1,e.warningEnable=!0,e._warningCounter=0,e}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"FollowCameraPointersInput"},t.prototype.onTouch=function(e,n,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=n/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=n/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=n/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)},t.prototype.onMultiTouch=function(e,n,i,o,a,s){if(!(i===0&&a===null||o===0&&s===null)){var d=(o-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(d*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=d*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=d*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=d*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=d),this.axisPinchControlHeight&&(this.camera.heightOffset+=d),this.axisPinchControlRadius&&(this.camera.radius-=d))}},t.prototype._warning=function(){if(this.warningEnable&&this._warningCounter++%100==0){var 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)}},Object(c.c)([Object(L.c)()],t.prototype,"angularSensibilityX",void 0),Object(c.c)([Object(L.c)()],t.prototype,"angularSensibilityY",void 0),Object(c.c)([Object(L.c)()],t.prototype,"pinchPrecision",void 0),Object(c.c)([Object(L.c)()],t.prototype,"pinchDeltaPercentage",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisXControlRadius",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisXControlHeight",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisXControlRotation",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisYControlRadius",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisYControlHeight",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisYControlRotation",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisPinchControlRadius",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisPinchControlHeight",void 0),Object(c.c)([Object(L.c)()],t.prototype,"axisPinchControlRotation",void 0),t}(Ml);un.FollowCameraPointersInput=is;var rs=function(){function r(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this._keys=new Array}return r.prototype.attachControl=function(t){var e=this;t=Ye.b.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){e._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(n){var i,o=n.event;o.metaKey||(n.type===qi.a.KEYDOWN?e.keysUp.indexOf(o.keyCode)===-1&&e.keysDown.indexOf(o.keyCode)===-1&&e.keysLeft.indexOf(o.keyCode)===-1&&e.keysRight.indexOf(o.keyCode)===-1&&e.keysUpward.indexOf(o.keyCode)===-1&&e.keysDownward.indexOf(o.keyCode)===-1||((i=e._keys.indexOf(o.keyCode))===-1&&e._keys.push(o.keyCode),t||o.preventDefault()):e.keysUp.indexOf(o.keyCode)===-1&&e.keysDown.indexOf(o.keyCode)===-1&&e.keysLeft.indexOf(o.keyCode)===-1&&e.keysRight.indexOf(o.keyCode)===-1&&e.keysUpward.indexOf(o.keyCode)===-1&&e.keysDownward.indexOf(o.keyCode)===-1||((i=e._keys.indexOf(o.keyCode))>=0&&e._keys.splice(i,1),t||o.preventDefault()))}))},r.prototype.detachControl=function(t){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=[]},r.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var t=this.camera,e=0;e1)t.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{var e=t._computeLocalCameraSpeed(),n=new u.e(0,0,e*this._offsetY/this.touchMoveSensibility);u.a.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(u.e.TransformCoordinates(n,t._cameraRotationMatrix))}}},r.prototype.getClassName=function(){return"FreeCameraTouchInput"},r.prototype.getSimpleName=function(){return"touch"},Object(c.c)([Object(L.c)()],r.prototype,"touchAngularSensibility",void 0),Object(c.c)([Object(L.c)()],r.prototype,"touchMoveSensibility",void 0),r}();un.FreeCameraTouchInput=ss;var $r=function(r){function t(e){var n=r.call(this,e)||this;return n._mouseInput=null,n._mouseWheelInput=null,n}return Object(c.d)(t,r),t.prototype.addKeyboard=function(){return this.add(new rs),this},t.prototype.addMouse=function(e){return e===void 0&&(e=!0),this._mouseInput||(this._mouseInput=new os(e),this.add(this._mouseInput)),this},t.prototype.removeMouse=function(){return this._mouseInput&&this.remove(this._mouseInput),this},t.prototype.addMouseWheel=function(){return this._mouseWheelInput||(this._mouseWheelInput=new as,this.add(this._mouseWheelInput)),this},t.prototype.removeMouseWheel=function(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this},t.prototype.addTouch=function(){return this.add(new ss),this},t.prototype.clear=function(){r.prototype.clear.call(this),this._mouseInput=null},t}(Jr);$r.prototype.addDeviceOrientation=function(){return this._deviceOrientationInput||(this._deviceOrientationInput=new cs,this.add(this._deviceOrientationInput)),this};var cs=function(){function r(){var t=this;this._screenOrientationAngle=0,this._screenQuaternion=new u.b,this._alpha=0,this._beta=0,this._gamma=0,this._onDeviceOrientationChangedObservable=new x.c,this._orientationChanged=function(){t._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,t._screenOrientationAngle=-Ye.b.ToRadians(t._screenOrientationAngle/2),t._screenQuaternion.copyFromFloats(0,Math.sin(t._screenOrientationAngle),0,Math.cos(t._screenOrientationAngle))},this._deviceOrientation=function(e){t._alpha=e.alpha!==null?e.alpha:0,t._beta=e.beta!==null?e.beta:0,t._gamma=e.gamma!==null?e.gamma:0,e.alpha!==null&&t._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new u.b(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}return r.WaitForOrientationChangeAsync=function(t){return new Promise(function(e,n){var i=!1,o=function(){window.removeEventListener("deviceorientation",o),i=!0,e()};t&&setTimeout(function(){i||(window.removeEventListener("deviceorientation",o),n("WaitForOrientationChangeAsync timed out"))},t),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(function(a){a=="granted"?window.addEventListener("deviceorientation",o):Ye.b.Warn("Permission not granted.")}).catch(function(a){Ye.b.Error(a)}):window.addEventListener("deviceorientation",o)})},Object.defineProperty(r.prototype,"camera",{get:function(){return this._camera},set:function(t){var e=this;this._camera=t,this._camera==null||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new u.b),this._camera&&this._camera.onDisposeObservable.add(function(){e._onDeviceOrientationChangedObservable.clear()})},enumerable:!1,configurable:!0}),r.prototype.attachControl=function(){var t=this,e=this.camera.getScene().getEngine().getHostWindow();if(e){var n=function(){e.addEventListener("orientationchange",t._orientationChanged),e.addEventListener("deviceorientation",t._deviceOrientation),t._orientationChanged()};typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(function(i){i==="granted"?n():Ye.b.Warn("Permission not granted.")}).catch(function(i){Ye.b.Error(i)}):n()}},r.prototype.detachControl=function(t){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0},r.prototype.checkInputs=function(){this._alpha&&(u.b.RotationYawPitchRollToRef(Ye.b.ToRadians(this._alpha),Ye.b.ToRadians(this._beta),-Ye.b.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)},r.prototype.getClassName=function(){return"FreeCameraDeviceOrientationInput"},r.prototype.getSimpleName=function(){return"deviceOrientation"},r}();un.FreeCameraDeviceOrientationInput=cs;var ls=function(){function r(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this._yAxisScale=1,this._cameraTransform=u.a.Identity(),this._deltaTransform=u.e.Zero(),this._vector3=u.e.Zero(),this._vector2=u.d.Zero()}return Object.defineProperty(r.prototype,"invertYAxis",{get:function(){return this._yAxisScale!==1},set:function(t){this._yAxisScale=t?-1:1},enumerable:!1,configurable:!0}),r.prototype.attachControl=function(){var t=this,e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(function(n){n.type!==hn.POSE_ENABLED&&(t.gamepad&&n.type!==hn.XBOX||(t.gamepad=n))}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(function(n){t.gamepad===n&&(t.gamepad=null)}),this.gamepad=e.getGamepadByType(hn.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])},r.prototype.detachControl=function(t){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},r.prototype.checkInputs=function(){if(this.gamepad&&this.gamepad.leftStick){var t=this.camera,e=this.gamepad.leftStick,n=e.x/this.gamepadMoveSensibility,i=e.y/this.gamepadMoveSensibility;e.x=Math.abs(n)>.005?0+n:0,e.y=Math.abs(i)>.005?0+i:0;var o=this.gamepad.rightStick;if(o){var a=o.x/this.gamepadAngularSensibility,s=o.y/this.gamepadAngularSensibility*this._yAxisScale;o.x=Math.abs(a)>.001?0+a:0,o.y=Math.abs(s)>.001?0+s:0}else o={x:0,y:0};t.rotationQuaternion?t.rotationQuaternion.toRotationMatrix(this._cameraTransform):u.a.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,this._cameraTransform);var d=50*t._computeLocalCameraSpeed();this._vector3.copyFromFloats(e.x*d,0,-e.y*d),u.e.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),t.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(o.y,o.x),t.cameraRotation.addInPlace(this._vector2)}},r.prototype.getClassName=function(){return"FreeCameraGamepadInput"},r.prototype.getSimpleName=function(){return"gamepad"},Object(c.c)([Object(L.c)()],r.prototype,"gamepadAngularSensibility",void 0),Object(c.c)([Object(L.c)()],r.prototype,"gamepadMoveSensibility",void 0),r}();un.FreeCameraGamepadInput=ls;var an,Il=f(112);(function(r){r[r.X=0]="X",r[r.Y=1]="Y",r[r.Z=2]="Z"})(an||(an={}));var us=function(){function r(t,e){var n=this,i=Object(c.a)(Object(c.a)({},r._GetDefaultOptions()),e);if(this._leftJoystick=!!t,r._globalJoystickIndex++,this._axisTargetedByLeftAndRight=an.X,this._axisTargetedByUpAndDown=an.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Il.a,this.deltaPosition=u.e.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=function(a){r.vjCanvasWidth=window.innerWidth,r.vjCanvasHeight=window.innerHeight,r.Canvas&&(r.Canvas.width=r.vjCanvasWidth,r.Canvas.height=r.vjCanvasHeight),r.halfWidth=r.vjCanvasWidth/2},!r.Canvas){window.addEventListener("resize",this._onResize,!1),r.Canvas=document.createElement("canvas"),r.vjCanvasWidth=window.innerWidth,r.vjCanvasHeight=window.innerHeight,r.Canvas.width=window.innerWidth,r.Canvas.height=window.innerHeight,r.Canvas.style.width="100%",r.Canvas.style.height="100%",r.Canvas.style.position="absolute",r.Canvas.style.backgroundColor="transparent",r.Canvas.style.top="0px",r.Canvas.style.left="0px",r.Canvas.style.zIndex="5",r.Canvas.style.msTouchAction="none",r.Canvas.style.touchAction="none",r.Canvas.setAttribute("touch-action","none");var o=r.Canvas.getContext("2d");if(!o)throw new Error("Unable to create canvas for virtual joystick");r.vjCanvasContext=o,r.vjCanvasContext.strokeStyle="#ffffff",r.vjCanvasContext.lineWidth=2,document.body.appendChild(r.Canvas)}r.halfWidth=r.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&&r._alwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerID=-1,this._joystickPointerPos=new u.d(0,0),this._joystickPreviousPointerPos=new u.d(0,0),this._joystickPointerStartPos=new u.d(0,0),this._deltaJoystickVector=new u.d(0,0),this._onPointerDownHandlerRef=function(a){n._onPointerDown(a)},this._onPointerMoveHandlerRef=function(a){n._onPointerMove(a)},this._onPointerUpHandlerRef=function(a){n._onPointerUp(a)},r.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),r.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),r.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),r.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),r.Canvas.addEventListener("contextmenu",function(a){a.preventDefault()},!1),requestAnimationFrame(function(){n._drawVirtualJoystick()})}return r._GetDefaultOptions=function(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}},r.prototype.setJoystickSensibility=function(t){this._joystickSensibility=t,this._inversedSensibility=1/(this._joystickSensibility/1e3)},r.prototype._onPointerDown=function(t){t.preventDefault(),(this._leftJoystick===!0?t.clientXr.halfWidth)&&this._joystickPointerID<0?(this._joystickPointerID=t.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(t)):(this._joystickPointerStartPos.x=t.clientX,this._joystickPointerStartPos.y=t.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(t.pointerId.toString(),t)):r._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(t.pointerId.toString(),{x:t.clientX,y:t.clientY,prevX:t.clientX,prevY:t.clientY}))},r.prototype._onPointerMove=function(t){if(this._joystickPointerID==t.pointerId){if(this.limitToContainer){var e=new u.d(t.clientX-this._joystickPointerStartPos.x,t.clientY-this._joystickPointerStartPos.y),n=e.length();n>this.containerSize&&e.scaleInPlace(this.containerSize/n),this._joystickPointerPos.x=this._joystickPointerStartPos.x+e.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+e.y}else this._joystickPointerPos.x=t.clientX,this._joystickPointerPos.y=t.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0=0?this.rotation.y=-Math.atan(n.z/n.x)+Math.PI/2:this.rotation.y=-Math.atan(n.z/n.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&&u.b.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},Object.defineProperty(t.prototype,"target",{get:function(){return this.getTarget()},set:function(e){this.setTarget(e)},enumerable:!1,configurable:!0}),t.prototype.getTarget=function(){return this._currentTarget},t.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(u.c.Matrix[0]),u.e.TransformNormalToRef(this.cameraDirection,u.c.Matrix[0],u.c.Vector3[0]),void this.position.addInPlace(u.c.Vector3[0]);this.position.addInPlace(this.cameraDirection)},t.prototype._checkInputs=function(){var e=this.invertRotation?-this.inverseRotationSpeed:1,n=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;n&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this.rotation.x>1.570796&&(this.rotation.x=1.570796),this.rotation.x<-1.570796&&(this.rotation.x=-1.570796)),this.rotationQuaternion&&this.rotation.lengthSquared()&&u.b.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)),n&&(Math.abs(this.cameraDirection.x)Ue.a.CollisionsEpsilon&&(a.position.addInPlace(a._diffPosition),a.onCollide&&p&&a.onCollide(p))},a.inputs=new $r(a),a.inputs.addKeyboard().addMouse(),a}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var n=this.inputs.attached.mouse;n&&(n.angularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUpward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUpward:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysUpward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDownward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDownward:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysDownward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysRight=e)},enumerable:!1,configurable:!0}),t.prototype.attachControl=function(e,n){n=Ye.b.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(n)},t.prototype.detachControl=function(e){this.inputs.detachElement(),this.cameraDirection=new u.e(0,0,0),this.cameraRotation=new u.d(0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?u.e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var n=this.getScene().collisionCoordinator;this._collider||(this._collider=n.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),n.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=u.e.Zero(),this._transformedDirection=u.e.Zero()),this.inputs.checkInputs(),r.prototype._checkInputs.call(this)},t.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):r.prototype._updatePosition.call(this)},t.prototype.dispose=function(){this.inputs.clear(),r.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FreeCamera"},Object(c.c)([Object(L.o)()],t.prototype,"ellipsoid",void 0),Object(c.c)([Object(L.o)()],t.prototype,"ellipsoidOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"checkCollisions",void 0),Object(c.c)([Object(L.c)()],t.prototype,"applyGravity",void 0),t}(Ii);Q.a.AddNodeConstructor("TouchCamera",function(r,t){return function(){return new ds(r,u.e.Zero(),t)}});var ds=function(r){function t(e,n,i){var o=r.call(this,e,n,i)||this;return o.inputs.addTouch(),o._setupInputs(),o}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var n=this.inputs.attached.touch;n&&(n.touchAngularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var n=this.inputs.attached.touch;n&&(n.touchMoveSensibility=e)},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.touch,n=this.inputs.attached.mouse;n?n.touchEnabled=!1:e.allowMouse=!0},t}(Hn);Q.a.AddNodeConstructor("ArcRotateCamera",function(r,t){return function(){return new Zi(r,0,0,1,u.e.Zero(),t)}});var Zi=function(r){function t(e,n,i,o,a,s,d){d===void 0&&(d=!0);var p=r.call(this,e,u.e.Zero(),s,d)||this;return p.inertialAlphaOffset=0,p.inertialBetaOffset=0,p.inertialRadiusOffset=0,p.lowerAlphaLimit=null,p.upperAlphaLimit=null,p.lowerBetaLimit=.01,p.upperBetaLimit=Math.PI-.01,p.lowerRadiusLimit=null,p.upperRadiusLimit=null,p.inertialPanningX=0,p.inertialPanningY=0,p.pinchToPanMaxDistance=20,p.panningDistanceLimit=null,p.panningOriginTarget=u.e.Zero(),p.panningInertia=.9,p.zoomOnFactor=1,p.targetScreenOffset=u.d.Zero(),p.allowUpsideDown=!0,p.useInputToRestoreState=!0,p._viewMatrix=new u.a,p.panningAxis=new u.e(1,1,0),p.onMeshTargetChangedObservable=new x.c,p.checkCollisions=!1,p.collisionRadius=new u.e(.5,.5,.5),p._previousPosition=u.e.Zero(),p._collisionVelocity=u.e.Zero(),p._newPosition=u.e.Zero(),p._computationVector=u.e.Zero(),p._onCollisionPositionChange=function(y,P,O){O===void 0&&(O=null),O?(p.setPosition(P),p.onCollide&&p.onCollide(O)):p._previousPosition.copyFrom(p._position);var U=Math.cos(p.alpha),F=Math.sin(p.alpha),z=Math.cos(p.beta),J=Math.sin(p.beta);J===0&&(J=1e-4);var ie=p._getTargetPosition();p._computationVector.copyFromFloats(p.radius*U*J,p.radius*z,p.radius*F*J),ie.addToRef(p._computationVector,p._newPosition),p._position.copyFrom(p._newPosition);var se=p.upVector;p.allowUpsideDown&&p.beta<0&&(se=(se=se.clone()).negate()),p._computeViewMatrix(p._position,ie,se),p._viewMatrix.addAtIndex(12,p.targetScreenOffset.x),p._viewMatrix.addAtIndex(13,p.targetScreenOffset.y),p._collisionTriggered=!1},p._target=u.e.Zero(),a&&p.setTarget(a),p.alpha=n,p.beta=i,p.radius=o,p.getViewMatrix(),p.inputs=new Uo(p),p.inputs.addKeyboard().addMouseWheel().addPointers(),p}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this.setPosition(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upToYMatrix||(this._YToUpMatrix=new u.a,this._upToYMatrix=new u.a,this._upVector=u.e.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()},enumerable:!1,configurable:!0}),t.prototype.setMatUp=function(){u.a.RotationAlignToRef(u.e.UpReadOnly,this._upVector,this._YToUpMatrix),u.a.RotationAlignToRef(this._upVector,u.e.UpReadOnly,this._upToYMatrix)},Object.defineProperty(t.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var n=this.inputs.attached.pointers;n&&(n.angularSensibilityX=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var n=this.inputs.attached.pointers;n&&(n.angularSensibilityY=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var n=this.inputs.attached.pointers;n&&(n.pinchPrecision=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var n=this.inputs.attached.pointers;n&&(n.pinchDeltaPercentage=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useNaturalPinchZoom",{get:function(){var e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom},set:function(e){var n=this.inputs.attached.pointers;n&&(n.useNaturalPinchZoom=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var n=this.inputs.attached.pointers;n&&(n.panningSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysRight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var n=this.inputs.attached.mousewheel;n&&(n.wheelPrecision=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var n=this.inputs.attached.mousewheel;n&&(n.wheelDeltaPercentage=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useBouncingBehavior",{get:function(){return this._bouncingBehavior!=null},set:function(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Sl,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useFramingBehavior",{get:function(){return this._framingBehavior!=null},set:function(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Al,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useAutoRotationBehavior",{get:function(){return this._autoRotationBehavior!=null},set:function(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new El,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!1,configurable:!0}),t.prototype._initCache=function(){r.prototype._initCache.call(this),this._cache._target=new u.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=u.d.Zero()},t.prototype._updateCache=function(e){e||r.prototype._updateCache.call(this),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)},t.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.absolutePosition;this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}var n=this._getLockedTargetPosition();return n||this._target},t.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),r.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!r.prototype._restoreStateValues.call(this)&&(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)},t.prototype._isSynchronizedViewMatrix=function(){return!!r.prototype._isSynchronizedViewMatrix.call(this)&&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)},t.prototype.attachControl=function(e,n,i,o){var a=this;i===void 0&&(i=!0),o===void 0&&(o=2),n=Ye.b.BackCompatCameraNoPreventDefault(arguments),this._useCtrlForPanning=i,this._panningMouseButton=o,typeof arguments[0]=="boolean"&&(arguments.length>1&&(this._useCtrlForPanning=arguments[1]),arguments.length>2&&(this._panningMouseButton=arguments[2])),this.inputs.attachElement(n),this._reset=function(){a.inertialAlphaOffset=0,a.inertialBetaOffset=0,a.inertialRadiusOffset=0,a.inertialPanningX=0,a.inertialPanningY=0}},t.prototype.detachControl=function(e){this.inputs.detachElement(),this._reset&&this._reset()},t.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){var e=this.inertialAlphaOffset;this.beta<=0&&(e*=-1),this.getScene().useRightHandedSystem&&(e*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),this.alpha+=e,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)},t.prototype.rebuildAnglesAndRadius=function(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),this._upVector.x===0&&this._upVector.y===1&&this._upVector.z===0||u.e.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);var e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);var n=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*n*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},t.prototype.setPosition=function(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())},t.prototype.setTarget=function(e,n,i){if(n===void 0&&(n=!1),i===void 0&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=n?e.getBoundingInfo().boundingBox.centerWorld.clone():null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var o=e,a=this._getTargetPosition();if(a&&!i&&a.equals(o))return;this._targetHost=null,this._target=o,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},t.prototype._getViewMatrix=function(){var e=Math.cos(this.alpha),n=Math.sin(this.alpha),i=Math.cos(this.beta),o=Math.sin(this.beta);o===0&&(o=1e-4),this.radius===0&&(this.radius=1e-4);var a=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*o,this.radius*i,this.radius*n*o),this._upVector.x===0&&this._upVector.y===1&&this._upVector.z===0||u.e.TransformCoordinatesToRef(this._computationVector,this._YToUpMatrix,this._computationVector),a.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){var s=this.getScene().collisionCoordinator;this._collider||(this._collider=s.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,s.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);var d=this.upVector;this.allowUpsideDown&&o<0&&(d=d.negate()),this._computeViewMatrix(this._position,a,d),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=a,this._viewMatrix},t.prototype.zoomOn=function(e,n){n===void 0&&(n=!1),e=e||this.getScene().meshes;var i=De.a.MinMax(e),o=u.e.Distance(i.min,i.max);this.radius=o*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:o},n)},t.prototype.focusOn=function(e,n){var i,o;if(n===void 0&&(n=!1),e.min===void 0){var a=e||this.getScene().meshes;i=De.a.MinMax(a),o=u.e.Distance(i.min,i.max)}else i=e,o=e.distance;this._target=De.a.Center(i),n||(this.maxZ=2*o)},t.prototype.createRigCamera=function(e,n){var i=0;switch(this.cameraRigMode){case gt.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case gt.a.RIG_MODE_STEREOSCOPIC_INTERLACED:case gt.a.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(n===0?1:-1);break;case gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(n===0?-1:1)}var o=new t(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return o._cameraRigParams={},o.isRigCamera=!0,o.rigParent=this,o.upVector=this.upVector,o},t.prototype._updateRigCameras=function(){var e=this._rigCameras[0],n=this._rigCameras[1];switch(e.beta=n.beta=this.beta,this.cameraRigMode){case gt.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case gt.a.RIG_MODE_STEREOSCOPIC_INTERLACED:case gt.a.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,n.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,n.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}r.prototype._updateRigCameras.call(this)},t.prototype.dispose=function(){this.inputs.clear(),r.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"ArcRotateCamera"},Object(c.c)([Object(L.c)()],t.prototype,"alpha",void 0),Object(c.c)([Object(L.c)()],t.prototype,"beta",void 0),Object(c.c)([Object(L.c)()],t.prototype,"radius",void 0),Object(c.c)([Object(L.o)("target")],t.prototype,"_target",void 0),Object(c.c)([Object(L.c)()],t.prototype,"inertialAlphaOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"inertialBetaOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"inertialRadiusOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"lowerAlphaLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"upperAlphaLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"lowerBetaLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"upperBetaLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"lowerRadiusLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"upperRadiusLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"inertialPanningX",void 0),Object(c.c)([Object(L.c)()],t.prototype,"inertialPanningY",void 0),Object(c.c)([Object(L.c)()],t.prototype,"pinchToPanMaxDistance",void 0),Object(c.c)([Object(L.c)()],t.prototype,"panningDistanceLimit",void 0),Object(c.c)([Object(L.o)()],t.prototype,"panningOriginTarget",void 0),Object(c.c)([Object(L.c)()],t.prototype,"panningInertia",void 0),Object(c.c)([Object(L.c)()],t.prototype,"zoomOnFactor",void 0),Object(c.c)([Object(L.c)()],t.prototype,"targetScreenOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"allowUpsideDown",void 0),Object(c.c)([Object(L.c)()],t.prototype,"useInputToRestoreState",void 0),t}(Ii);Q.a.AddNodeConstructor("DeviceOrientationCamera",function(r,t){return function(){return new Vo(r,u.e.Zero(),t)}});var Vo=function(r){function t(e,n,i){var o=r.call(this,e,n,i)||this;return o._tmpDragQuaternion=new u.b,o._disablePointerInputWhenUsingDeviceOrientation=!0,o._dragFactor=0,o._quaternionCache=new u.b,o.inputs.addDeviceOrientation(),o.inputs._deviceOrientationInput&&o.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function(){o._disablePointerInputWhenUsingDeviceOrientation&&o.inputs._mouseInput&&(o.inputs._mouseInput._allowCameraRotation=!1,o.inputs._mouseInput.onPointerMovedObservable.add(function(a){o._dragFactor!=0&&(o._initialQuaternion||(o._initialQuaternion=new u.b),u.b.FromEulerAnglesToRef(0,a.offsetX*o._dragFactor,0,o._tmpDragQuaternion),o._initialQuaternion.multiplyToRef(o._tmpDragQuaternion,o._initialQuaternion))}))}),o}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"disablePointerInputWhenUsingDeviceOrientation",{get:function(){return this._disablePointerInputWhenUsingDeviceOrientation},set:function(e){this._disablePointerInputWhenUsingDeviceOrientation=e},enumerable:!1,configurable:!0}),t.prototype.enableHorizontalDragging=function(e){e===void 0&&(e=1/300),this._dragFactor=e},t.prototype.getClassName=function(){return"DeviceOrientationCamera"},t.prototype._checkInputs=function(){r.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},t.prototype.resetToCurrentRotation=function(e){var n=this;e===void 0&&(e=ye.a.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new u.b),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(function(i){e[i]?n._initialQuaternion[i]*=-1:n._initialQuaternion[i]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},t}(Hn),Dl=function(r){function t(e){return r.call(this,e)||this}return Object(c.d)(t,r),t.prototype.addKeyboard=function(){return this.add(new $a),this},t.prototype.addMouse=function(e){return e===void 0&&(e=!0),this.add(new es(e)),this},t}(Jr),sp=function(r){function t(e,n,i,o){o===void 0&&(o=!0);var a=r.call(this,e,n,i,o)||this;return a.ellipsoid=new u.e(1,1,1),a.ellipsoidOffset=new u.e(0,0,0),a.checkCollisions=!1,a.applyGravity=!1,a.cameraDirection=u.e.Zero(),a._trackRoll=0,a.rollCorrect=100,a.bankedTurn=!1,a.bankedTurnLimit=Math.PI/2,a.bankedTurnMultiplier=1,a._needMoveForGravity=!1,a._oldPosition=u.e.Zero(),a._diffPosition=u.e.Zero(),a._newPosition=u.e.Zero(),a._collisionMask=-1,a._onCollisionPositionChange=function(s,d,p){p===void 0&&(p=null);var y;y=d,a._newPosition.copyFrom(y),a._newPosition.subtractToRef(a._oldPosition,a._diffPosition),a._diffPosition.length()>Ue.a.CollisionsEpsilon&&(a.position.addInPlace(a._diffPosition),a.onCollide&&p&&a.onCollide(p))},a.inputs=new Dl(a),a.inputs.addKeyboard().addMouse(),a}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var n=this.inputs.attached.mouse;n&&(n.angularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysForward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysForward:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysForward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysBackward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysBackward:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysBackward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var n=this.inputs.attached.keyboard;n&&(n.keysRight=e)},enumerable:!1,configurable:!0}),t.prototype.attachControl=function(e,n){n=Ye.b.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(n)},t.prototype.detachControl=function(){this.inputs.detachElement(),this.cameraDirection=new u.e(0,0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?u.e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var n=this.getScene().collisionCoordinator;this._collider||(this._collider=n.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),n.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=u.e.Zero(),this._transformedDirection=u.e.Zero()),this.inputs.checkInputs(),r.prototype._checkInputs.call(this)},t.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):r.prototype._updatePosition.call(this)},t.prototype.restoreRoll=function(e){var n=this._trackRoll,i=n-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(n-this.rotation.z)<=.001&&(this.rotation.z=n))},t.prototype.dispose=function(){this.inputs.clear(),r.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FlyCamera"},Object(c.c)([Object(L.o)()],t.prototype,"ellipsoid",void 0),Object(c.c)([Object(L.o)()],t.prototype,"ellipsoidOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"checkCollisions",void 0),Object(c.c)([Object(L.c)()],t.prototype,"applyGravity",void 0),t}(Ii),Ll=function(r){function t(e){return r.call(this,e)||this}return Object(c.d)(t,r),t.prototype.addKeyboard=function(){return this.add(new ts),this},t.prototype.addMouseWheel=function(){return this.add(new ns),this},t.prototype.addPointers=function(){return this.add(new is),this},t.prototype.addVRDeviceOrientation=function(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this},t}(Jr);Q.a.AddNodeConstructor("FollowCamera",function(r,t){return function(){return new Nl(r,u.e.Zero(),t)}}),Q.a.AddNodeConstructor("ArcFollowCamera",function(r,t){return function(){return new wl(r,0,0,1,null,t)}});var ei,Nl=function(r){function t(e,n,i,o){o===void 0&&(o=null);var a=r.call(this,e,n,i)||this;return a.radius=12,a.lowerRadiusLimit=null,a.upperRadiusLimit=null,a.rotationOffset=0,a.lowerRotationOffsetLimit=null,a.upperRotationOffsetLimit=null,a.heightOffset=4,a.lowerHeightOffsetLimit=null,a.upperHeightOffsetLimit=null,a.cameraAcceleration=.05,a.maxCameraSpeed=20,a.lockedTarget=o,a.inputs=new Ll(a),a.inputs.addKeyboard().addMouseWheel().addPointers(),a}return Object(c.d)(t,r),t.prototype._follow=function(e){if(e){var n;if(e.rotationQuaternion){var i=new u.a;e.rotationQuaternion.toRotationMatrix(i),n=Math.atan2(i.m[8],i.m[10])}else n=e.rotation.y;var o=Ye.b.ToRadians(this.rotationOffset)+n,a=e.getAbsolutePosition(),s=a.x+Math.sin(o)*this.radius,d=a.z+Math.cos(o)*this.radius,p=s-this.position.x,y=a.y+this.heightOffset-this.position.y,P=d-this.position.z,O=p*this.cameraAcceleration*2,U=y*this.cameraAcceleration,F=P*this.cameraAcceleration*2;(O>this.maxCameraSpeed||O<-this.maxCameraSpeed)&&(O=O<1?-this.maxCameraSpeed:this.maxCameraSpeed),(U>this.maxCameraSpeed||U<-this.maxCameraSpeed)&&(U=U<1?-this.maxCameraSpeed:this.maxCameraSpeed),(F>this.maxCameraSpeed||F<-this.maxCameraSpeed)&&(F=F<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new u.e(this.position.x+O,this.position.y+U,this.position.z+F),this.setTarget(a)}},t.prototype.attachControl=function(e,n){n=Ye.b.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(n),this._reset=function(){}},t.prototype.detachControl=function(e){this.inputs.detachElement(),this._reset&&this._reset()},t.prototype._checkInputs=function(){this.inputs.checkInputs(),this._checkLimits(),r.prototype._checkInputs.call(this),this.lockedTarget&&this._follow(this.lockedTarget)},t.prototype._checkLimits=function(){this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),this.lowerHeightOffsetLimit!==null&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),this.lowerRotationOffsetLimit!==null&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)},t.prototype.getClassName=function(){return"FollowCamera"},Object(c.c)([Object(L.c)()],t.prototype,"radius",void 0),Object(c.c)([Object(L.c)()],t.prototype,"lowerRadiusLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"upperRadiusLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"rotationOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"lowerRotationOffsetLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"upperRotationOffsetLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"heightOffset",void 0),Object(c.c)([Object(L.c)()],t.prototype,"lowerHeightOffsetLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"upperHeightOffsetLimit",void 0),Object(c.c)([Object(L.c)()],t.prototype,"cameraAcceleration",void 0),Object(c.c)([Object(L.c)()],t.prototype,"maxCameraSpeed",void 0),Object(c.c)([Object(L.k)("lockedTargetId")],t.prototype,"lockedTarget",void 0),t}(Ii),wl=function(r){function t(e,n,i,o,a,s){var d=r.call(this,e,u.e.Zero(),s)||this;return d.alpha=n,d.beta=i,d.radius=o,d._cartesianCoordinates=u.e.Zero(),d._meshTarget=a,d._follow(),d}return Object(c.d)(t,r),t.prototype._follow=function(){if(this._meshTarget){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);var e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},t.prototype._checkInputs=function(){r.prototype._checkInputs.call(this),this._follow()},t.prototype.getClassName=function(){return"ArcFollowCamera"},t}(Ii),fs=f(38),dn=f(39);(function(r){r[r.VIVE=0]="VIVE",r[r.OCULUS=1]="OCULUS",r[r.WINDOWS=2]="WINDOWS",r[r.GEAR_VR=3]="GEAR_VR",r[r.DAYDREAM=4]="DAYDREAM",r[r.GENERIC=5]="GENERIC"})(ei||(ei={}));var Cn,Ji,Di=function(){function r(){}return r.InitiateController=function(t){for(var e=0,n=this._ControllerFactories;ethis._maxRotationDistFromHeadset){var o=i-(i<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=o;var a=Math.sin(-o),s=Math.cos(-o);this._calculatedPosition.x=this._calculatedPosition.x*s-this._calculatedPosition.z*a,this._calculatedPosition.z=this._calculatedPosition.x*a+this._calculatedPosition.z*s}}u.e.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),u.b.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))}},t.prototype.updateFromDevice=function(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));var n=this.rawPose;e.orientation&&n.orientation&&n.orientation.length===4&&(this._deviceRoomRotationQuaternion.copyFromFloats(n.orientation[0],n.orientation[1],-n.orientation[2],-n.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))}},t.prototype.attachToMesh=function(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 u.b),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){for(var n=[],i=this._pointingPoseNode;i.parent;)n.push(i.parent),i=i.parent;n.reverse().forEach(function(o){o.computeWorldMatrix(!0)})}this._meshAttachedObservable.notifyObservers(e)},t.prototype.attachToPoseControlledCamera=function(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)},t.prototype.dispose=function(){this._mesh&&this._mesh.dispose(),this._mesh=null,r.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},enumerable:!1,configurable:!0}),t.prototype.getForwardRay=function(e){if(e===void 0&&(e=100),!this.mesh)return new dn.a(u.e.Zero(),new u.e(0,0,1),e);var n=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=n.getTranslation(),o=new u.e(0,0,-1),a=u.e.TransformNormal(o,n),s=u.e.Normalize(a);return new dn.a(i,s,e)},t.POINTING_POSE="POINTING_POSE",t}(hn);(function(r){r[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"})(Cn||(Cn={})),function(r){r[r.Up=12]="Up",r[r.Down=13]="Down",r[r.Left=14]="Left",r[r.Right=15]="Right"}(Ji||(Ji={}));var Gn,$i,Fl=function(r){function t(e,n,i,o){o===void 0&&(o=!1);var a=r.call(this,e,n,i,0,1,2,3)||this;return a._leftTrigger=0,a._rightTrigger=0,a.onButtonDownObservable=new x.c,a.onButtonUpObservable=new x.c,a.onPadDownObservable=new x.c,a.onPadUpObservable=new x.c,a._buttonA=0,a._buttonB=0,a._buttonX=0,a._buttonY=0,a._buttonBack=0,a._buttonStart=0,a._buttonLB=0,a._buttonRB=0,a._buttonLeftStick=0,a._buttonRightStick=0,a._dPadUp=0,a._dPadDown=0,a._dPadLeft=0,a._dPadRight=0,a._isXboxOnePad=!1,a.type=hn.XBOX,a._isXboxOnePad=o,a}return Object(c.d)(t,r),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!1,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,n,i){return e!==n&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,n,i){return e!==n&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,Cn.A)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,Cn.B)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,Cn.X)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,Cn.Y)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Cn.Start)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Cn.Back)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Cn.LB)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Cn.RB)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Cn.LeftStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Cn.RightStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Ji.Up)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Ji.Down)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Ji.Left)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Ji.Right)},enumerable:!1,configurable:!0}),t.prototype.update=function(){r.prototype.update.call(this),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},t.prototype.dispose=function(){r.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(hn);(function(r){r[r.Cross=0]="Cross",r[r.Circle=1]="Circle",r[r.Square=2]="Square",r[r.Triangle=3]="Triangle",r[r.L1=4]="L1",r[r.R1=5]="R1",r[r.Share=8]="Share",r[r.Options=9]="Options",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick"})(Gn||(Gn={})),function(r){r[r.Up=12]="Up",r[r.Down=13]="Down",r[r.Left=14]="Left",r[r.Right=15]="Right"}($i||($i={}));var Bl=function(r){function t(e,n,i){var o=r.call(this,e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),n,i,0,1,2,3)||this;return o._leftTrigger=0,o._rightTrigger=0,o.onButtonDownObservable=new x.c,o.onButtonUpObservable=new x.c,o.onPadDownObservable=new x.c,o.onPadUpObservable=new x.c,o._buttonCross=0,o._buttonCircle=0,o._buttonSquare=0,o._buttonTriangle=0,o._buttonShare=0,o._buttonOptions=0,o._buttonL1=0,o._buttonR1=0,o._buttonLeftStick=0,o._buttonRightStick=0,o._dPadUp=0,o._dPadDown=0,o._dPadLeft=0,o._dPadRight=0,o.type=hn.DUALSHOCK,o}return Object(c.d)(t,r),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!1,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,n,i){return e!==n&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,n,i){return e!==n&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonCross",{get:function(){return this._buttonCross},set:function(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Gn.Cross)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonCircle",{get:function(){return this._buttonCircle},set:function(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Gn.Circle)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonSquare",{get:function(){return this._buttonSquare},set:function(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Gn.Square)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonTriangle",{get:function(){return this._buttonTriangle},set:function(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Gn.Triangle)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonOptions",{get:function(){return this._buttonOptions},set:function(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Gn.Options)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonShare",{get:function(){return this._buttonShare},set:function(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Gn.Share)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonL1",{get:function(){return this._buttonL1},set:function(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Gn.L1)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonR1",{get:function(){return this._buttonR1},set:function(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Gn.R1)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Gn.LeftStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Gn.RightStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,$i.Up)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,$i.Down)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,$i.Left)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,$i.Right)},enumerable:!1,configurable:!0}),t.prototype.update=function(){r.prototype.update.call(this),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},t.prototype.dispose=function(){r.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(hn),Ul=function(){function r(t){var e=this;if(this._scene=t,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new x.c,fs.a.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new x.c(function(i){for(var o in e._babylonGamepads){var a=e._babylonGamepads[o];a&&a._isConnected&&e.onGamepadConnectedObservable.notifyObserver(i,a)}}),this._onGamepadConnectedEvent=function(i){var o,a=i.gamepad;a.index in e._babylonGamepads&&e._babylonGamepads[a.index].isConnected||(e._babylonGamepads[a.index]?((o=e._babylonGamepads[a.index]).browserGamepad=a,o._isConnected=!0):o=e._addNewGamepad(a),e.onGamepadConnectedObservable.notifyObservers(o),e._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=function(i){var o=i.gamepad;for(var a in e._babylonGamepads)if(e._babylonGamepads[a].index===o.index){var s=e._babylonGamepads[a];s._isConnected=!1,e.onGamepadDisconnectedObservable.notifyObservers(s),s.dispose&&s.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){var n=this._scene?this._scene.getEngine().getHostWindow():window;n&&(n.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),n.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}return Object.defineProperty(r.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!1,configurable:!0}),r.prototype.getGamepadByType=function(t){t===void 0&&(t=hn.XBOX);for(var e=0,n=this._babylonGamepads;e1&&(p=a.generateStencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24),o.is2DArray?e.texImage3D(i,0,p,o.width,o.height,n,0,d,s,null):e.texImage2D(i,0,p,o.width,o.height,0,d,s,null),this._bindTextureDirectly(i,null),o};var _t=function(){function r(t,e,n,i,o,a,s,d,p,y,P,O,U,F,z){s===void 0&&(s=h.a.TEXTURE_NEAREST_SAMPLINGMODE),y===void 0&&(y=null),P===void 0&&(P=h.a.TEXTURETYPE_UNSIGNED_INT),O===void 0&&(O="postprocess"),F===void 0&&(F=!1),z===void 0&&(z=h.a.TEXTUREFORMAT_RGBA),this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.alphaMode=h.a.ALPHA_DISABLE,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=h.a.SCALEMODE_FLOOR,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._textures=new li.a(2),this._currentRenderTextureInd=0,this._scaleRatio=new u.d(1,1),this._texelSize=u.d.Zero(),this.onActivateObservable=new x.c,this.onSizeChangedObservable=new x.c,this.onApplyObservable=new x.c,this.onBeforeRenderObservable=new x.c,this.onAfterRenderObservable=new x.c,this.name=t,a!=null?(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()):d&&(this._engine=d,this._engine.postProcesses.push(this)),this._options=o,this.renderTargetSamplingMode=s||h.a.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=p||!1,this._textureType=P,this._textureFormat=z,this._samplers=i||[],this._samplers.push("textureSampler"),this._fragmentUrl=e,this._vertexUrl=O,this._parameters=n||[],this._parameters.push("scale"),this._indexParameters=U,F||this.updateEffect(y)}return Object.defineProperty(r.prototype,"samples",{get:function(){return this._samples},set:function(t){var e=this;this._samples=Math.min(t,this._engine.getCaps().maxMSAASamples),this._textures.forEach(function(n){n.samples!==e._samples&&e._engine.updateRenderTargetTextureSampleCount(n,e._samples)})},enumerable:!1,configurable:!0}),r.prototype.getEffectName=function(){return this._fragmentUrl},Object.defineProperty(r.prototype,"onActivate",{set:function(t){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),t&&(this._onActivateObserver=this.onActivateObservable.add(t))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onSizeChanged",{set:function(t){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onApply",{set:function(t){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onBeforeRender",{set:function(t){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onAfterRender",{set:function(t){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"inputTexture",{get:function(){return this._textures.data[this._currentRenderTextureInd]},set:function(t){this._forcedOutputTexture=t},enumerable:!1,configurable:!0}),r.prototype.restoreDefaultInputTexture=function(){this._forcedOutputTexture=null},r.prototype.getCamera=function(){return this._camera},Object.defineProperty(r.prototype,"texelSize",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)},enumerable:!1,configurable:!0}),r.prototype.getClassName=function(){return"PostProcess"},r.prototype.getEngine=function(){return this._engine},r.prototype.getEffect=function(){return this._effect},r.prototype.shareOutputWith=function(t){return this._disposeTextures(),this._shareOutputWithPostProcess=t,this},r.prototype.useOwnOutput=function(){this._textures.length==0&&(this._textures=new li.a(2)),this._shareOutputWithPostProcess=null},r.prototype.updateEffect=function(t,e,n,i,o,a,s,d){t===void 0&&(t=null),e===void 0&&(e=null),n===void 0&&(n=null),this._effect=this._engine.createEffect({vertex:s??this._vertexUrl,fragment:d??this._fragmentUrl},["position"],e||this._parameters,n||this._samplers,t!==null?t:"",void 0,o,a,i||this._indexParameters)},r.prototype.isReusable=function(){return this._reusable},r.prototype.markTextureDirty=function(){this.width=-1},r.prototype.activate=function(t,e,n){var i=this;e===void 0&&(e=null);var o=(t=t||this._camera).getScene(),a=o.getEngine(),s=a.getCaps().maxTextureSize,d=(e?e.width:this._engine.getRenderWidth(!0))*this._options|0,p=(e?e.height:this._engine.getRenderHeight(!0))*this._options|0,y=t.parent;!y||y.leftCamera!=t&&y.rightCamera!=t||(d/=2);var P,O=this._options.width||d,U=this._options.height||p,F=this.renderTargetSamplingMode!==h.a.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==h.a.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==h.a.TEXTURE_LINEAR_LINEAR;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){var z=a.currentViewport;z&&(O*=z.width,U*=z.height)}if((F||this.alwaysForcePOT)&&(this._options.width||(O=a.needPOTTextures?Ue.a.GetExponentOfTwo(O,s,this.scaleMode):O),this._options.height||(U=a.needPOTTextures?Ue.a.GetExponentOfTwo(U,s,this.scaleMode):U)),this.width!==O||this.height!==U){if(this._textures.length>0){for(var J=0;J0)for(var t=0;t0){var n=this._camera._getFirstPostProcess();n&&n.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},r.prototype.serialize=function(){var t=L.a.Serialize(this);return t.customType="BABYLON."+this.getClassName(),t.cameraId=this.getCamera().id,t.reusable=this._reusable,t.options=this._options,t.textureType=this._textureType,t},r.Parse=function(t,e,n){var i=R.a.GetClass(t.customType);if(!i||!i._Parse)return null;var o=e.getCameraByID(t.cameraId);return o?i._Parse(t,o,e,n):null},Object(c.c)([Object(L.c)()],r.prototype,"uniqueId",void 0),Object(c.c)([Object(L.c)()],r.prototype,"name",void 0),Object(c.c)([Object(L.c)()],r.prototype,"width",void 0),Object(c.c)([Object(L.c)()],r.prototype,"height",void 0),Object(c.c)([Object(L.c)()],r.prototype,"renderTargetSamplingMode",void 0),Object(c.c)([Object(L.f)()],r.prototype,"clearColor",void 0),Object(c.c)([Object(L.c)()],r.prototype,"autoClear",void 0),Object(c.c)([Object(L.c)()],r.prototype,"alphaMode",void 0),Object(c.c)([Object(L.c)()],r.prototype,"alphaConstants",void 0),Object(c.c)([Object(L.c)()],r.prototype,"enablePixelPerfectMode",void 0),Object(c.c)([Object(L.c)()],r.prototype,"forceFullscreenViewport",void 0),Object(c.c)([Object(L.c)()],r.prototype,"scaleMode",void 0),Object(c.c)([Object(L.c)()],r.prototype,"alwaysForcePOT",void 0),Object(c.c)([Object(L.c)("samples")],r.prototype,"_samples",void 0),Object(c.c)([Object(L.c)()],r.prototype,"adaptScaleToCurrentViewport",void 0),r}();R.a.RegisteredTypes["BABYLON.PostProcess"]=_t;var lp=` -varying vec2 vUV; -uniform sampler2D textureSampler; -void main(void) -{ -gl_FragColor=texture2D(textureSampler,vUV); -}`;je.a.ShadersStore.passPixelShader=lp;var up=` -varying vec2 vUV; -uniform samplerCube textureSampler; -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 -}`;je.a.ShadersStore.passCubePixelShader=up;var Li=function(r){function t(e,n,i,o,a,s,d,p){return i===void 0&&(i=null),d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT),p===void 0&&(p=!1),r.call(this,e,"pass",null,null,n,i,o,a,s,void 0,d,void 0,null,p)||this}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"PassPostProcess"},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable)},e,i,o)},t}(_t);R.a.RegisteredTypes["BABYLON.PassPostProcess"]=Li;var hp=function(r){function t(e,n,i,o,a,s,d,p){i===void 0&&(i=null),d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT),p===void 0&&(p=!1);var y=r.call(this,e,"passCube",null,null,n,i,o,a,s,"#define POSITIVEX",d,void 0,null,p)||this;return y._face=0,y}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"face",{get:function(){return this._face},set:function(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PassCubePostProcess"},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable)},e,i,o)},t}(_t);Ue.a._RescalePostProcessFactory=function(r){return new Li("rescale",1,null,h.a.TEXTURE_BILINEAR_SAMPLINGMODE,r,!1,h.a.TEXTURETYPE_UNSIGNED_INT)};var dp=` -varying vec2 vUV; -uniform sampler2D textureSampler; -uniform sampler2D leftSampler; -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); -}`;je.a.ShadersStore.anaglyphPixelShader=dp;var ps=function(r){function t(e,n,i,o,a,s){var d=r.call(this,e,"anaglyph",null,["leftSampler"],n,i[1],o,a,s)||this;return d._passedProcess=i[0]._rigPostProcess,d.onApplyObservable.add(function(p){p.setTextureFromPostProcess("leftSampler",d._passedProcess)}),d}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"AnaglyphPostProcess"},t}(_t);R.a.RegisteredTypes["BABYLON.AnaglyphPostProcess"]=ps,gt.a._setStereoscopicAnaglyphRigMode=function(r){r._rigCameras[0]._rigPostProcess=new Li(r.name+"_passthru",1,r._rigCameras[0]),r._rigCameras[1]._rigPostProcess=new ps(r.name+"_anaglyph",1,r._rigCameras)},Q.a.AddNodeConstructor("AnaglyphArcRotateCamera",function(r,t,e){return function(){return new Gl(r,0,0,1,u.e.Zero(),e.interaxial_distance,t)}});var Gl=function(r){function t(e,n,i,o,a,s,d){var p=r.call(this,e,n,i,o,a,d)||this;return p.interaxialDistance=s,p.setCameraRigMode(gt.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:s}),p}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"AnaglyphArcRotateCamera"},t}(Zi);Q.a.AddNodeConstructor("AnaglyphFreeCamera",function(r,t,e){return function(){return new zl(r,u.e.Zero(),e.interaxial_distance,t)}});var zl=function(r){function t(e,n,i,o){var a=r.call(this,e,n,o)||this;return a.interaxialDistance=i,a.setCameraRigMode(gt.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i}),a}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"AnaglyphFreeCamera"},t}(Hn);Q.a.AddNodeConstructor("AnaglyphGamepadCamera",function(r,t,e){return function(){return new jl(r,u.e.Zero(),e.interaxial_distance,t)}});var jl=function(r){function t(e,n,i,o){var a=r.call(this,e,n,o)||this;return a.interaxialDistance=i,a.setCameraRigMode(gt.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i}),a}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"AnaglyphGamepadCamera"},t}(ko);Q.a.AddNodeConstructor("AnaglyphUniversalCamera",function(r,t,e){return function(){return new Hl(r,u.e.Zero(),e.interaxial_distance,t)}});var Hl=function(r){function t(e,n,i,o){var a=r.call(this,e,n,o)||this;return a.interaxialDistance=i,a.setCameraRigMode(gt.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i}),a}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"AnaglyphUniversalCamera"},t}(pr),Wn=f(58);gt.a._setStereoscopicRigMode=function(r){var t=r.cameraRigMode===gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||r.cameraRigMode===gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,e=r.cameraRigMode===gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;r._rigCameras[e?1:0].viewport=new Wn.a(0,0,t?.5:1,t?1:.5),r._rigCameras[e?0:1].viewport=new Wn.a(t?.5:0,t?0:.5,t?.5:1,t?1:.5)},Q.a.AddNodeConstructor("StereoscopicArcRotateCamera",function(r,t,e){return function(){return new Wl(r,0,0,1,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Wl=function(r){function t(e,n,i,o,a,s,d,p){var y=r.call(this,e,n,i,o,a,p)||this;return y.interaxialDistance=s,y.isStereoscopicSideBySide=d,y.setCameraRigMode(d?gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:s}),y}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicArcRotateCamera"},t}(Zi);Q.a.AddNodeConstructor("StereoscopicFreeCamera",function(r,t,e){return function(){return new Xl(r,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Xl=function(r){function t(e,n,i,o,a){var s=r.call(this,e,n,a)||this;return s.interaxialDistance=i,s.isStereoscopicSideBySide=o,s.setCameraRigMode(o?gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i}),s}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicFreeCamera"},t}(Hn);Q.a.AddNodeConstructor("StereoscopicGamepadCamera",function(r,t,e){return function(){return new Yl(r,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Yl=function(r){function t(e,n,i,o,a){var s=r.call(this,e,n,a)||this;return s.interaxialDistance=i,s.isStereoscopicSideBySide=o,s.setCameraRigMode(o?gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i}),s}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicGamepadCamera"},t}(ko);Q.a.AddNodeConstructor("StereoscopicFreeCamera",function(r,t,e){return function(){return new Kl(r,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Kl=function(r){function t(e,n,i,o,a){var s=r.call(this,e,n,a)||this;return s.interaxialDistance=i,s.isStereoscopicSideBySide=o,s.setCameraRigMode(o?gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i}),s}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicUniversalCamera"},t}(pr);Q.a.AddNodeConstructor("VirtualJoysticksCamera",function(r,t){return function(){return new Ql(r,u.e.Zero(),t)}});var Ql=function(r){function t(e,n,i){var o=r.call(this,e,n,i)||this;return o.inputs.addVirtualJoystick(),o}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t}(Hn),_r=function(){function r(){this.compensateDistortion=!0,this.multiviewEnabled=!1}return Object.defineProperty(r.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"leftHMatrix",{get:function(){var t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return u.a.Translation(t,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"rightHMatrix",{get:function(){var t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return u.a.Translation(-t,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"leftPreViewMatrix",{get:function(){return u.a.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"rightPreViewMatrix",{get:function(){return u.a.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!1,configurable:!0}),r.GetDefault=function(){var t=new r;return t.hResolution=1280,t.vResolution=800,t.hScreenSize=.149759993,t.vScreenSize=.0935999975,t.vScreenCenter=.0467999987,t.eyeToScreenDistance=.0410000011,t.lensSeparationDistance=.063500002,t.interpupillaryDistance=.064000003,t.distortionK=[1,.219999999,.239999995,0],t.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],t.postProcessScaleFactor=1.714605507808412,t.lensCenterOffset=.151976421,t},r}(),fp=` -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; -} -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); -} -}`;je.a.ShadersStore.vrDistortionCorrectionPixelShader=fp;var _s=function(r){function t(e,n,i,o){var a=r.call(this,e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,o.postProcessScaleFactor,n,we.a.BILINEAR_SAMPLINGMODE)||this;return a._isRightEye=i,a._distortionFactors=o.distortionK,a._postProcessScaleFactor=o.postProcessScaleFactor,a._lensCenterOffset=o.lensCenterOffset,a.adaptScaleToCurrentViewport=!0,a.onSizeChangedObservable.add(function(){a._scaleIn=new u.d(2,2/a.aspectRatio),a._scaleFactor=new u.d(1/a._postProcessScaleFactor*.5,1/a._postProcessScaleFactor*.5*a.aspectRatio),a._lensCenter=new u.d(a._isRightEye?.5-.5*a._lensCenterOffset:.5+.5*a._lensCenterOffset,.5)}),a.onApplyObservable.add(function(s){s.setFloat2("LensCenter",a._lensCenter.x,a._lensCenter.y),s.setFloat2("Scale",a._scaleFactor.x,a._scaleFactor.y),s.setFloat2("ScaleIn",a._scaleIn.x,a._scaleIn.y),s.setFloat4("HmdWarpParam",a._distortionFactors[0],a._distortionFactors[1],a._distortionFactors[2],a._distortionFactors[3])}),a}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"VRDistortionCorrectionPostProcess"},t}(_t),pp=`precision mediump sampler2DArray; -varying vec2 vUV; -uniform sampler2DArray multiviewSampler; -uniform int imageIndex; -void main(void) -{ -gl_FragColor=texture(multiviewSampler,vec3(vUV,imageIndex)); -}`;je.a.ShadersStore.vrMultiviewToSingleviewPixelShader=pp;var ql=f(85),ms=f(95),eo=f(96);Bt.a.prototype.createRenderTargetCubeTexture=function(r,t){var e=Object(c.a)({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:h.a.TEXTURETYPE_UNSIGNED_INT,samplingMode:h.a.TEXTURE_TRILINEAR_SAMPLINGMODE,format:h.a.TEXTUREFORMAT_RGBA},t);e.generateStencilBuffer=e.generateDepthBuffer&&e.generateStencilBuffer,(e.type!==h.a.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(e.type!==h.a.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(e.samplingMode=h.a.TEXTURE_NEAREST_SAMPLINGMODE);var n=this._gl,i=new xt.a(this,xt.b.RenderTarget);this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,i,!0);var o=this._getSamplingParameters(e.samplingMode,e.generateMipMaps);e.type!==h.a.TEXTURETYPE_FLOAT||this._caps.textureFloat||(e.type=h.a.TEXTURETYPE_UNSIGNED_INT,l.a.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,o.min),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);for(var a=0;a<6;a++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,this._getRGBABufferInternalSizedFormat(e.type,e.format),r,r,0,this._getInternalFormat(e.format),this._getWebGLTextureType(e.type),null);var s=n.createFramebuffer();return this._bindUnboundFramebuffer(s),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(e.generateStencilBuffer,e.generateDepthBuffer,r,r),e.generateMipMaps&&n.generateMipmap(n.TEXTURE_CUBE_MAP),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=s,i.width=r,i.height=r,i.isReady=!0,i.isCube=!0,i.samples=1,i.generateMipMaps=e.generateMipMaps,i.samplingMode=e.samplingMode,i.type=e.type,i.format=e.format,i._generateDepthBuffer=e.generateDepthBuffer,i._generateStencilBuffer=e.generateStencilBuffer,this._internalTexturesCache.push(i),i};var sn=function(r){function t(e,n,i,o,a,s,d,p,y,P,O,U,F){a===void 0&&(a=!0),s===void 0&&(s=h.a.TEXTURETYPE_UNSIGNED_INT),d===void 0&&(d=!1),p===void 0&&(p=we.a.TRILINEAR_SAMPLINGMODE),y===void 0&&(y=!0),P===void 0&&(P=!1),O===void 0&&(O=!1),U===void 0&&(U=h.a.TEXTUREFORMAT_RGBA),F===void 0&&(F=!1);var z=r.call(this,null,i,!o)||this;return z.renderParticles=!0,z.renderSprites=!1,z.ignoreCameraViewport=!1,z.onBeforeBindObservable=new x.c,z.onAfterUnbindObservable=new x.c,z.onBeforeRenderObservable=new x.c,z.onAfterRenderObservable=new x.c,z.onClearObservable=new x.c,z.onResizeObservable=new x.c,z._currentRefreshId=-1,z._refreshRate=1,z._samples=1,z.boundingBoxPosition=u.e.Zero(),(i=z.getScene())&&(z._coordinatesMode=we.a.PROJECTION_MODE,z.renderList=new Array,z.name=e,z.isRenderTarget=!0,z._initialSizeParameter=n,z._processSizeParameter(n),z._resizeObserver=z.getScene().getEngine().onResizeObservable.add(function(){}),z._generateMipMaps=!!o,z._doNotChangeAspectRatio=a,z._renderingManager=new eo.b(i),z._renderingManager._useSceneAutoClearSetup=!0,O||(z._renderTargetOptions={generateMipMaps:o,type:s,format:U,samplingMode:p,generateDepthBuffer:y,generateStencilBuffer:P},p===we.a.NEAREST_SAMPLINGMODE&&(z.wrapU=we.a.CLAMP_ADDRESSMODE,z.wrapV=we.a.CLAMP_ADDRESSMODE),F||(d?(z._texture=i.getEngine().createRenderTargetCubeTexture(z.getRenderSize(),z._renderTargetOptions),z.coordinatesMode=we.a.INVCUBIC_MODE,z._textureMatrix=u.a.Identity()):z._texture=i.getEngine().createRenderTargetTexture(z._size,z._renderTargetOptions)))),z}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"renderList",{get:function(){return this._renderList},set:function(e){this._renderList=e,this._renderList&&this._hookArray(this._renderList)},enumerable:!1,configurable:!0}),t.prototype._hookArray=function(e){var n=this,i=e.push;e.push=function(){for(var a=[],s=0;s0&&(this._postProcesses[0].autoClear=!1))}},t.prototype._shouldRender=function(){return this._currentRefreshId===-1||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},t.prototype.getRenderSize=function(){return this.getRenderWidth()},t.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},t.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},t.prototype.getRenderLayers=function(){var e=this._size.layers;return e||0},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.scale=function(e){var n=Math.max(1,this.getRenderSize()*e);this.resize(n)},t.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:r.prototype.getReflectionTextureMatrix.call(this)},t.prototype.resize=function(e){var n=this.isCube;this.releaseInternalTexture();var i=this.getScene();i&&(this._processSizeParameter(e),this._texture=n?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))},t.prototype.render=function(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=!1),p=this.getScene()){var i,o=p.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var a=0;a1||this.activeCamera&&this.activeCamera!==p.activeCamera)&&p.setTransformMatrix(p.activeCamera.getViewMatrix(),p.activeCamera.getProjectionMatrix(!0)),o.setViewport(p.activeCamera.viewport)),p.resetCachedMaterial()}},t.prototype._bestReflectionRenderTargetDimension=function(e,n){var i=e*n,o=Ue.a.NearestPOT(i+16384/(128+i));return Math.min(Ue.a.FloorPOT(e),o)},t.prototype._prepareRenderingManager=function(e,n,i,o){var a=this.getScene();if(a){this._renderingManager.reset();for(var s=a.getRenderId(),d=0;d=0&&this._renderingManager.dispatchParticles(z)}}},t.prototype._bindFrameBuffer=function(e,n){e===void 0&&(e=0),n===void 0&&(n=0);var i=this.getScene();if(i){var o=i.getEngine();this._texture&&o.bindFramebuffer(this._texture,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,n)}},t.prototype.unbindFrameBuffer=function(e,n){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,function(){i.onAfterRenderObservable.notifyObservers(n)})},t.prototype.renderToTarget=function(e,n,i,o,a){o===void 0&&(o=0),a===void 0&&(a=null);var s=this.getScene();if(s){var d=s.getEngine();if(this._texture){this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&s.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(e,o),this.is2DArray?this.onBeforeRenderObservable.notifyObservers(o):this.onBeforeRenderObservable.notifyObservers(e);var p=null,y=this.renderList?this.renderList:s.getActiveMeshes().data,P=this.renderList?this.renderList.length:s.getActiveMeshes().length;this.getCustomRenderList&&(p=this.getCustomRenderList(this.is2DArray?o:e,y,P)),p?this._prepareRenderingManager(p,p.length,a,!1):(this._defaultRenderListPrepared||(this._prepareRenderingManager(y,P,a,!this.renderList),this._defaultRenderListPrepared=!0),p=y),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):d.clear(this.clearColor||s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(var O=0,U=s._beforeRenderTargetDrawStage;O=0&&e.customRenderTargets.splice(n,1);for(var i=0,o=e.cameras;i=0&&a.customRenderTargets.splice(n,1)}this.depthStencilTexture&&this.getScene().getEngine()._releaseTexture(this.depthStencilTexture),r.prototype.dispose.call(this)}},t.prototype._rebuild=function(){this.refreshRate===t.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=t.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},t.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},t.prototype.getViewCount=function(){return 1},t.REFRESHRATE_RENDER_ONCE=0,t.REFRESHRATE_RENDER_ONEVERYFRAME=1,t.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,t}(we.a);we.a._CreateRenderTargetTexture=function(r,t,e,n){return new sn(r,t,e,n)};var Zl=function(r){function t(e,n){n===void 0&&(n=512);var i=r.call(this,"multiview rtt",n,e,!1,!0,xt.b.Unknown,!1,void 0,!1,!1,!0,void 0,!0)||this,o=e.getEngine().createMultiviewRenderTargetTexture(i.getRenderWidth(),i.getRenderHeight());return o.isMultiview=!0,o.format=h.a.TEXTUREFORMAT_RGBA,i._texture=o,i.samples=i._getEngine().getCaps().maxSamples||i.samples,i}return Object(c.d)(t,r),t.prototype._bindFrameBuffer=function(e){this._texture&&this.getScene().getEngine().bindMultiviewFramebuffer(this._texture)},t.prototype.getViewCount=function(){return 2},t}(sn),Jl=f(90);Ue.a.prototype.createMultiviewRenderTargetTexture=function(r,t){var e=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";var n=new xt.a(this,xt.b.Unknown,!0);return n.width=r,n.height=t,n._framebuffer=e.createFramebuffer(),n._colorTextureArray=e.createTexture(),e.bindTexture(e.TEXTURE_2D_ARRAY,n._colorTextureArray),e.texStorage3D(e.TEXTURE_2D_ARRAY,1,e.RGBA8,r,t,2),n._depthStencilTextureArray=e.createTexture(),e.bindTexture(e.TEXTURE_2D_ARRAY,n._depthStencilTextureArray),e.texStorage3D(e.TEXTURE_2D_ARRAY,1,e.DEPTH32F_STENCIL8,r,t,2),n.isReady=!0,n},Ue.a.prototype.bindMultiviewFramebuffer=function(r){var t=this._gl,e=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(r,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,r._framebuffer),!r._colorTextureArray||!r._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(e.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,r._colorTextureArray,0,r.samples,0,2),e.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,r._depthStencilTextureArray,0,r.samples,0,2)):(e.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,r._colorTextureArray,0,0,2),e.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,r._depthStencilTextureArray,0,0,2))},gt.a.prototype._useMultiviewToSingleView=!1,gt.a.prototype._multiviewTexture=null,gt.a.prototype._resizeOrCreateMultiviewTexture=function(r,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==r&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Zl(this.getScene(),{width:r,height:t})):this._multiviewTexture=new Zl(this.getScene(),{width:r,height:t})},_e.a.prototype._transformMatrixR=u.a.Zero(),_e.a.prototype._multiviewSceneUbo=null,_e.a.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=new ql.a(this.getEngine(),void 0,!0),this._multiviewSceneUbo.addUniform("viewProjection",16),this._multiviewSceneUbo.addUniform("viewProjectionR",16),this._multiviewSceneUbo.addUniform("view",16)},_e.a.prototype._updateMultiviewUbo=function(r,t){r&&t&&r.multiplyToRef(t,this._transformMatrixR),r&&t&&(r.multiplyToRef(t,u.c.Matrix[0]),Jl.a.GetRightPlaneToRef(u.c.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.update())},_e.a.prototype._renderMultiviewToSingleView=function(r){r._resizeOrCreateMultiviewTexture(r._rigPostProcess&&r._rigPostProcess&&r._rigPostProcess.width>0?r._rigPostProcess.width:this.getEngine().getRenderWidth(!0),r._rigPostProcess&&r._rigPostProcess&&r._rigPostProcess.height>0?r._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),r.outputRenderTarget=r._multiviewTexture,this._renderForCamera(r),r.outputRenderTarget=null;for(var t=0;t=2&&e.onControllersAttachedObservable.notifyObservers(e.controllers)}}})},t}(Hn),Ni=function(r){function t(e){var n=r.call(this,e)||this;return n.onTriggerStateChangedObservable=new x.c,n.onMainButtonStateChangedObservable=new x.c,n.onSecondaryButtonStateChangedObservable=new x.c,n.onPadStateChangedObservable=new x.c,n.onPadValuesChangedObservable=new x.c,n.pad={x:0,y:0},n._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},n._buttons=new Array(e.buttons.length),n.hand=e.hand,n}return Object(c.d)(t,r),t.prototype.onButtonStateChange=function(e){this._onButtonStateChange=e},Object.defineProperty(t.prototype,"defaultModel",{get:function(){return this._defaultModel},enumerable:!1,configurable:!0}),t.prototype.update=function(){r.prototype.update.call(this);for(var e=0;e -#include -#include -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; -}`);je.a.ShadersStore.imageProcessingPixelShader=_p;var Ho=function(r){function t(e,n,i,o,a,s,d,p){i===void 0&&(i=null),d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT);var y=r.call(this,e,"imageProcessing",[],[],n,i,o,a,s,null,d,"postprocess",null,!0)||this;return y._fromLinearSpace=!0,y._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,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1},p?(p.applyByPostProcess=!0,y._attachImageProcessingConfiguration(p,!0),y.fromLinearSpace=!1):(y._attachImageProcessingConfiguration(null,!0),y.imageProcessingConfiguration.applyByPostProcess=!0),y.onApply=function(P){y.imageProcessingConfiguration.bind(P,y.aspectRatio)},y}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e,n){var i=this;if(n===void 0&&(n=!1),e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{var o=null,a=this.getEngine(),s=this.getCamera();if(s)o=s.getScene();else if(a&&a.scenes){var d=a.scenes;o=d[d.length-1]}else o=te.a.LastCreatedScene;this._imageProcessingConfiguration=o?o.imageProcessingConfiguration:new vn.a}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){i._updateParameters()})),n||this._updateParameters()}},Object.defineProperty(t.prototype,"isSupported",{get:function(){var e=this.getEffect();return!e||e.isSupported},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingTexture",{get:function(){return this.imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"exposure",{get:function(){return this.imageProcessingConfiguration.exposure},set:function(e){this.imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingType",{get:function(){return this._imageProcessingConfiguration.toneMappingType},set:function(e){this._imageProcessingConfiguration.toneMappingType=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"contrast",{get:function(){return this.imageProcessingConfiguration.contrast},set:function(e){this.imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteStretch",{get:function(){return this.imageProcessingConfiguration.vignetteStretch},set:function(e){this.imageProcessingConfiguration.vignetteStretch=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreX",{get:function(){return this.imageProcessingConfiguration.vignetteCentreX},set:function(e){this.imageProcessingConfiguration.vignetteCentreX=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreY",{get:function(){return this.imageProcessingConfiguration.vignetteCentreY},set:function(e){this.imageProcessingConfiguration.vignetteCentreY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteWeight",{get:function(){return this.imageProcessingConfiguration.vignetteWeight},set:function(e){this.imageProcessingConfiguration.vignetteWeight=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteColor",{get:function(){return this.imageProcessingConfiguration.vignetteColor},set:function(e){this.imageProcessingConfiguration.vignetteColor=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCameraFov",{get:function(){return this.imageProcessingConfiguration.vignetteCameraFov},set:function(e){this.imageProcessingConfiguration.vignetteCameraFov=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteBlendMode",{get:function(){return this.imageProcessingConfiguration.vignetteBlendMode},set:function(e){this.imageProcessingConfiguration.vignetteBlendMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteEnabled",{get:function(){return this.imageProcessingConfiguration.vignetteEnabled},set:function(e){this.imageProcessingConfiguration.vignetteEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fromLinearSpace",{get:function(){return this._fromLinearSpace},set:function(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"ImageProcessingPostProcess"},t.prototype._updateParameters=function(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);var e="";for(var n in this._defines)this._defines[n]&&(e+="#define "+n+`;\r -`);var i=["textureSampler"],o=["scale"];vn.a&&(vn.a.PrepareSamplers(i,this._defines),vn.a.PrepareUniforms(o,this._defines)),this.updateEffect(e,o,i)},t.prototype.dispose=function(e){r.prototype.dispose.call(this,e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)},Object(c.c)([Object(L.c)()],t.prototype,"_fromLinearSpace",void 0),t}(_t),ft=f(16),Me=f(4);De.a._GroundMeshParser=function(r,t){return Wo.Parse(r,t)};var Wo=function(r){function t(e,n){var i=r.call(this,e,n)||this;return i.generateOctree=!1,i}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"GroundMesh"},Object.defineProperty(t.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!1,configurable:!0}),t.prototype.optimize=function(e,n){n===void 0&&(n=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(n)},t.prototype.getHeightAtCoordinates=function(e,n){var i=this.getWorldMatrix(),o=u.c.Matrix[5];i.invertToRef(o);var a=u.c.Vector3[8];if(u.e.TransformCoordinatesFromFloatsToRef(e,0,n,o,a),e=a.x,n=a.z,ethis._maxX||nthis._maxZ)return this.position.y;this._heightQuads&&this._heightQuads.length!=0||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(e,n),d=-(s.x*e+s.z*n+s.w)/s.y;return u.e.TransformCoordinatesFromFloatsToRef(0,d,0,i,a),a.y},t.prototype.getNormalAtCoordinates=function(e,n){var i=new u.e(0,1,0);return this.getNormalAtCoordinatesToRef(e,n,i),i},t.prototype.getNormalAtCoordinatesToRef=function(e,n,i){var o=this.getWorldMatrix(),a=u.c.Matrix[5];o.invertToRef(a);var s=u.c.Vector3[8];if(u.e.TransformCoordinatesFromFloatsToRef(e,0,n,a,s),e=s.x,n=s.z,ethis._maxX||nthis._maxZ)return this;this._heightQuads&&this._heightQuads.length!=0||(this._initHeightQuads(),this._computeHeightQuads());var d=this._getFacetAt(e,n);return u.e.TransformNormalFromFloatsToRef(d.x,d.y,d.z,o,i),this},t.prototype.updateCoordinateHeights=function(){return this._heightQuads&&this._heightQuads.length!=0||this._initHeightQuads(),this._computeHeightQuads(),this},t.prototype._getFacetAt=function(e,n){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),o=Math.floor(-(n+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),a=this._heightQuads[o*this._subdivisionsX+i];return nr.maxHeight){p=!0;var y=r.maxHeight;r.maxHeight=r.minHeight,r.minHeight=y}for(t=0;t<=r.subdivisions;t++)for(e=0;e<=r.subdivisions;e++){var P=new u.e(e*r.width/r.subdivisions-r.width/2,0,(r.subdivisions-t)*r.height/r.subdivisions-r.height/2),O=4*(((P.x+r.width/2)/r.width*(r.bufferWidth-1)|0)+((1-(P.z+r.height/2)/r.height)*(r.bufferHeight-1)|0)*r.bufferWidth),U=r.buffer[O]/255,F=r.buffer[O+1]/255,z=r.buffer[O+2]/255,J=r.buffer[O+3]/255;p&&(U=1-U,F=1-F,z=1-z);var ie=U*s.r+F*s.g+z*s.b;P.y=J>=d?r.minHeight+(r.maxHeight-r.minHeight)*ie:r.minHeight-Gt.a,i.push(P.x,P.y,P.z),o.push(0,0,0),a.push(e/r.subdivisions,1-t/r.subdivisions)}for(t=0;t=r.minHeight,Te=i[3*ce+1]>=r.minHeight,Oe=i[3*ue+1]>=r.minHeight;ve&&Te&&Oe&&(n.push(se),n.push(ce),n.push(ue)),i[3*fe+1]>=r.minHeight&&ve&&Oe&&(n.push(fe),n.push(se),n.push(ue))}ft.a.ComputeNormals(i,n,o);var Pe=new ft.a;return Pe.indices=n,Pe.positions=i,Pe.normals=o,Pe.uvs=a,Pe},De.a.CreateGround=function(r,t,e,n,i,o){var a={width:t,height:e,subdivisions:n,updatable:o};return wi.CreateGround(r,a,i)},De.a.CreateTiledGround=function(r,t,e,n,i,o,a,s,d){var p={xmin:t,zmin:e,xmax:n,zmax:i,subdivisions:o,precision:a,updatable:d};return wi.CreateTiledGround(r,p,s)},De.a.CreateGroundFromHeightMap=function(r,t,e,n,i,o,a,s,d,p,y){var P={width:e,height:n,subdivisions:i,minHeight:o,maxHeight:a,updatable:d,onReady:p,alphaFilter:y};return wi.CreateGroundFromHeightMap(r,t,P,s)};var wi=function(){function r(){}return r.CreateGround=function(t,e,n){var i=new Wo(t,n);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,ft.a.CreateGround(e).applyToMesh(i,e.updatable),i._setReady(!0),i},r.CreateTiledGround=function(t,e,n){n===void 0&&(n=null);var i=new De.a(t,n);return ft.a.CreateTiledGround(e).applyToMesh(i,e.updatable),i},r.CreateGroundFromHeightMap=function(t,e,n,i){i===void 0&&(i=null);var o=n.width||10,a=n.height||10,s=n.subdivisions||1,d=n.minHeight||0,p=n.maxHeight||1,y=n.colorFilter||new M.a(.3,.59,.11),P=n.alphaFilter||0,O=n.updatable,U=n.onReady;i=i||te.a.LastCreatedScene;var F=new Wo(t,i);return F._subdivisionsX=s,F._subdivisionsY=s,F._width=o,F._height=a,F._maxX=F._width/2,F._maxZ=F._height/2,F._minX=-F._maxX,F._minZ=-F._maxZ,F._setReady(!1),Ye.b.LoadImage(e,function(z){var J=z.width,ie=z.height,se=vs.a.CreateCanvas(J,ie).getContext("2d");if(!se)throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");if(!i.isDisposed){se.drawImage(z,0,0);var ce=se.getImageData(0,0,J,ie).data;ft.a.CreateGroundFromHeightMap({width:o,height:a,subdivisions:s,minHeight:d,maxHeight:p,colorFilter:y,buffer:ce,bufferWidth:J,bufferHeight:ie,alphaFilter:P}).applyToMesh(F,O),U&&U(F),F._setReady(!0)}},function(){},i.offlineProvider),F},r}();ft.a.CreateTorus=function(r){for(var t=[],e=[],n=[],i=[],o=r.diameter||1,a=r.thickness||.5,s=r.tessellation||16,d=r.sideOrientation===0?0:r.sideOrientation||ft.a.DEFAULTSIDE,p=s+1,y=0;y<=s;y++)for(var P=y/s,O=y*Math.PI*2/s-Math.PI/2,U=u.a.Translation(o/2,0,0).multiply(u.a.RotationY(O)),F=0;F<=s;F++){var z=1-F/s,J=F*Math.PI*2/s+Math.PI,ie=Math.cos(J),se=Math.sin(J),ce=new u.e(ie,se,0),ue=ce.scale(a/2),fe=new u.d(P,z);ue=u.e.TransformCoordinates(ue,U),ce=u.e.TransformNormal(ce,U),e.push(ue.x,ue.y,ue.z),n.push(ce.x,ce.y,ce.z),i.push(fe.x,fe.y);var ve=(y+1)%p,Te=(F+1)%p;t.push(y*p+F),t.push(y*p+Te),t.push(ve*p+F),t.push(y*p+Te),t.push(ve*p+Te),t.push(ve*p+F)}ft.a._ComputeSides(d,e,t,n,i,r.frontUVs,r.backUVs);var Oe=new ft.a;return Oe.indices=t,Oe.positions=e,Oe.normals=n,Oe.uvs=i,Oe},De.a.CreateTorus=function(r,t,e,n,i,o,a){var s={diameter:t,thickness:e,tessellation:n,sideOrientation:a,updatable:o};return mr.CreateTorus(r,s,i)};var fn,er,mr=function(){function r(){}return r.CreateTorus=function(t,e,n){var i=new De.a(t,n);return e.sideOrientation=De.a._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,ft.a.CreateTorus(e).applyToMesh(i,e.updatable),i},r}(),ui=f(53),bs=function(){function r(){}return r.GetDefaults=function(t){var e=new r;return e.canvasOptions={antialias:!0,depth:!0,stencil:!t||t.isStencilEnable,alpha:!0,multiview:!1,framebufferScaleFactor:1},e.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",e},r}(),tu=function(){function r(t,e){var n=this;if(e===void 0&&(e=bs.GetDefaults()),this._options=e,this._canvas=null,this.xrLayer=null,this.onXRLayerInitObservable=new x.c,this._engine=t.scene.getEngine(),e.canvasElement)this._setManagedOutputCanvas(e.canvasElement);else{var i=document.createElement("canvas");i.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(i)}t.onXRSessionInit.add(function(){n._addCanvas()}),t.onXRSessionEnded.add(function(){n._removeCanvas()})}return r.prototype.dispose=function(){this._removeCanvas(),this._setManagedOutputCanvas(null)},r.prototype.initializeXRLayerAsync=function(t){var e=this,n=function(){var i=new XRWebGLLayer(t,e.canvasContext,e._options.canvasOptions);return e.onXRLayerInitObservable.notifyObservers(i),i};return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(function(){return e.xrLayer=n(),e.xrLayer}):(this.xrLayer=n(),Promise.resolve(this.xrLayer))},r.prototype._addCanvas=function(){var t=this;this._canvas&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(function(e){t._setCanvasSize(!0,e)})},r.prototype._removeCanvas=function(){this._canvas&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)},r.prototype._setCanvasSize=function(t,e){t===void 0&&(t=!0),e===void 0&&(e=this.xrLayer),this._canvas&&(t?e&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=e.framebufferWidth+"px",this._canvas.style.height=e.framebufferHeight+"px"):this._engine.setSize(e.framebufferWidth,e.framebufferHeight)):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)))},r.prototype._setManagedOutputCanvas=function(t){this._removeCanvas(),t?(this._originalCanvasSize={width:t.offsetWidth,height:t.offsetHeight},this._canvas=t,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)},r}(),ys=function(){function r(t){this.scene=t,this._sessionEnded=!1,this.baseLayer=null,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new x.c,this.onXRReferenceSpaceChanged=new x.c,this.onXRSessionEnded=new x.c,this.onXRSessionInit=new x.c}return Object.defineProperty(r.prototype,"referenceSpace",{get:function(){return this._referenceSpace},set:function(t){this._referenceSpace=t,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)},enumerable:!1,configurable:!0}),r.prototype.dispose=function(){this._sessionEnded||this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear()},r.prototype.exitXRAsync=function(){return this.session&&!this._sessionEnded?(this._sessionEnded=!0,this.session.end().catch(function(t){l.a.Warn("Could not end XR session.")})):Promise.resolve()},r.prototype.getRenderTargetTextureForEye=function(t){return this._rttProvider.getRenderTargetForEye(t)},r.prototype.getWebXRRenderTarget=function(t){var e=this.scene.getEngine();return this._xrNavigator.xr.native?this._xrNavigator.xr.getWebXRRenderTarget(e):((t=t||bs.GetDefaults(e)).canvasElement=e.getRenderingCanvas()||void 0,new tu(this,t))},r.prototype.initializeAsync=function(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")},r.prototype.initializeSessionAsync=function(t,e){var n=this;return t===void 0&&(t="immersive-vr"),e===void 0&&(e={}),this._xrNavigator.xr.requestSession(t,e).then(function(i){return n.session=i,n.onXRSessionInit.notifyObservers(i),n._sessionEnded=!1,n.session.addEventListener("end",function(){var o=n.scene.getEngine();n._sessionEnded=!0,n._rttProvider=null,o.framebufferDimensionsObject=null,o.restoreDefaultFramebuffer(),o.customAnimationFrameRequester=null,n.onXRSessionEnded.notifyObservers(null),o._renderLoop()},{once:!0}),n.session})},r.prototype.isSessionSupportedAsync=function(t){return r.IsSessionSupportedAsync(t)},r.prototype.resetReferenceSpace=function(){this.referenceSpace=this.baseReferenceSpace},r.prototype.runXRRenderLoop=function(){var t=this,e=this.scene.getEngine();if(e.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:function(i,o){t._sessionEnded||(t.currentFrame=o,t.currentTimestamp=i,o&&(e.framebufferDimensionsObject=t.baseLayer,t.onXRFrameObservable.notifyObservers(o),e._renderLoop(),e.framebufferDimensionsObject=null))}},this._xrNavigator.xr.native)this._rttProvider=this._xrNavigator.xr.getNativeRenderTargetProvider(this.session,this._createRenderTargetTexture.bind(this));else{var n=this._createRenderTargetTexture(this.baseLayer.framebufferWidth,this.baseLayer.framebufferHeight,this.baseLayer.framebuffer);this._rttProvider={getRenderTargetForEye:function(){return n}},e.framebufferDimensionsObject=this.baseLayer}typeof window<"u"&&window.cancelAnimationFrame&&window.cancelAnimationFrame(e._frameHandler),e._renderLoop()},r.prototype.setReferenceSpaceTypeAsync=function(t){var e=this;return t===void 0&&(t="local-floor"),this.session.requestReferenceSpace(t).then(function(n){return n},function(n){return l.a.Error("XR.requestReferenceSpace failed for the following reason: "),l.a.Error(n),l.a.Log('Defaulting to universally-supported "viewer" reference space type.'),e.session.requestReferenceSpace("viewer").then(function(i){var o=new XRRigidTransform({x:0,y:-e.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(o)},function(i){throw l.a.Error(i),'XR initialization failed: required "viewer" reference space type not supported.'})}).then(function(n){return e.session.requestReferenceSpace("viewer").then(function(i){return e.viewerReferenceSpace=i,n})}).then(function(n){return e.referenceSpace=e.baseReferenceSpace=n,e.referenceSpace})},r.prototype.updateRenderStateAsync=function(t){return t.baseLayer&&(this.baseLayer=t.baseLayer),this.session.updateRenderState(t)},r.IsSessionSupportedAsync=function(t){if(!navigator.xr)return Promise.resolve(!1);var e=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return e?e.call(navigator.xr,t).then(function(n){var i=n===void 0||n;return Promise.resolve(i)}).catch(function(n){return l.a.Warn(n),Promise.resolve(!1)}):Promise.resolve(!1)},r.prototype._createRenderTargetTexture=function(t,e,n){n===void 0&&(n=null);var i=new xt.a(this.scene.getEngine(),xt.b.Unknown,!0);i.width=t,i.height=e,i._framebuffer=n;var o=new sn("XR renderTargetTexture",{width:t,height:e},this.scene,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0);return o._texture=i,o},r}();(function(r){r[r.ENTERING_XR=0]="ENTERING_XR",r[r.EXITING_XR=1]="EXITING_XR",r[r.IN_XR=2]="IN_XR",r[r.NOT_IN_XR=3]="NOT_IN_XR"})(fn||(fn={})),function(r){r[r.NOT_TRACKING=0]="NOT_TRACKING",r[r.TRACKING_LOST=1]="TRACKING_LOST",r[r.TRACKING=2]="TRACKING"}(er||(er={}));var ti,nu=function(){function r(t,e){if(e===void 0&&(e=null),this.scene=t,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=r._idCounter++,e)this._gazeTracker=e.clone("gazeTracker");else{this._gazeTracker=De.a.CreateTorus("gazeTracker",.0035,.0025,20,t,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new Ft.a("targetMat",t);n.specularColor=M.a.Black(),n.emissiveColor=new M.a(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return r.prototype._getForwardRay=function(t){return new dn.a(u.e.Zero(),new u.e(0,0,t))},r.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},r.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},r.prototype._activatePointer=function(){this._activePointer=!0},r.prototype._deactivatePointer=function(){this._activePointer=!1},r.prototype._updatePointerDistance=function(t){},r.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},r._idCounter=0,r}(),mp=function(r){function t(e,n,i){var o=r.call(this,n,i)||this;o.webVRController=e,o._laserPointer=De.a.CreateCylinder("laserPointer",1,.004,2e-4,20,1,n,!1);var a=new Ft.a("laserPointerMat",n);if(a.emissiveColor=new M.a(.7,.7,.7),a.alpha=.6,o._laserPointer.material=a,o._laserPointer.rotation.x=Math.PI/2,o._laserPointer.position.z=-.5,o._laserPointer.isVisible=!1,o._laserPointer.isPickable=!1,!e.mesh){var s=new De.a("preloadControllerMesh",n),d=new De.a(fr.POINTING_POSE,n);d.rotation.x=-.7,s.addChild(d),e.attachToMesh(s)}return o._setLaserPointerParent(e.mesh),o._meshAttachedObserver=e._meshAttachedObservable.add(function(p){o._setLaserPointerParent(p)}),o}return Object(c.d)(t,r),t.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},t.prototype._activatePointer=function(){r.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},t.prototype._deactivatePointer=function(){r.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},t.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},t.prototype._setLaserPointerLightingDisabled=function(e){this._laserPointer.material.disableLighting=e},t.prototype._setLaserPointerParent=function(e){var n=function(s){s.isPickable=!1,s.getChildMeshes().forEach(function(d){n(d)})};n(e);var i=e.getChildren(void 0,!1),o=e;this.webVRController._pointingPoseNode=null;for(var a=0;a=0){o=i[a],this.webVRController._pointingPoseNode=o;break}this._laserPointer.parent=o},t.prototype._updatePointerDistance=function(e){e===void 0&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},t.prototype.dispose=function(){r.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},t}(nu),iu=function(r){function t(e,n){var i=r.call(this,n)||this;return i.getCamera=e,i}return Object(c.d)(t,r),t.prototype._getForwardRay=function(e){var n=this.getCamera();return n?n.getForwardRay(e):new dn.a(u.e.Zero(),u.e.Forward())},t}(nu),gp=function(){},ru=function(){function r(t,e){var n=this;if(e===void 0&&(e={}),this.webVROptions=e,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new x.c,this.onAfterEnteringVRObservable=new x.c,this.onExitingVRObservable=new x.c,this.onControllerMeshLoadedObservable=new x.c,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=r.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new u.e(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new u.e(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new M.a(.7,.7,.7),this._laserColor=new M.a(.7,.7,.7),this._pickedLaserColor=new M.a(.2,.2,1),this._pickedGazeColor=new M.a(0,0,1),this.onNewMeshSelected=new x.c,this.onMeshSelectedWithController=new x.c,this.onNewMeshPicked=new x.c,this.onBeforeCameraTeleport=new x.c,this.onAfterCameraTeleport=new x.c,this.onSelectedMeshUnselected=new x.c,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=function(){n.moveButtonToBottomRight(),n._fullscreenVRpresenting&&n._webVRready&&n.exitVR()},this._onFullscreenChange=function(){var o=document;o.fullscreen!==void 0?n._fullscreenVRpresenting=document.fullscreen:o.mozFullScreen!==void 0?n._fullscreenVRpresenting=o.mozFullScreen:o.webkitIsFullScreen!==void 0?n._fullscreenVRpresenting=o.webkitIsFullScreen:o.msIsFullScreen!==void 0?n._fullscreenVRpresenting=o.msIsFullScreen:document.msFullscreenElement!==void 0&&(n._fullscreenVRpresenting=document.msFullscreenElement),!n._fullscreenVRpresenting&&n._inputElement&&(n.exitVR(),!n._useCustomVRButton&&n._btnVR&&(n._btnVR.style.top=n._inputElement.offsetTop+n._inputElement.offsetHeight-70+"px",n._btnVR.style.left=n._inputElement.offsetLeft+n._inputElement.offsetWidth-100+"px",n.updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this.beforeRender=function(){n._leftController&&n._leftController._activePointer&&n._castRayAndSelectObject(n._leftController),n._rightController&&n._rightController._activePointer&&n._castRayAndSelectObject(n._rightController),n._noControllerIsActive&&(n._scene.getEngine().isPointerLock||n.enableGazeEvenWhenNoPointerLock)?n._castRayAndSelectObject(n._cameraGazer):n._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(o){if(o.type!==hn.POSE_ENABLED)o.leftStick&&o.onleftstickchanged(function(d){n._teleportationInitialized&&n.teleportationEnabled&&(!n._leftController&&!n._rightController||n._leftController&&!n._leftController._activePointer&&n._rightController&&!n._rightController._activePointer)&&(n._checkTeleportWithRay(d,n._cameraGazer),n._checkTeleportBackwards(d,n._cameraGazer))}),o.rightStick&&o.onrightstickchanged(function(d){n._teleportationInitialized&&n._checkRotate(d,n._cameraGazer)}),o.type===hn.XBOX&&(o.onbuttondown(function(d){n._interactionsEnabled&&d===Cn.A&&n._cameraGazer._selectionPointerDown()}),o.onbuttonup(function(d){n._interactionsEnabled&&d===Cn.A&&n._cameraGazer._selectionPointerUp()}));else{var a=o,s=new mp(a,n._scene,n._cameraGazer._gazeTracker);a.hand==="right"||n._leftController&&n._leftController.webVRController!=a?n._rightController=s:n._leftController=s,n._tryEnableInteractionOnController(s)}},this._tryEnableInteractionOnController=function(o){n._interactionsRequested&&!o._interactionsEnabled&&n._enableInteractionOnController(o),n._teleportationRequested&&!o._teleportationEnabled&&n._enableTeleportationOnController(o)},this._onNewGamepadDisconnected=function(o){o instanceof Ni&&(o.hand==="left"&&n._leftController!=null&&(n._leftController.dispose(),n._leftController=null),o.hand==="right"&&n._rightController!=null&&(n._rightController.dispose(),n._rightController=null))},this._workingVector=u.e.Zero(),this._workingQuaternion=u.b.Identity(),this._workingMatrix=u.a.Identity(),this._scene=t,this._inputElement=t.getEngine().getInputElement(),"getVRDisplays"in navigator||(e.useXR=!0),e.createFallbackVRDeviceOrientationFreeCamera===void 0&&(e.createFallbackVRDeviceOrientationFreeCamera=!0),e.createDeviceOrientationCamera===void 0&&(e.createDeviceOrientationCamera=!0),e.laserToggle===void 0&&(e.laserToggle=!0),e.defaultHeight===void 0&&(e.defaultHeight=1.7),e.useCustomVRButton&&(this._useCustomVRButton=!0,e.customVRButton&&(this._btnVR=e.customVRButton)),e.rayLength&&(this._rayLength=e.rayLength),this._defaultHeight=e.defaultHeight,e.positionScale&&(this._rayLength*=e.positionScale,this._defaultHeight*=e.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new u.e(0,this._defaultHeight,0),e.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Vo("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Ii&&this._scene.activeCamera.rotation)){var i=this._scene.activeCamera;i.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(i.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(u.b.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z)),this._deviceOrientationCamera.rotation=i.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?ys.IsSessionSupportedAsync("immersive-vr").then(function(o){o?(l.a.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),t.createDefaultXRExperienceAsync({floorMeshes:e.floorMeshes||[]}).then(function(a){n.xr=a,n.xrTestDone=!0,n._cameraGazer=new iu(function(){return n.xr.baseExperience.camera},t),n.xr.baseExperience.onStateChangedObservable.add(function(s){switch(s){case fn.ENTERING_XR:n.onEnteringVRObservable.notifyObservers(n),n._interactionsEnabled||n.xr.pointerSelection.detach(),n.xr.pointerSelection.displayLaserPointer=n._displayLaserPointer;break;case fn.EXITING_XR:n.onExitingVRObservable.notifyObservers(n),n._scene.getEngine().resize();break;case fn.IN_XR:n._hasEnteredVR=!0;break;case fn.NOT_IN_XR:n._hasEnteredVR=!1}})})):n.completeVRInit(t,e)}):this.completeVRInit(t,e)}return Object.defineProperty(r.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(t){t&&(t.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(t){t&&(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=t,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")))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"leftControllerGazeTrackerMesh",{get:function(){return this._leftController?this._leftController._gazeTracker:null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"rightControllerGazeTrackerMesh",{get:function(){return this._rightController?this._rightController._gazeTracker:null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(t){this._displayGaze=t,t||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(t){this._displayLaserPointer=t,t?(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))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"vrButton",{get:function(){return this._btnVR},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||this._leftController!==null&&this._leftController._teleportationRequestInitiated||this._rightController!==null&&this._rightController._teleportationRequestInitiated},enumerable:!1,configurable:!0}),r.prototype.completeVRInit=function(t,e){var n=this;if(this.xrTestDone=!0,e.createFallbackVRDeviceOrientationFreeCamera&&(e.useMultiview&&(e.vrDeviceOrientationCameraMetrics||(e.vrDeviceOrientationCameraMetrics=_r.GetDefault()),e.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new Go("VRDeviceOrientationVRHelper",this._position,this._scene,!0,e.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new jo("WebVRHelper",this._position,this._scene,e),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new iu(function(){return n.currentVRCamera},t),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var i=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";i+=".babylonVRicon.vrdisplaypresenting { display: none; }";var o=document.createElement("style");o.appendChild(document.createTextNode(i)),document.getElementsByTagName("head")[0].appendChild(o),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",function(){n.isInVRMode?n._scene.getEngine().disableVR():n.enterVR()});var a=this._scene.getEngine().getHostWindow();a&&(a.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),document.onmsfullscreenchange=this._onFullscreenChange,e.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add(function(s){s.vrDisplay&&n.displayVRButton()}),this._onKeyDown=function(s){s.keyCode===27&&n.isInVRMode&&n.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(function(){n._hasEnteredVR&&n.exitVROnDoubleTap&&(n.exitVR(),n._fullscreenVRpresenting&&n._scene.getEngine().exitFullscreen())},Tt.a.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(s){return n.onVRDisplayChanged(s)},this._onVrDisplayPresentChange=function(){return n.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){n._webVRrequesting=!0,n.updateButtonVisibility()},this._onVRRequestPresentComplete=function(){n._webVRrequesting=!1,n.updateButtonVisibility()},t.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),t.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),t.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),a.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),t.onDisposeObservable.add(function(){n.dispose()}),this._webVRCamera.onControllerMeshLoadedObservable.add(function(s){return n._onDefaultMeshLoaded(s)}),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new it,this._circleEase.setEasingMode(ze.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,t.onPointerObservable.add(function(s){n._interactionsEnabled&&t.activeCamera===n.vrDeviceOrientationCamera&&s.event.pointerType==="mouse"&&(s.type===Tt.a.POINTERDOWN?n._cameraGazer._selectionPointerDown():s.type===Tt.a.POINTERUP&&n._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))},r.prototype._onDefaultMeshLoaded=function(t){this._leftController&&this._leftController.webVRController==t&&t.mesh&&this._leftController._setLaserPointerParent(t.mesh),this._rightController&&this._rightController.webVRController==t&&t.mesh&&this._rightController._setLaserPointerParent(t.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(t)}catch(e){l.a.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}},Object.defineProperty(r.prototype,"isInVRMode",{get:function(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===fn.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!1,configurable:!0}),r.prototype.onVrDisplayPresentChange=function(){var t=this._scene.getEngine().getVRDevice();if(t){var e=this._webVRpresenting;this._webVRpresenting=t.isPresenting,e&&!this._webVRpresenting&&this.exitVR()}else l.a.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},r.prototype.onVRDisplayChanged=function(t){this._webVRsupported=t.vrSupported,this._webVRready=!!t.vrDisplay,this._webVRpresenting=t.vrDisplay&&t.vrDisplay.isPresenting,this.updateButtonVisibility()},r.prototype.moveButtonToBottomRight=function(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){var t=this._inputElement.getBoundingClientRect();this._btnVR.style.top=t.top+t.height-70+"px",this._btnVR.style.left=t.left+t.width-100+"px"}},r.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},r.prototype.updateButtonVisibility=function(){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")))},r.prototype.enterVR=function(){var t=this;if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(o){l.a.Warn("Error in your custom logic onEnteringVR: "+o)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=u.b.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){var e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,n=u.b.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-e,i=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=u.b.FromEulerAngles(0,i+n,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(function(o){t.onAfterEnteringVRObservable.notifyObservers({success:o})}),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(function(){t.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(function(o){o&&o._activatePointer()}),this._hasEnteredVR=!0)}},r.prototype.exitVR=function(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){l.a.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(function(e){e&&e._deactivatePointer()}),this._hasEnteredVR=!1;var t=this._scene.getEngine();t._onVrDisplayPresentChange&&t._onVrDisplayPresentChange()}},Object.defineProperty(r.prototype,"position",{get:function(){return this._position},set:function(t){this._position=t,this._scene.activeCamera&&(this._scene.activeCamera.position=t)},enumerable:!1,configurable:!0}),r.prototype.enableInteractions=function(){var t=this;if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr)return void(this.xr.baseExperience.state===fn.IN_XR&&this.xr.pointerSelection.attach());this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=function(e){return e.isVisible&&(e.isPickable||e.name===t._floorMeshName)},this.meshSelectionPredicate=function(){return!0},this._raySelectionPredicate=function(e){return!!(t._isTeleportationFloor(e)||e.name.indexOf("gazeTracker")===-1&&e.name.indexOf("teleportationTarget")===-1&&e.name.indexOf("torusTeleportation")===-1)&&t.raySelectionPredicate(e)},this._interactionsEnabled=!0}},Object.defineProperty(r.prototype,"_noControllerIsActive",{get:function(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)},enumerable:!1,configurable:!0}),r.prototype._isTeleportationFloor=function(t){for(var e=0;e-1||this._floorMeshesCollection.push(t))},r.prototype.removeFloorMesh=function(t){if(this._floorMeshesCollection){var e=this._floorMeshesCollection.indexOf(t);e!==-1&&this._floorMeshesCollection.splice(e,1)}},r.prototype.enableTeleportation=function(t){var e=this;if(t===void 0&&(t={}),!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(t.floorMeshes||t.floorMeshName)){var n=t.floorMeshes||[];if(!n.length){var i=this._scene.getMeshByName(t.floorMeshName);i&&n.push(i)}if(this.xr)return n.forEach(function(s){e.xr.teleportation.addFloorMesh(s)}),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){var o=function(){e.xrTestDone&&(e._scene.unregisterBeforeRender(o),e.xr?e.xr.teleportation.attached||e.xr.teleportation.attach():e.enableTeleportation(t))};return void this._scene.registerBeforeRender(o)}}t.floorMeshName&&(this._floorMeshName=t.floorMeshName),t.floorMeshes&&(this._floorMeshesCollection=t.floorMeshes),t.teleportationMode&&(this._teleportationMode=t.teleportationMode),t.teleportationTime&&t.teleportationTime>0&&(this._teleportationTime=t.teleportationTime),t.teleportationSpeed&&t.teleportationSpeed>0&&(this._teleportationSpeed=t.teleportationSpeed),t.easingFunction!==void 0&&(this._teleportationEasing=t.easingFunction),this._leftController!=null&&this._enableTeleportationOnController(this._leftController),this._rightController!=null&&this._enableTeleportationOnController(this._rightController);var a=new vn.a;a.vignetteColor=new M.b(0,0,0,0),a.vignetteEnabled=!0,this._postProcessMove=new Ho("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,a),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},r.prototype._enableInteractionOnController=function(t){var e=this;t.webVRController.mesh&&(t._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&t._activatePointer(),this.webVROptions.laserToggle&&t.webVRController.onMainButtonStateChangedObservable.add(function(n){e._displayLaserPointer&&n.value===1&&(t._activePointer?t._deactivatePointer():t._activatePointer(),e.displayGaze&&(t._gazeTracker.isVisible=t._activePointer))}),t.webVRController.onTriggerStateChangedObservable.add(function(n){var i=t;e._noControllerIsActive&&(i=e._cameraGazer),i._pointerDownOnMeshAsked?n.valuee._padSensibilityUp&&i._selectionPointerDown()}))},r.prototype._checkTeleportWithRay=function(t,e){this._teleportationRequestInitiated&&!e._teleportationRequestInitiated||(e._teleportationRequestInitiated?Math.sqrt(t.y*t.y+t.x*t.x)-this._padSensibilityDown&&(e._rotationLeftAsked=!1):t.x<-this._padSensibilityUp&&e._dpadPressed&&(e._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),e._rotationRightAsked?t.xthis._padSensibilityUp&&e._dpadPressed&&(e._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},r.prototype._checkTeleportBackwards=function(t,e){if(!e._teleportationRequestInitiated)if(t.y>this._padSensibilityUp&&e._dpadPressed){if(!e._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var n=u.b.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(n=this.currentVRCamera.deviceRotationQuaternion,i=this.currentVRCamera.devicePosition),n.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,u.b.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),u.e.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var o=new dn.a(i,this._workingVector),a=this._scene.pickWithRay(o,this._raySelectionPredicate);a&&a.pickedPoint&&a.pickedMesh&&this._isTeleportationFloor(a.pickedMesh)&&a.distance<5&&this.teleportCamera(a.pickedPoint),e._teleportationBackRequestInitiated=!0}}else e._teleportationBackRequestInitiated=!1},r.prototype._enableTeleportationOnController=function(t){var e=this;t.webVRController.mesh&&(t._interactionsEnabled||this._enableInteractionOnController(t),t._interactionsEnabled=!0,t._teleportationEnabled=!0,t.webVRController.controllerType===ei.VIVE&&(t._dpadPressed=!1,t.webVRController.onPadStateChangedObservable.add(function(n){t._dpadPressed=n.pressed,t._dpadPressed||(t._rotationLeftAsked=!1,t._rotationRightAsked=!1,t._teleportationBackRequestInitiated=!1)})),t.webVRController.onPadValuesChangedObservable.add(function(n){e.teleportationEnabled&&(e._checkTeleportBackwards(n,t),e._checkTeleportWithRay(n,t)),e._checkRotate(n,t)}))},r.prototype._createTeleportationCircles=function(){this._teleportationTarget=De.a.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var t=new yi.a("DynamicTexture",512,this._scene,!0);t.hasAlpha=!0;var e=t.getContext();e.beginPath(),e.arc(256,256,200,0,2*Math.PI,!1),e.fillStyle=this._teleportationFillColor,e.fill(),e.lineWidth=10,e.strokeStyle=this._teleportationBorderColor,e.stroke(),e.closePath(),t.update();var n=new Ft.a("TextPlaneMaterial",this._scene);n.diffuseTexture=t,this._teleportationTarget.material=n;var i=De.a.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);i.isPickable=!1,i.parent=this._teleportationTarget;var o=new k("animationInnerCircle","position.y",30,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CYCLE),a=[];a.push({frame:0,value:0}),a.push({frame:30,value:.4}),a.push({frame:60,value:0}),o.setKeys(a);var s=new on;s.setEasingMode(ze.EASINGMODE_EASEINOUT),o.setEasingFunction(s),i.animations=[],i.animations.push(o),this._scene.beginAnimation(i,0,60,!0),this._hideTeleportationTarget()},r.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},r.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},r.prototype._rotateCamera=function(t){var e=this;if(this.currentVRCamera instanceof Hn){t?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var n=u.b.FromRotationMatrix(u.a.RotationY(Math.PI/4*this._rotationAngle)),i=new k("animationRotation","rotationQuaternion",90,k.ANIMATIONTYPE_QUATERNION,k.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),o.push({frame:6,value:n}),i.setKeys(o),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];var a=new k("animationPP","vignetteWeight",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:3,value:4}),s.push({frame:6,value:0}),a.setKeys(s),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a);var d=new k("animationPP2","vignetteStretch",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),p=[];p.push({frame:0,value:0}),p.push({frame:3,value:10}),p.push({frame:6,value:0}),d.setKeys(p),d.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(d),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,function(){e._webVRCamera.detachPostProcess(e._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},r.prototype._moveTeleportationSelectorTo=function(t,e,n){if(t.pickedPoint){e._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(t.pickedPoint),this._teleportationTarget.position.copyFrom(t.pickedPoint));var i=this._convertNormalToDirectionOfRay(t.getNormal(!0,!1),n);if(i){var o=u.e.Cross(ye.a.Y,i),a=u.e.Cross(i,o);u.e.RotationFromAxisToRef(a,i,o,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},r.prototype.teleportCamera=function(t){var e=this;if(this.currentVRCamera instanceof Hn){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),t.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(t),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector);var n,i;if(this._teleportationMode==r.TELEPORTATIONMODE_CONSTANTSPEED){i=90;var o=u.e.Distance(this.currentVRCamera.position,this._workingVector);n=this._teleportationSpeed/o}else i=Math.round(90*this._teleportationTime/1e3),n=1;this.currentVRCamera.animations=[];var a=new k("animationCameraTeleportation","position",90,k.ANIMATIONTYPE_VECTOR3,k.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];a.setKeys(s),a.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(a),this._postProcessMove.animations=[];var d=Math.round(i/2),p=new k("animationPP","vignetteWeight",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),y=[];y.push({frame:0,value:0}),y.push({frame:d,value:8}),y.push({frame:i,value:0}),p.setKeys(y),this._postProcessMove.animations.push(p);var P=new k("animationPP2","vignetteStretch",90,k.ANIMATIONTYPE_FLOAT,k.ANIMATIONLOOPMODE_CONSTANT),O=[];O.push({frame:0,value:0}),O.push({frame:d,value:10}),O.push({frame:i,value:0}),P.setKeys(O),this._postProcessMove.animations.push(P),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,i,!1,n,function(){e._webVRCamera.detachPostProcess(e._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,i,!1,n,function(){e.onAfterCameraTeleport.notifyObservers(e._workingVector)}),this._hideTeleportationTarget()}},r.prototype._convertNormalToDirectionOfRay=function(t,e){return t&&Math.acos(u.e.Dot(t,e.direction))s){var d=s;s=a,a=d}return a>0&&a0&&s=0))},r.prototype._canDoCollision=function(t,e,n,i){var o=u.e.Distance(this._basePointWorld,t),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(o>this._velocityWorldLength+a+e)&&!!function(s,d,p,y){return!(s.x>p.x+y)&&!(p.x-y>d.x)&&!(s.y>p.y+y)&&!(p.y-y>d.y)&&!(s.z>p.z+y)&&!(p.z-y>d.z)}(n,i,this._basePointWorld,this._velocityWorldLength+a)},r.prototype._testTriangle=function(t,e,n,i,o,a,s){var d,p=!1;e||(e=[]),e[t]||(e[t]=new gr.a(0,0,0,0),e[t].copyFromPoints(n,i,o));var y=e[t];if(a||y.isFrontFacingTo(this._normalizedVelocity,0)){var P=y.signedDistanceTo(this._basePoint),O=u.e.Dot(y.normal,this._velocity);if(O==0){if(Math.abs(P)>=1)return;p=!0,d=0}else{var U=(1-P)/O;if((d=(-1-P)/O)>U){var F=U;U=d,d=F}if(d>1||U<0)return;d<0&&(d=0),d>1&&(d=1)}this._collisionPoint.copyFromFloats(0,0,0);var z=!1,J=1;if(p||(this._basePoint.subtractToRef(y.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(d,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,i,o,y.normal)&&(z=!0,J=d,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!z){var ie=this._velocity.lengthSquared(),se=ie;this._basePoint.subtractToRef(n,this._tempVector);var ce=2*u.e.Dot(this._velocity,this._tempVector),ue=this._tempVector.lengthSquared()-1,fe=vr(se,ce,ue,J);fe.found&&(J=fe.root,z=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(i,this._tempVector),ce=2*u.e.Dot(this._velocity,this._tempVector),ue=this._tempVector.lengthSquared()-1,(fe=vr(se,ce,ue,J)).found&&(J=fe.root,z=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(o,this._tempVector),ce=2*u.e.Dot(this._velocity,this._tempVector),ue=this._tempVector.lengthSquared()-1,(fe=vr(se,ce,ue,J)).found&&(J=fe.root,z=!0,this._collisionPoint.copyFrom(o)),i.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex);var ve=this._edge.lengthSquared(),Te=u.e.Dot(this._edge,this._velocity),Oe=u.e.Dot(this._edge,this._baseToVertex);if(se=ve*-ie+Te*Te,ce=ve*(2*u.e.Dot(this._velocity,this._baseToVertex))-2*Te*Oe,ue=ve*(1-this._baseToVertex.lengthSquared())+Oe*Oe,(fe=vr(se,ce,ue,J)).found){var Pe=(Te*fe.root-Oe)/ve;Pe>=0&&Pe<=1&&(J=fe.root,z=!0,this._edge.scaleInPlace(Pe),n.addToRef(this._edge,this._collisionPoint))}o.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex),ve=this._edge.lengthSquared(),Te=u.e.Dot(this._edge,this._velocity),Oe=u.e.Dot(this._edge,this._baseToVertex),se=ve*-ie+Te*Te,ce=ve*(2*u.e.Dot(this._velocity,this._baseToVertex))-2*Te*Oe,ue=ve*(1-this._baseToVertex.lengthSquared())+Oe*Oe,(fe=vr(se,ce,ue,J)).found&&(Pe=(Te*fe.root-Oe)/ve)>=0&&Pe<=1&&(J=fe.root,z=!0,this._edge.scaleInPlace(Pe),i.addToRef(this._edge,this._collisionPoint)),n.subtractToRef(o,this._edge),o.subtractToRef(this._basePoint,this._baseToVertex),ve=this._edge.lengthSquared(),Te=u.e.Dot(this._edge,this._velocity),Oe=u.e.Dot(this._edge,this._baseToVertex),se=ve*-ie+Te*Te,ce=ve*(2*u.e.Dot(this._velocity,this._baseToVertex))-2*Te*Oe,ue=ve*(1-this._baseToVertex.lengthSquared())+Oe*Oe,(fe=vr(se,ce,ue,J)).found&&(Pe=(Te*fe.root-Oe)/ve)>=0&&Pe<=1&&(J=fe.root,z=!0,this._edge.scaleInPlace(Pe),o.addToRef(this._edge,this._collisionPoint))}if(z){var Ee=J*this._velocity.length();(!this.collisionFound||Ee=i)o.copyFrom(t);else{var d=a?a.collisionMask:n.collisionMask;n._initialize(t,e,s);for(var p=a&&a.surroundingMeshes||this._scene.meshes,y=0;ythis.capacity&&this._depth-1&&this.entries.splice(n,1)}},r.prototype.addEntries=function(t){for(var e=0;e=i.buttons.length?o[n]=i.axes[n-i.buttons.length].valueOf():o[n]=i.buttons[n].value}},r.prototype._getGamepadDeviceType=function(t){return t.indexOf("054c")!==-1?Kt.DualShock:t.indexOf("Xbox One")!==-1||t.search("Xbox 360")!==-1||t.search("xinput")!==-1?Kt.Xbox:t.indexOf("057e")!==-1?Kt.Switch:Kt.Generic},r._MAX_KEYCODES=255,r._MAX_POINTER_INPUTS=7,r}(),uu=function(){function r(t,e,n){n===void 0&&(n=0),this.deviceType=e,this.deviceSlot=n,this.onInputChangedObservable=new x.c,this._deviceInputSystem=t}return r.prototype.getInput=function(t){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,t)},r}(),yp=function(){function r(t){var e=this;this.onDeviceConnectedObservable=new x.c(function(i){e.getDevices().forEach(function(o){e.onDeviceConnectedObservable.notifyObserver(i,o)})}),this.onDeviceDisconnectedObservable=new x.c;var n=Object.keys(Kt).length/2;this._devices=new Array(n),this._firstDevice=new Array(n),this._deviceInputSystem=lu.Create(t),this._deviceInputSystem.onDeviceConnected=function(i,o){e._addDevice(i,o),e.onDeviceConnectedObservable.notifyObservers(e.getDeviceSource(i,o))},this._deviceInputSystem.onDeviceDisconnected=function(i,o){var a=e.getDeviceSource(i,o);e._removeDevice(i,o),e.onDeviceDisconnectedObservable.notifyObservers(a)},this._deviceInputSystem.onInputChanged||(this._deviceInputSystem.onInputChanged=function(i,o,a,s,d){var p;(p=e.getDeviceSource(i,o))===null||p===void 0||p.onInputChangedObservable.notifyObservers({inputIndex:a,previousState:s,currentState:d})})}return r.prototype.getDeviceSource=function(t,e){if(e===void 0){if(this._firstDevice[t]===void 0)return null;e=this._firstDevice[t]}return this._devices[t]&&this._devices[t][e]!==void 0?this._devices[t][e]:null},r.prototype.getDeviceSources=function(t){return this._devices[t].filter(function(e){return!!e})},r.prototype.getDevices=function(){var t=new Array;return this._devices.forEach(function(e){t.push.apply(t,e)}),t},r.prototype.dispose=function(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._deviceInputSystem.dispose()},r.prototype._addDevice=function(t,e){this._devices[t]||(this._devices[t]=new Array),this._devices[t][e]||(this._devices[t][e]=new uu(this._deviceInputSystem,t,e),this._updateFirstDevices(t))},r.prototype._removeDevice=function(t,e){delete this._devices[t][e],this._updateFirstDevices(t)},r.prototype._updateFirstDevices=function(t){switch(t){case Kt.Keyboard:case Kt.Mouse:this._firstDevice[t]=0;break;case Kt.Touch:case Kt.DualShock:case Kt.Xbox:case Kt.Switch:case Kt.Generic:var e=this._devices[t];delete this._firstDevice[t];for(var n=0;nr.occlusionRetryCount))return!1;r.isOcclusionQueryInProgress=!1,r.occlusionInternalRetryCounter=0,r.isOccluded=r.occlusionType!==Dt.a.OCCLUSION_TYPE_OPTIMISTIC&&r.isOccluded}var n=this.getScene();if(n.getBoundingBoxRenderer){var i=n.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(r.occlusionQueryAlgorithmType,this._occlusionQuery),i.renderOcclusionBoundingBox(this),t.endOcclusionQuery(r.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0}return r.isOccluded};var Tp=!0;Ue.a.prototype.createTransformFeedback=function(){return this._gl.createTransformFeedback()},Ue.a.prototype.deleteTransformFeedback=function(r){this._gl.deleteTransformFeedback(r)},Ue.a.prototype.bindTransformFeedback=function(r){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,r)},Ue.a.prototype.beginTransformFeedback=function(r){r===void 0&&(r=!0),this._gl.beginTransformFeedback(r?this._gl.POINTS:this._gl.TRIANGLES)},Ue.a.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},Ue.a.prototype.setTranformFeedbackVaryings=function(r,t){this._gl.transformFeedbackVaryings(r,t,this._gl.INTERLEAVED_ATTRIBS)},Ue.a.prototype.bindTransformFeedbackBuffer=function(r){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,r?r.underlyingResource:null)},f(126),Bt.a.prototype.updateVideoTexture=function(r,t,e){if(r&&!r._isDisabled){var n=this._bindTextureDirectly(this._gl.TEXTURE_2D,r,!0);this._unpackFlipY(!e);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),this._gl.getError()!==0?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!r._workingCanvas){r._workingCanvas=vs.a.CreateCanvas(r.width,r.height);var i=r._workingCanvas.getContext("2d");if(!i)throw new Error("Unable to get 2d context");r._workingContext=i,r._workingCanvas.width=r.width,r._workingCanvas.height=r.height}r._workingContext.clearRect(0,0,r.width,r.height),r._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,r.width,r.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,r._workingCanvas)}r.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r.isReady=!0}catch{r._isDisabled=!0}}},Bt.a.prototype.restoreSingleAttachment=function(){var r=this._gl;this.bindAttachments([r.BACK])},Bt.a.prototype.buildTextureLayout=function(r){for(var t=this._gl,e=[],n=0;n1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],n.readBuffer(i[a]),n.drawBuffers(i),n.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,n.COLOR_BUFFER_BIT,n.NEAREST)}for(a=0;a1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];n.drawBuffers(i)}for(a=0;a1?"COLOR_ATTACHMENT"+se:"COLOR_ATTACHMENT"+se+"_WEBGL"];z.push(ve),J.push(Te),P.activeTexture(P["TEXTURE"+se]),P.bindTexture(P.TEXTURE_2D,ve._webGLTexture),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MAG_FILTER,fe.mag),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MIN_FILTER,fe.min),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_S,P.CLAMP_TO_EDGE),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_T,P.CLAMP_TO_EDGE),P.texImage2D(P.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(ue),U,F,0,P.RGBA,this._getWebGLTextureType(ue),null),P.framebufferTexture2D(P.DRAW_FRAMEBUFFER,Te,P.TEXTURE_2D,ve._webGLTexture,0),e&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(P.TEXTURE_2D,null),ve._framebuffer=O,ve._depthStencilBuffer=ie,ve.baseWidth=U,ve.baseHeight=F,ve.width=U,ve.height=F,ve.isReady=!0,ve.samples=1,ve.generateMipMaps=e,ve.samplingMode=ce,ve.type=ue,ve._generateDepthBuffer=n,ve._generateStencilBuffer=i,ve._attachments=J,ve._textureArray=z,this._internalTexturesCache.push(ve)}if(o&&this._caps.depthTextureExtension){var Oe=new xt.a(this,xt.b.MultiRenderTarget);P.activeTexture(P.TEXTURE0),P.bindTexture(P.TEXTURE_2D,Oe._webGLTexture),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MAG_FILTER,P.NEAREST),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MIN_FILTER,P.NEAREST),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_S,P.CLAMP_TO_EDGE),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_T,P.CLAMP_TO_EDGE),P.texImage2D(P.TEXTURE_2D,0,this.webGLVersion<2?P.DEPTH_COMPONENT:P.DEPTH_COMPONENT16,U,F,0,P.DEPTH_COMPONENT,P.UNSIGNED_SHORT,null),P.framebufferTexture2D(P.FRAMEBUFFER,P.DEPTH_ATTACHMENT,P.TEXTURE_2D,Oe._webGLTexture,0),Oe._framebuffer=O,Oe.baseWidth=U,Oe.baseHeight=F,Oe.width=U,Oe.height=F,Oe.isReady=!0,Oe.samples=1,Oe.generateMipMaps=e,Oe.samplingMode=P.NEAREST,Oe._generateDepthBuffer=n,Oe._generateStencilBuffer=i,z.push(Oe),this._internalTexturesCache.push(Oe)}return P.drawBuffers(J),this._bindUnboundFramebuffer(null),this.resetTextureCache(),z},Bt.a.prototype.updateMultipleRenderTargetTextureSampleCount=function(r,t){if(this.webGLVersion<2||!r)return 1;if(r[0].samples===t)return t;var e=r[0]._attachments.length;if(e===0)return 1;var n=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),r[0]._depthStencilBuffer&&(n.deleteRenderbuffer(r[0]._depthStencilBuffer),r[0]._depthStencilBuffer=null),r[0]._MSAAFramebuffer&&(n.deleteFramebuffer(r[0]._MSAAFramebuffer),r[0]._MSAAFramebuffer=null);for(var i=0;i1&&n.renderbufferStorageMultisample){var o=n.createFramebuffer();if(!o)throw new Error("Unable to create multi sampled framebuffer");this._bindUnboundFramebuffer(o);var a=this._setupFramebufferDepthAttachments(r[0]._generateStencilBuffer,r[0]._generateDepthBuffer,r[0].width,r[0].height,t),s=[];for(i=0;i1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],y=n.createRenderbuffer();if(!y)throw new Error("Unable to create multi sampled framebuffer");n.bindRenderbuffer(n.RENDERBUFFER,y),n.renderbufferStorageMultisample(n.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(d.type),d.width,d.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,p,n.RENDERBUFFER,y),d._MSAAFramebuffer=o,d._MSAARenderBuffer=y,d.samples=t,d._depthStencilBuffer=a,n.bindRenderbuffer(n.RENDERBUFFER,null),s.push(p)}n.drawBuffers(s)}else this._bindUnboundFramebuffer(r[0]._framebuffer);return this._bindUnboundFramebuffer(null),t};var no=f(56);Bt.a.prototype._createDepthStencilCubeTexture=function(r,t){var e=new xt.a(this,xt.b.Unknown);if(e.isCube=!0,this.webGLVersion===1)return l.a.Error("Depth cube texture is not supported by WebGL 1."),e;var n=Object(c.a)({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),this._setupDepthStencilTexture(e,r,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var o=0;o<6;o++)n.generateStencil?i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,i.DEPTH24_STENCIL8,r,r,0,i.DEPTH_STENCIL,i.UNSIGNED_INT_24_8,null):i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,i.DEPTH_COMPONENT24,r,r,0,i.DEPTH_COMPONENT,i.UNSIGNED_INT,null);return this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null),e},Bt.a.prototype._partialLoadFile=function(r,t,e,n,i){i===void 0&&(i=null),this._loadFile(r,function(o){e[t]=o,e._internalCount++,e._internalCount===6&&n(e)},void 0,void 0,!0,function(o,a){i&&o&&i(o.status+" "+o.statusText,a)})},Bt.a.prototype._cascadeLoadFiles=function(r,t,e,n){n===void 0&&(n=null);var i=[];i._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(e[o],o,i,t,n)},Bt.a.prototype._cascadeLoadImgs=function(r,t,e,n,i){n===void 0&&(n=null);var o=[];o._internalCount=0;for(var a=0;a<6;a++)this._partialLoadImg(e[a],a,o,r,t,n,i)},Bt.a.prototype._partialLoadImg=function(r,t,e,n,i,o,a){var s;o===void 0&&(o=null),s=no.a.LoadImage(r,function(){s&&(e[t]=s,e._internalCount++,n&&n._removePendingData(s)),e._internalCount===6&&i(e)},function(d,p){n&&n._removePendingData(s),o&&o(d,p)},n?n.offlineProvider:null,a),n&&s&&n._addPendingData(s)},Bt.a.prototype._setCubeMapTextureParams=function(r,t){var e=this._gl;e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.LINEAR),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_CUBE_MAP,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r.samplingMode=t?h.a.TEXTURE_TRILINEAR_SAMPLINGMODE:h.a.TEXTURE_LINEAR_LINEAR,this._bindTextureDirectly(e.TEXTURE_CUBE_MAP,null)},Bt.a.prototype.createCubeTexture=function(r,t,e,n,i,o,a,s,d,p,y,P,O){var U=this;i===void 0&&(i=null),o===void 0&&(o=null),s===void 0&&(s=null),d===void 0&&(d=!1),p===void 0&&(p=0),y===void 0&&(y=0),P===void 0&&(P=null);var F=this._gl,z=P||new xt.a(this,xt.b.Cube);z.isCube=!0,z.url=r,z.generateMipMaps=!n,z._lodGenerationScale=p,z._lodGenerationOffset=y,this._doNotHandleContextLost||(z._extension=s,z._files=e);var J=r;this._transformTextureUrl&&!P&&(r=this._transformTextureUrl(r));for(var ie=r.lastIndexOf("."),se=s||(ie>-1?r.substring(ie).toLowerCase():""),ce=null,ue=0,fe=Bt.a._TextureLoaders;ue-1?r.substring(e,r.length):"";return(t>-1?r.substring(0,t):r)+this._textureFormatInUse+n}Object.defineProperty(Ue.a.prototype,"texturesSupported",{get:function(){var r=new Array;return this._caps.astc&&r.push("-astc.ktx"),this._caps.s3tc&&r.push("-dxt.ktx"),this._caps.pvrtc&&r.push("-pvrtc.ktx"),this._caps.etc2&&r.push("-etc2.ktx"),this._caps.etc1&&r.push("-etc1.ktx"),r},enumerable:!0,configurable:!0}),Object.defineProperty(Ue.a.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),Ue.a.prototype.setCompressedTextureExclusions=function(r){this._excludedCompressedTextures=r},Ue.a.prototype.setTextureFormatToUse=function(r){for(var t=this.texturesSupported,e=0,n=t.length;e -void main(void) -{ -gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb); -}`;je.a.ShadersStore.rgbdEncodePixelShader=Cp;var xp=` -varying vec2 vUV; -uniform sampler2D textureSampler; -#include -void main(void) -{ -gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0); -}`;je.a.ShadersStore.rgbdDecodePixelShader=xp;var Si=function(){function r(){}return r.GetEnvInfo=function(t){for(var e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=0,i=0;i"u")Ke=createImageBitmap(Ie).then(function(rt){return n._OnImageReadyAsync(rt,o,a,d,Fe,xe,Ee,s,y,p,t)});else{var nt=new Image;nt.src=Fe,Ke=new Promise(function(rt,ut){nt.onload=function(){n._OnImageReadyAsync(nt,o,a,d,Fe,xe,Ee,s,y,p,t).then(function(){return rt()}).catch(function(qe){ut(qe)})},nt.onerror=function(qe){ut(qe)}})}ue.push(Ke)},Le=0;Le<6;Le++)Se(Le)};for(F=0;F=0&&F.push(J.substring(ie+1))}a!=="void"&&F.push("return"),this._functionDescr.push({name:s,type:a,parameters:F,body:O,callIndex:0}),t=P+1;var se=e>0?this._sourceCode.substring(0,e):"",ce=P+1=0},r.prototype._extractBetweenMarkers=function(t,e,n,i){for(var o=i,a=0,s="";o0?this._sourceCode.substring(0,y):"",fe=O+1"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(){}),e._shaderProcessor=new pu.a,e}return Object(c.d)(t,r),t.prototype.getHardwareScalingLevel=function(){return 1},t.prototype.dispose=function(){r.prototype.dispose.call(this),this._boundBuffersVertexArray&&this._native.deleteVertexArray(this._boundBuffersVertexArray),this._native.dispose()},t.prototype._queueNewFrame=function(e,n){return n.requestAnimationFrame&&n!==window?n.requestAnimationFrame(e):this._native.requestAnimationFrame(e),0},t.prototype._bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&this._native.unbindFramebuffer(this._currentFramebuffer),e&&this._native.bindFramebuffer(e),this._currentFramebuffer=e)},t.prototype.getHostDocument=function(){return null},t.prototype.clear=function(e,n,i,o){o===void 0&&(o=!1);var a=0;n&&e&&(this._native.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),a|=this._native.CLEAR_FLAG_COLOR),i&&(this._native.clearDepth(1),a|=this._native.CLEAR_FLAG_DEPTH),o&&(this._native.clearStencil(0),a|=this._native.CLEAR_FLAG_STENCIL),this._native.clear(a)},t.prototype.createIndexBuffer=function(e,n){var i=this._normalizeIndexData(e),o=new mu;if(o.references=1,o.is32Bits=i.BYTES_PER_ELEMENT===4,i.length){if(o.nativeIndexBuffer=this._native.createIndexBuffer(i,n!=null&&n),o.nativeVertexBuffer===this.INVALID_HANDLE)throw new Error("Could not create a native index buffer.")}else o.nativeVertexBuffer=this.INVALID_HANDLE;return o},t.prototype.createVertexBuffer=function(e,n){var i=new mu;if(i.references=1,i.nativeVertexBuffer=this._native.createVertexBuffer(ArrayBuffer.isView(e)?e:new Float32Array(e),n!=null&&n),i.nativeVertexBuffer===this.INVALID_HANDLE)throw new Error("Could not create a native vertex buffer.");return i},t.prototype._recordVertexArrayObject=function(e,n,i,o){i&&this._native.recordIndexBuffer(e,i.nativeIndexBuffer);for(var a=o.getAttributesNames(),s=0;s=0){var p=n[a[s]];if(p){var y=p.getBuffer();y&&this._native.recordVertexBuffer(e,y.nativeVertexBuffer,d,p.byteOffset,p.byteStride,p.getSize(),this._getNativeAttribType(p.type),p.normalized)}}}},t.prototype.bindBuffers=function(e,n,i){this._boundBuffersVertexArray&&this._native.deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._native.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,n,i),this._native.bindVertexArray(this._boundBuffersVertexArray)},t.prototype.recordVertexArrayObject=function(e,n,i){var o=this._native.createVertexArray();return this._recordVertexArrayObject(o,e,n,i),o},t.prototype.bindVertexArrayObject=function(e){this._native.bindVertexArray(e)},t.prototype.releaseVertexArrayObject=function(e){this._native.deleteVertexArray(e)},t.prototype.getAttributes=function(e,n){var i=e;return this._native.getAttributes(i.nativeProgram,n)},t.prototype.drawElementsType=function(e,n,i,o){this._drawCalls.addCount(1,!1),this._native.drawIndexed(e,n,i)},t.prototype.drawArraysType=function(e,n,i,o){this._drawCalls.addCount(1,!1),this._native.draw(e,n,i)},t.prototype.createPipelineContext=function(){return new Rp},t.prototype._preparePipelineContext=function(e,n,i,o,a,s,d){var p=e;p.nativeProgram=o?this.createRawShaderProgram(e,n,i,void 0,d):this.createShaderProgram(e,n,i,s,void 0,d)},t.prototype._isRenderingStateCompiled=function(e){return!0},t.prototype._executeWhenRenderingStateIsCompiled=function(e,n){n()},t.prototype.createRawShaderProgram=function(e,n,i,o,a){throw new Error("Not Supported")},t.prototype.createShaderProgram=function(e,n,i,o,a,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);var d=new Rs(n);d.processCode(),n=d.code;var p=new Rs(i);p.processCode(),i=p.code,n=Bt.a._ConcatenateShader(n,o),i=Bt.a._ConcatenateShader(i,o);var y=this._native.createProgram(n,i);return this.onAfterShaderCompilationObservable.notifyObservers(this),y},t.prototype._setProgram=function(e){this._currentProgram!==e&&(this._native.setProgram(e),this._currentProgram=e)},t.prototype._releaseEffect=function(e){},t.prototype._deletePipelineContext=function(e){},t.prototype.getUniforms=function(e,n){var i=e;return this._native.getUniforms(i.nativeProgram,n)},t.prototype.bindUniformBlock=function(e,n,i){throw new Error("Not Implemented")},t.prototype.bindSamplers=function(e){var n=e.getPipelineContext();this._setProgram(n.nativeProgram);for(var i=e.getSamplers(),o=0;o-1?e.substring(ue).toLowerCase():""),ve=null,Te=0,Oe=Ue.a._TextureLoaders;Te-1?e.substring(J).toLowerCase():""))===".env"){if(i&&i.length===6)throw new Error("Multi-file loading not allowed on env files.");this._loadFile(e,function(se){return function(ce){var ue=Si.GetEnvInfo(ce);if(z.width=ue.width,z.height=ue.width,Si.UploadEnvSpherical(z,ue),ue.version!==1)throw new Error('Unsupported babylon environment map version "'+ue.version+'"');var fe=ue.specular;if(!fe)throw new Error("Nothing else parsed so far");z._lodGenerationScale=fe.lodGenerationScale;var ve=Si.CreateImageDataArrayBufferViews(ce,ue);z.format=h.a.TEXTUREFORMAT_RGBA,z.type=h.a.TEXTURETYPE_UNSIGNED_INT,z.generateMipMaps=!0,z.getEngine().updateTextureSamplingMode(we.a.TRILINEAR_SAMPLINGMODE,z),z._isRGBD=!0,z.invertY=!0,F._native.loadCubeTextureWithMips(z._webGLTexture,ve,function(){z.isReady=!0,a&&a()},function(){throw new Error("Could not load a native cube texture.")})}(new Uint8Array(se))},void 0,void 0,!0,function(se,ce){s&&se&&s(se.status+" "+se.statusText,ce)})}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");var ie=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(ie.map(function(se){return Ye.b.LoadFileAsync(se).then(function(ce){return new Uint8Array(ce)})})).then(function(se){return new Promise(function(ce,ue){F._native.loadCubeTexture(z._webGLTexture,se,!o,ce,ue)})}).then(function(){z.isReady=!0,a&&a()},function(se){s&&s("Failed to load cubemap: "+se.message,se)})}return this._internalTexturesCache.push(z),z},t.prototype.createRenderTargetTexture=function(e,n){var i=new kl.a;n!==void 0&&typeof n=="object"?(i.generateMipMaps=n.generateMipMaps,i.generateDepthBuffer=n.generateDepthBuffer===void 0||n.generateDepthBuffer,i.generateStencilBuffer=i.generateDepthBuffer&&n.generateStencilBuffer,i.type=n.type===void 0?h.a.TEXTURETYPE_UNSIGNED_INT:n.type,i.samplingMode=n.samplingMode===void 0?h.a.TEXTURE_TRILINEAR_SAMPLINGMODE:n.samplingMode,i.format=n.format===void 0?h.a.TEXTUREFORMAT_RGBA:n.format):(i.generateMipMaps=n,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.type=h.a.TEXTURETYPE_UNSIGNED_INT,i.samplingMode=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE,i.format=h.a.TEXTUREFORMAT_RGBA),(i.type!==h.a.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(i.type!==h.a.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(i.samplingMode=h.a.TEXTURE_NEAREST_SAMPLINGMODE);var o=new gu(this,xt.b.RenderTarget),a=e.width||e,s=e.height||e;i.type!==h.a.TEXTURETYPE_FLOAT||this._caps.textureFloat||(i.type=h.a.TEXTURETYPE_UNSIGNED_INT,l.a.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"));var d=this._native.createFramebuffer(o._webGLTexture,a,s,this._getNativeTextureFormat(i.format,i.type),i.samplingMode,!!i.generateStencilBuffer,i.generateDepthBuffer,!!i.generateMipMaps);return o._framebuffer=d,o.baseWidth=a,o.baseHeight=s,o.width=a,o.height=s,o.isReady=!0,o.samples=1,o.generateMipMaps=!!i.generateMipMaps,o.samplingMode=i.samplingMode,o.type=i.type,o.format=i.format,o._generateDepthBuffer=i.generateDepthBuffer,o._generateStencilBuffer=!!i.generateStencilBuffer,this._internalTexturesCache.push(o),o},t.prototype.updateTextureSamplingMode=function(e,n){if(n._webGLTexture){var i=this._getNativeSamplingMode(e);this._native.setTextureSampling(n._webGLTexture,i)}n.samplingMode=e},t.prototype.bindFramebuffer=function(e,n,i,o,a){if(n)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||o)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._depthStencilTexture?this._bindUnboundFramebuffer(e._depthStencilTexture._framebuffer):this._bindUnboundFramebuffer(e._framebuffer)},t.prototype.unBindFramebuffer=function(e,n,i){n===void 0&&(n=!1),n&&l.a.Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring."),i&&i(),this._bindUnboundFramebuffer(null)},t.prototype.createDynamicVertexBuffer=function(e){return this.createVertexBuffer(e,!0)},t.prototype.updateDynamicIndexBuffer=function(e,n,i){i===void 0&&(i=0);var o=e,a=this._normalizeIndexData(n);o.is32Bits=a.BYTES_PER_ELEMENT===4,this._native.updateDynamicIndexBuffer(o.nativeIndexBuffer,a,i)},t.prototype.updateDynamicVertexBuffer=function(e,n,i,o){var a=e,s=ArrayBuffer.isView(n)?n:new Float32Array(n);this._native.updateDynamicVertexBuffer(a.nativeVertexBuffer,s,i??0,o??s.byteLength)},t.prototype._setTexture=function(e,n,i,o){o===void 0&&(o=!1);var a,s=this._boundUniforms[e];if(!s)return!1;if(!n)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._native.setTexture(s,null)),!1;if(n.video)this._activeChannel=e,n.update();else if(n.delayLoadState===h.a.DELAYLOADSTATE_NOTLOADED)return n.delayLoad(),!1;return a=o?n.depthStencilTexture:n.isReady()?n.getInternalTexture():n.isCube?this.emptyCubeTexture:n.is3D?this.emptyTexture3D:n.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!a||!a._webGLTexture)&&(this._native.setTextureWrapMode(a._webGLTexture,this._getAddressMode(n.wrapU),this._getAddressMode(n.wrapV),this._getAddressMode(n.wrapR)),this._updateAnisotropicLevel(n),this._native.setTexture(s,a._webGLTexture),!0)},t.prototype._updateAnisotropicLevel=function(e){var n=e.getInternalTexture(),i=e.anisotropicFilteringLevel;n&&n._webGLTexture&&n._cachedAnisotropicFilteringLevel!==i&&(this._native.setTextureAnisotropicLevel(n._webGLTexture,i),n._cachedAnisotropicFilteringLevel=i)},t.prototype._getAddressMode=function(e){switch(e){case h.a.TEXTURE_WRAP_ADDRESSMODE:return this._native.ADDRESS_MODE_WRAP;case h.a.TEXTURE_CLAMP_ADDRESSMODE:return this._native.ADDRESS_MODE_CLAMP;case h.a.TEXTURE_MIRROR_ADDRESSMODE:return this._native.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}},t.prototype._bindTexture=function(e,n){var i=this._boundUniforms[e];i&&this._native.setTexture(i,n._webGLTexture)},t.prototype._deleteBuffer=function(e){e.nativeIndexBuffer&&(this._native.deleteIndexBuffer(e.nativeIndexBuffer),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._native.deleteVertexBuffer(e.nativeVertexBuffer),delete e.nativeVertexBuffer)},t.prototype.releaseEffects=function(){},t.prototype._uploadCompressedDataToTextureDirectly=function(e,n,i,o,a,s,d){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")},t.prototype._uploadDataToTextureDirectly=function(e,n,i,o){throw new Error("_uploadDataToTextureDirectly not implemented.")},t.prototype._uploadArrayBufferViewToTexture=function(e,n,i,o){throw new Error("_uploadArrayBufferViewToTexture not implemented.")},t.prototype._uploadImageToTexture=function(e,n,i,o){throw new Error("_uploadArrayBufferViewToTexture not implemented.")},t.prototype._getNativeSamplingMode=function(e){switch(e){case h.a.TEXTURE_NEAREST_NEAREST:return this._native.TEXTURE_NEAREST_NEAREST;case h.a.TEXTURE_LINEAR_LINEAR:return this._native.TEXTURE_LINEAR_LINEAR;case h.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR:return this._native.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case h.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST:return this._native.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case h.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST:return this._native.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case h.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR:return this._native.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case h.a.TEXTURE_NEAREST_LINEAR:return this._native.TEXTURE_NEAREST_LINEAR;case h.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR:return this._native.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case h.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST:return this._native.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case h.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR:return this._native.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case h.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST:return this._native.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case h.a.TEXTURE_LINEAR_NEAREST:return this._native.TEXTURE_LINEAR_NEAREST;default:throw new Error("Unsupported sampling mode: "+e+".")}},t.prototype._getNativeTextureFormat=function(e,n){if(e==h.a.TEXTUREFORMAT_RGBA&&n==h.a.TEXTURETYPE_UNSIGNED_INT)return this._native.TEXTURE_FORMAT_RGBA8;if(e==h.a.TEXTUREFORMAT_RGBA&&n==h.a.TEXTURETYPE_FLOAT)return this._native.TEXTURE_FORMAT_RGBA32F;throw new Error("Unsupported texture format or type: format "+e+", type "+n+".")},t.prototype._getNativeAlphaMode=function(e){switch(e){case h.a.ALPHA_DISABLE:return this._native.ALPHA_DISABLE;case h.a.ALPHA_ADD:return this._native.ALPHA_ADD;case h.a.ALPHA_COMBINE:return this._native.ALPHA_COMBINE;case h.a.ALPHA_SUBTRACT:return this._native.ALPHA_SUBTRACT;case h.a.ALPHA_MULTIPLY:return this._native.ALPHA_MULTIPLY;case h.a.ALPHA_MAXIMIZED:return this._native.ALPHA_MAXIMIZED;case h.a.ALPHA_ONEONE:return this._native.ALPHA_ONEONE;case h.a.ALPHA_PREMULTIPLIED:return this._native.ALPHA_PREMULTIPLIED;case h.a.ALPHA_PREMULTIPLIED_PORTERDUFF:return this._native.ALPHA_PREMULTIPLIED_PORTERDUFF;case h.a.ALPHA_INTERPOLATE:return this._native.ALPHA_INTERPOLATE;case h.a.ALPHA_SCREENMODE:return this._native.ALPHA_SCREENMODE;default:throw new Error("Unsupported alpha mode: "+e+".")}},t.prototype._getNativeAttribType=function(e){switch(e){case Me.b.UNSIGNED_BYTE:return this._native.ATTRIB_TYPE_UINT8;case Me.b.SHORT:return this._native.ATTRIB_TYPE_INT16;case Me.b.FLOAT:return this._native.ATTRIB_TYPE_FLOAT;default:throw new Error("Unsupported attribute type: "+e+".")}},t}(Ue.a),Mp=f(74),Yo=function(){function r(){}return r.COPY=1,r.CUT=2,r.PASTE=3,r}(),Ip=function(){function r(t,e){this.type=t,this.event=e}return r.GetTypeFromCharacter=function(t){switch(t){case 67:return Yo.COPY;case 86:return Yo.PASTE;case 88:return Yo.CUT;default:return-1}},r}(),Os=f(83),Pi=f(69);(function(r){r[r.Clean=0]="Clean",r[r.Stop=1]="Stop",r[r.Sync=2]="Sync",r[r.NoSync=3]="NoSync"})(Ai||(Ai={}));var Ut=function(){function r(){}return Object.defineProperty(r,"ForceFullSceneLoadingForIncremental",{get:function(){return Pi.a.ForceFullSceneLoadingForIncremental},set:function(t){Pi.a.ForceFullSceneLoadingForIncremental=t},enumerable:!1,configurable:!0}),Object.defineProperty(r,"ShowLoadingScreen",{get:function(){return Pi.a.ShowLoadingScreen},set:function(t){Pi.a.ShowLoadingScreen=t},enumerable:!1,configurable:!0}),Object.defineProperty(r,"loggingLevel",{get:function(){return Pi.a.loggingLevel},set:function(t){Pi.a.loggingLevel=t},enumerable:!1,configurable:!0}),Object.defineProperty(r,"CleanBoneMatrixWeights",{get:function(){return Pi.a.CleanBoneMatrixWeights},set:function(t){Pi.a.CleanBoneMatrixWeights=t},enumerable:!1,configurable:!0}),r.GetDefaultPlugin=function(){return r._registeredPlugins[".babylon"]},r._GetPluginForExtension=function(t){var e=r._registeredPlugins[t];return e||(l.a.Warn("Unable to find a plugin to load "+t+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/how_to/load_from_any_file_type"),r.GetDefaultPlugin())},r._GetPluginForDirectLoad=function(t){for(var e in r._registeredPlugins){var n=r._registeredPlugins[e].plugin;if(n.canDirectLoad&&n.canDirectLoad(t))return r._registeredPlugins[e]}return r.GetDefaultPlugin()},r._GetPluginForFilename=function(t){var e=t.indexOf("?");e!==-1&&(t=t.substring(0,e));var n=t.lastIndexOf("."),i=t.substring(n,t.length).toLowerCase();return r._GetPluginForExtension(i)},r._GetDirectLoad=function(t){return t.substr(0,5)==="data:"?t.substr(5):null},r._LoadData=function(t,e,n,i,o,a,s){var d,p=r._GetDirectLoad(t.name),y=s?r._GetPluginForExtension(s):p?r._GetPluginForDirectLoad(t.name):r._GetPluginForFilename(t.name);if(!(d=y.plugin.createPlugin!==void 0?y.plugin.createPlugin():y.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(r.OnPluginActivatedObservable.notifyObservers(d),p){if(d.directLoad){var P=d.directLoad(e,p);P.then?P.then(function(Pe){n(d,Pe)}).catch(function(Pe){o("Error in directLoad of _loadData: "+Pe,Pe)}):n(d,P)}else n(d,p);return d}var O=y.isBinary,U=function(Pe,Ee){e.isDisposed?o("Scene has been disposed"):n(d,Pe,Ee)},F=null,z=!1,J=d.onDisposeObservable;J&&J.add(function(){z=!0,F&&(F.abort(),F=null),a()});var ie=function(){if(!z){var Pe=function(Se,Le){U(Se,Le?Le.responseURL:void 0)},Ee=function(Se){o(Se.message,Se)};F=d.requestFile?d.requestFile(e,t.url,Pe,i,O,Ee):e._requestFile(t.url,Pe,i,!0,O,Ee)}},se=t.file||Os.a.FilesToLoad[t.name.toLowerCase()];if(t.rootUrl.indexOf("file:")===-1||t.rootUrl.indexOf("file:")!==-1&&!se){var ce=e.getEngine(),ue=ce.enableOfflineSupport;if(ue){for(var fe=!1,ve=0,Te=e.disableOfflineSupportExceptionRules;veF.snapDistance?(Fe=Math.floor(Math.abs(Oe)/F.snapDistance),Oe<0&&(Fe*=-1),Oe%=F.snapDistance,Pe.scaleToRef(F.snapDistance*Fe,Pe),Ie=!0):Pe.scaleInPlace(0)),u.a.ScalingToRef(1+Pe.x,1+Pe.y,1+Pe.z,F._tmpMatrix2),F._tmpMatrix2.multiplyToRef(F.attachedNode.getWorldMatrix(),F._tmpMatrix),F._tmpMatrix.decompose(F._tmpVector),Math.abs(F._tmpVector.x)<1e5&&Math.abs(F._tmpVector.y)<1e5&&Math.abs(F._tmpVector.z)<1e5&&F.attachedNode.getWorldMatrix().copyFrom(F._tmpMatrix),Ie&&(Ee.snapDistance=F.snapDistance*Fe,F.onSnapObservable.notifyObservers(Ee)),F._matrixChanged()}}),F.dragBehavior.onDragStartObservable.add(function(){F._dragging=!0}),F.dragBehavior.onDragObservable.add(function(xe){return ve(xe.dragDistance)}),F.dragBehavior.onDragEndObservable.add(Te),(p=(d=(s=o?.uniformScaleGizmo)===null||s===void 0?void 0:s.dragBehavior)===null||d===void 0?void 0:d.onDragObservable)===null||p===void 0||p.add(function(xe){return ve(xe.delta.y)}),(O=(P=(y=o?.uniformScaleGizmo)===null||y===void 0?void 0:y.dragBehavior)===null||P===void 0?void 0:P.onDragEndObservable)===null||O===void 0||O.add(Te);var Se={gizmoMeshes:[J,ie],colliderMeshes:[se.arrowMesh,se.arrowTail],material:F._coloredMaterial,hoverMaterial:F._hoverMaterial,disableMaterial:F._disableMaterial,active:!1};(U=F._parent)===null||U===void 0||U.addToAxisCache(F._gizmoMesh,Se),F._pointerObserver=i.utilityLayerScene.onPointerObservable.add(function(xe){var Ne;if(!F._customMeshSet&&(F._isHovered=Se.colliderMeshes.indexOf((Ne=xe?.pickInfo)===null||Ne===void 0?void 0:Ne.pickedMesh)!=-1,!F._parent)){var Ie=F._isHovered||F._dragging?F._hoverMaterial:F._coloredMaterial;Se.gizmoMeshes.forEach(function(Fe){Fe.material=Ie,Fe.color&&(Fe.color=Ie.diffuseColor)})}});var Le=i._getSharedGizmoLight();return Le.includedOnlyMeshes=Le.includedOnlyMeshes.concat(F._rootMesh.getChildMeshes()),F}return Object(c.d)(t,r),t.prototype._createGizmoMesh=function(e,n,i){i===void 0&&(i=!1);var o=yr.a.CreateBox("yPosMesh",{size:.4*(1+(n-1)/4)},this.gizmoLayer.utilityLayerScene),a=ui.a.CreateCylinder("cylinder",{diameterTop:.005*n,height:.275,diameterBottom:.005*n,tessellation:96},this.gizmoLayer.utilityLayerScene);return o.scaling.scaleInPlace(.1),o.material=this._coloredMaterial,o.rotation.x=Math.PI/2,o.position.z+=.3,a.material=this._coloredMaterial,a.position.z+=.1375,a.rotation.x=Math.PI/2,i&&(o.visibility=0,a.visibility=0),e.addChild(o),e.addChild(a),{arrowMesh:o,arrowTail:a}},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()}),r.prototype.dispose.call(this)},t.prototype.setCustomMesh=function(e,n){var i=this;n===void 0&&(n=!1),r.prototype.setCustomMesh.call(this,e),n&&(this._rootMesh.getChildMeshes().forEach(function(o){o.material=i._coloredMaterial,o.color&&(o.color=i._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)},t}(Ln.a),Nn=f(45),cn=f(40),bu=function(r){function t(e,n){e===void 0&&(e=M.a.Gray()),n===void 0&&(n=xn.a.DefaultKeepDepthUtilityLayer);var i=r.call(this,n)||this;i._boundingDimensions=new u.e(1,1,1),i._renderObserver=null,i._pointerObserver=null,i._scaleDragSpeed=.2,i._tmpQuaternion=new u.b,i._tmpVector=new u.e(0,0,0),i._tmpRotationMatrix=new u.a,i.ignoreChildren=!1,i.includeChildPredicate=null,i.rotationSphereSize=.1,i.scaleBoxSize=.1,i.fixedDragMeshScreenSize=!1,i.fixedDragMeshBoundsSize=!1,i.fixedDragMeshScreenSizeDistanceFactor=10,i.onDragStartObservable=new x.c,i.onScaleBoxDragObservable=new x.c,i.onScaleBoxDragEndObservable=new x.c,i.onRotationSphereDragObservable=new x.c,i.onRotationSphereDragEndObservable=new x.c,i.scalePivot=null,i._existingMeshScale=new u.e,i._dragMesh=null,i.pointerDragBehavior=new bi.a,i.updateScale=!1,i._anchorMesh=new Dt.a("anchor",n.utilityLayerScene),i.coloredMaterial=new Ft.a("",n.utilityLayerScene),i.coloredMaterial.disableLighting=!0,i.hoverColoredMaterial=new Ft.a("",n.utilityLayerScene),i.hoverColoredMaterial.disableLighting=!0,i._lineBoundingBox=new Dt.a("",n.utilityLayerScene),i._lineBoundingBox.rotationQuaternion=new u.b;var o=[];o.push(cn.a.CreateLines("lines",{points:[new u.e(0,0,0),new u.e(i._boundingDimensions.x,0,0)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(0,0,0),new u.e(0,i._boundingDimensions.y,0)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(0,0,0),new u.e(0,0,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(i._boundingDimensions.x,0,0),new u.e(i._boundingDimensions.x,i._boundingDimensions.y,0)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(i._boundingDimensions.x,0,0),new u.e(i._boundingDimensions.x,0,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(0,i._boundingDimensions.y,0),new u.e(i._boundingDimensions.x,i._boundingDimensions.y,0)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(0,i._boundingDimensions.y,0),new u.e(0,i._boundingDimensions.y,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(0,0,i._boundingDimensions.z),new u.e(i._boundingDimensions.x,0,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(0,0,i._boundingDimensions.z),new u.e(0,i._boundingDimensions.y,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(i._boundingDimensions.x,i._boundingDimensions.y,i._boundingDimensions.z),new u.e(0,i._boundingDimensions.y,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(i._boundingDimensions.x,i._boundingDimensions.y,i._boundingDimensions.z),new u.e(i._boundingDimensions.x,0,i._boundingDimensions.z)]},n.utilityLayerScene)),o.push(cn.a.CreateLines("lines",{points:[new u.e(i._boundingDimensions.x,i._boundingDimensions.y,i._boundingDimensions.z),new u.e(i._boundingDimensions.x,i._boundingDimensions.y,0)]},n.utilityLayerScene)),o.forEach(function(J){J.color=e,J.position.addInPlace(new u.e(-i._boundingDimensions.x/2,-i._boundingDimensions.y/2,-i._boundingDimensions.z/2)),J.isPickable=!1,i._lineBoundingBox.addChild(J)}),i._rootMesh.addChild(i._lineBoundingBox),i.setColor(e),i._rotateSpheresParent=new Dt.a("",n.utilityLayerScene),i._rotateSpheresParent.rotationQuaternion=new u.b;for(var a=function(J){var ie=Nn.a.CreateSphere("",{diameter:1},n.utilityLayerScene);ie.rotationQuaternion=new u.b,ie.material=s.coloredMaterial,(P=new bi.a({})).moveAttached=!1,P.updateDragPlane=!1,ie.addBehavior(P);var se=new u.e(1,0,0),ce=0;P.onDragStartObservable.add(function(){se.copyFrom(ie.forward),ce=0}),P.onDragObservable.add(function(ue){if(i.onRotationSphereDragObservable.notifyObservers({}),i.attachedMesh){var fe=i.attachedMesh.parent;if(fe&&fe.scaling&&fe.scaling.isNonUniformWithinEpsilon(.001))return void l.a.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");kn.a._RemoveAndStorePivotPoint(i.attachedMesh);var ve=se,Te=ue.dragPlaneNormal.scale(u.e.Dot(ue.dragPlaneNormal,ve)),Oe=ve.subtract(Te).normalizeToNew(),Pe=u.e.Dot(Oe,ue.delta)<0?Math.abs(ue.delta.length()):-Math.abs(ue.delta.length());Pe=Pe/i._boundingDimensions.length()*i._anchorMesh.scaling.length(),i.attachedMesh.rotationQuaternion||(i.attachedMesh.rotationQuaternion=u.b.RotationYawPitchRoll(i.attachedMesh.rotation.y,i.attachedMesh.rotation.x,i.attachedMesh.rotation.z)),i._anchorMesh.rotationQuaternion||(i._anchorMesh.rotationQuaternion=u.b.RotationYawPitchRoll(i._anchorMesh.rotation.y,i._anchorMesh.rotation.x,i._anchorMesh.rotation.z)),ce+=Pe,Math.abs(ce)<=2*Math.PI&&(J>=8?u.b.RotationYawPitchRollToRef(0,0,Pe,i._tmpQuaternion):J>=4?u.b.RotationYawPitchRollToRef(Pe,0,0,i._tmpQuaternion):u.b.RotationYawPitchRollToRef(0,Pe,0,i._tmpQuaternion),i._anchorMesh.addChild(i.attachedMesh),i._anchorMesh.rotationQuaternion.multiplyToRef(i._tmpQuaternion,i._anchorMesh.rotationQuaternion),i._anchorMesh.removeChild(i.attachedMesh),i.attachedMesh.setParent(fe)),i.updateBoundingBox(),kn.a._RestorePivotPoint(i.attachedMesh)}i._updateDummy()}),P.onDragStartObservable.add(function(){i.onDragStartObservable.notifyObservers({}),i._selectNode(ie)}),P.onDragEndObservable.add(function(){i.onRotationSphereDragEndObservable.notifyObservers({}),i._selectNode(null),i._updateDummy()}),s._rotateSpheresParent.addChild(ie)},s=this,d=0;d<12;d++)a(d);i._rootMesh.addChild(i._rotateSpheresParent),i._scaleBoxesParent=new Dt.a("",n.utilityLayerScene),i._scaleBoxesParent.rotationQuaternion=new u.b;for(var p=0;p<3;p++)for(var y=0;y<3;y++)for(var P,O=function(){var J=(p===1?1:0)+(y===1?1:0)+(F===1?1:0);if(J===1||J===3)return"continue";var ie=yr.a.CreateBox("",{size:1},n.utilityLayerScene);ie.material=U.coloredMaterial,ie.metadata=J===2;var se=new u.e(p-1,y-1,F-1).normalize();(P=new bi.a({dragAxis:se})).updateDragPlane=!1,P.moveAttached=!1,ie.addBehavior(P),P.onDragObservable.add(function(ce){if(i.onScaleBoxDragObservable.notifyObservers({}),i.attachedMesh){var ue=i.attachedMesh.parent;if(ue&&ue.scaling&&ue.scaling.isNonUniformWithinEpsilon(.001))return void l.a.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");kn.a._RemoveAndStorePivotPoint(i.attachedMesh);var fe=ce.dragDistance/i._boundingDimensions.length()*i._anchorMesh.scaling.length(),ve=new u.e(fe,fe,fe);J===2&&(ve.x*=Math.abs(se.x),ve.y*=Math.abs(se.y),ve.z*=Math.abs(se.z)),ve.scaleInPlace(i._scaleDragSpeed),i.updateBoundingBox(),i.scalePivot?(i.attachedMesh.getWorldMatrix().getRotationMatrixToRef(i._tmpRotationMatrix),i._boundingDimensions.scaleToRef(.5,i._tmpVector),u.e.TransformCoordinatesToRef(i._tmpVector,i._tmpRotationMatrix,i._tmpVector),i._anchorMesh.position.subtractInPlace(i._tmpVector),i._boundingDimensions.multiplyToRef(i.scalePivot,i._tmpVector),u.e.TransformCoordinatesToRef(i._tmpVector,i._tmpRotationMatrix,i._tmpVector),i._anchorMesh.position.addInPlace(i._tmpVector)):(ie.absolutePosition.subtractToRef(i._anchorMesh.position,i._tmpVector),i._anchorMesh.position.subtractInPlace(i._tmpVector)),i._anchorMesh.addChild(i.attachedMesh),i._anchorMesh.scaling.addInPlace(ve),(i._anchorMesh.scaling.x<0||i._anchorMesh.scaling.y<0||i._anchorMesh.scaling.z<0)&&i._anchorMesh.scaling.subtractInPlace(ve),i._anchorMesh.removeChild(i.attachedMesh),i.attachedMesh.setParent(ue),kn.a._RestorePivotPoint(i.attachedMesh)}i._updateDummy()}),P.onDragStartObservable.add(function(){i.onDragStartObservable.notifyObservers({}),i._selectNode(ie)}),P.onDragEndObservable.add(function(){i.onScaleBoxDragEndObservable.notifyObservers({}),i._selectNode(null),i._updateDummy()}),U._scaleBoxesParent.addChild(ie)},U=this,F=0;F<3;F++)O();i._rootMesh.addChild(i._scaleBoxesParent);var z=new Array;return i._pointerObserver=n.utilityLayerScene.onPointerObservable.add(function(J){z[J.event.pointerId]?J.pickInfo&&J.pickInfo.pickedMesh!=z[J.event.pointerId]&&(z[J.event.pointerId].material=i.coloredMaterial,delete z[J.event.pointerId]):i._rotateSpheresParent.getChildMeshes().concat(i._scaleBoxesParent.getChildMeshes()).forEach(function(ie){J.pickInfo&&J.pickInfo.pickedMesh==ie&&(z[J.event.pointerId]=ie,ie.material=i.hoverColoredMaterial)})}),i._renderObserver=i.gizmoLayer.originalScene.onBeforeRenderObservable.add(function(){i.attachedMesh&&!i._existingMeshScale.equals(i.attachedMesh.scaling)?i.updateBoundingBox():(i.fixedDragMeshScreenSize||i.fixedDragMeshBoundsSize)&&(i._updateRotationSpheres(),i._updateScaleBoxes()),i._dragMesh&&i.attachedMesh&&i.pointerDragBehavior.dragging&&(i._lineBoundingBox.position.rotateByQuaternionToRef(i._rootMesh.rotationQuaternion,i._tmpVector),i.attachedMesh.setAbsolutePosition(i._dragMesh.position.add(i._tmpVector.scale(-1))))}),i.updateBoundingBox(),i}return Object(c.d)(t,r),t.prototype.setColor=function(e){this.coloredMaterial.emissiveColor=e,this.hoverColoredMaterial.emissiveColor=e.clone().add(new M.a(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(function(n){n.color&&(n.color=e)})},t.prototype._attachedNodeChanged=function(e){var n=this;if(e){kn.a._RemoveAndStorePivotPoint(e);var i=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(i),kn.a._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach(function(o){o.markAsDirty("scaling")}),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function(){n._updateDummy()})}},t.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(function(n){n.isVisible=!e||n==e})},t.prototype.updateBoundingBox=function(){if(this.attachedMesh){kn.a._RemoveAndStorePivotPoint(this.attachedMesh);var e=this.attachedMesh.parent;this.attachedMesh.setParent(null);var n=null;this.attachedMesh.skeleton&&(n=this.attachedMesh.skeleton.overrideMesh,this.attachedMesh.skeleton.overrideMesh=null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=u.b.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=u.b.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var i=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);i.max.subtractToRef(i.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((i.max.x+i.min.x)/2,(i.max.y+i.min.y)/2,(i.max.z+i.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),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e),this.attachedMesh.skeleton&&(this.attachedMesh.skeleton.overrideMesh=n)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),kn.a._RestorePivotPoint(this.attachedMesh))},t.prototype._updateRotationSpheres=function(){for(var e=this._rotateSpheresParent.getChildMeshes(),n=0;n<3;n++)for(var i=0;i<2;i++)for(var o=0;o<2;o++){var a=4*n+2*i+o;if(n==0&&(e[a].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*o),e[a].position.addInPlace(new u.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[a].lookAt(u.e.Cross(e[a].position.normalizeToNew(),u.e.Right()).normalizeToNew().add(e[a].position))),n==1&&(e[a].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*o),e[a].position.addInPlace(new u.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[a].lookAt(u.e.Cross(e[a].position.normalizeToNew(),u.e.Up()).normalizeToNew().add(e[a].position))),n==2&&(e[a].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*o,this._boundingDimensions.z/2),e[a].position.addInPlace(new u.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[a].lookAt(u.e.Cross(e[a].position.normalizeToNew(),u.e.Forward()).normalizeToNew().add(e[a].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[a].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var s=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[a].scaling.set(s,s,s)}else this.fixedDragMeshBoundsSize?e[a].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[a].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}},t.prototype._updateScaleBoxes=function(){for(var e=this._scaleBoxesParent.getChildMeshes(),n=0,i=0;i<3;i++)for(var o=0;o<3;o++)for(var a=0;a<3;a++){var s=(i===1?1:0)+(o===1?1:0)+(a===1?1:0);if(s!==1&&s!==3){if(e[n])if(e[n].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(o/2),this._boundingDimensions.z*(a/2)),e[n].position.addInPlace(new u.e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[n].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var d=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[n].scaling.set(d,d,d)}else this.fixedDragMeshBoundsSize?e[n].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[n].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);n++}}},t.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach(function(n,i){i<4?n.setEnabled(e.indexOf("x")!=-1):i<8?n.setEnabled(e.indexOf("y")!=-1):n.setEnabled(e.indexOf("z")!=-1)})},t.prototype.setEnabledScaling=function(e,n){n===void 0&&(n=!1),this._scaleBoxesParent.getChildMeshes().forEach(function(i,o){var a=e;n&&i.metadata===!0&&(a=!1),i.setEnabled(a)})},t.prototype._updateDummy=function(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))},t.prototype.enableDragBehavior=function(){this._dragMesh=De.a.CreateBox("dummy",1,this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new u.b,this.pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this.pointerDragBehavior)},t.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),r.prototype.dispose.call(this)},t.MakeNotPickableAndWrapInBoundingBox=function(e){var n=function(d){d.isPickable=!1,d.getChildMeshes().forEach(function(p){n(p)})};n(e),e.rotationQuaternion||(e.rotationQuaternion=u.b.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));var i=e.position.clone(),o=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);var a=yr.a.CreateBox("box",{size:1},e.getScene()),s=e.getHierarchyBoundingVectors();return s.max.subtractToRef(s.min,a.scaling),a.scaling.y===0&&(a.scaling.y=Gt.a),a.scaling.x===0&&(a.scaling.x=Gt.a),a.scaling.z===0&&(a.scaling.z=Gt.a),a.position.set((s.max.x+s.min.x)/2,(s.max.y+s.min.y)/2,(s.max.z+s.min.z)/2),e.addChild(a),e.rotationQuaternion.copyFrom(o),e.position.copyFrom(i),e.removeChild(a),a.addChild(e),a.visibility=0,a},t.prototype.setCustomMesh=function(e){l.a.Error("Custom meshes are not supported on this gizmo")},t}(Ln.a),Zo=function(r){function t(e,n,i,o,a,s,d){var p;n===void 0&&(n=M.a.Gray()),i===void 0&&(i=xn.a.DefaultUtilityLayer),o===void 0&&(o=32),a===void 0&&(a=null),d===void 0&&(d=1);var y=r.call(this,i)||this;y._pointerObserver=null,y.snapDistance=0,y.onSnapObservable=new x.c,y._isEnabled=!0,y._parent=null,y._dragging=!1,y._parent=a,y._coloredMaterial=new Ft.a("",i.utilityLayerScene),y._coloredMaterial.diffuseColor=n,y._coloredMaterial.specularColor=n.subtract(new M.a(.1,.1,.1)),y._hoverMaterial=new Ft.a("",i.utilityLayerScene),y._hoverMaterial.diffuseColor=M.a.Yellow(),y._disableMaterial=new Ft.a("",i.utilityLayerScene),y._disableMaterial.diffuseColor=M.a.Gray(),y._disableMaterial.alpha=.4,y._gizmoMesh=new De.a("",i.utilityLayerScene);var P=y._createGizmoMesh(y._gizmoMesh,d,o),O=P.rotationMesh,U=P.collider,F=[];y._rotationCircle=y.setupRotationCircle(F,y._gizmoMesh),y._gizmoMesh.lookAt(y._rootMesh.position.add(e)),y._rootMesh.addChild(y._gizmoMesh),y._gizmoMesh.scaling.scaleInPlace(1/3),y.dragBehavior=new bi.a({dragPlaneNormal:e}),y.dragBehavior.moveAttached=!1,y.dragBehavior.maxDragAngle=9*Math.PI/20,y.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,y._rootMesh.addBehavior(y.dragBehavior);var z=0,J=new u.e,ie=new u.e,se=new u.a,ce=new u.e,ue=new u.e;y.dragBehavior.onDragStartObservable.add(function(Se){if(y.attachedNode){J.copyFrom(Se.dragPlanePoint);var Le=new u.e(0,0,1),xe=y._rotationCircle.getDirection(Le);xe.normalize(),y._gizmoMesh.removeChild(y._rotationCircle),J.copyFrom(Se.dragPlanePoint),ie=Se.dragPlanePoint;var Ne=y._rotationCircle.getAbsolutePosition().clone(),Ie=y._rotationCircle.getAbsolutePosition().clone().addInPlace(xe),Fe=Se.dragPlanePoint,Ke=u.e.GetAngleBetweenVectors(Ie.subtract(Ne),Fe.subtract(Ne),y._rotationCircle.up);y._rotationCircle.addRotation(0,Ke,0),y._dragging=!0}}),y.dragBehavior.onDragEndObservable.add(function(){z=0,y.updateRotationCircle(y._rotationCircle,F,z,ie),y._gizmoMesh.addChild(y._rotationCircle),y._dragging=!1});var fe={snapDistance:0},ve=0,Te=new u.a,Oe=new u.b;y.dragBehavior.onDragObservable.add(function(Se){if(y.attachedNode){var Le=new u.e(1,1,1),xe=new u.b(0,0,0,1),Ne=new u.e(0,0,0);y.attachedNode.getWorldMatrix().decompose(Le,xe,Ne);var Ie=Se.dragPlanePoint.subtract(Ne).normalize(),Fe=J.subtract(Ne).normalize(),Ke=u.e.Cross(Ie,Fe),nt=u.e.Dot(Ie,Fe),rt=Math.atan2(Ke.length(),nt);ce.copyFrom(e),ue.copyFrom(e),y.updateGizmoRotationToMatchAttachedMesh&&(xe.toRotationMatrix(se),ue=u.e.TransformCoordinates(ce,se));var ut=!1;if(i.utilityLayerScene.activeCamera){var qe=i.utilityLayerScene.activeCamera.position.subtract(Ne);u.e.Dot(qe,ue)>0&&(ce.scaleInPlace(-1),ue.scaleInPlace(-1),ut=!0)}u.e.Dot(ue,Ke)>0&&(rt=-rt);var at=!1;if(y.snapDistance!=0)if(ve+=rt,Math.abs(ve)>y.snapDistance){var ot=Math.floor(Math.abs(ve)/y.snapDistance);ve<0&&(ot*=-1),ve%=y.snapDistance,rt=y.snapDistance*ot,at=!0}else rt=0;z+=ut?-rt:rt,y.updateRotationCircle(y._rotationCircle,F,z,ie);var Je=Math.sin(rt/2);if(Oe.set(ce.x*Je,ce.y*Je,ce.z*Je,Math.cos(rt/2)),Te.determinant()>0){var dt=new u.e;Oe.toEulerAnglesToRef(dt),u.b.RotationYawPitchRollToRef(dt.y,-dt.x,-dt.z,Oe)}y.updateGizmoRotationToMatchAttachedMesh?xe.multiplyToRef(Oe,xe):Oe.multiplyToRef(xe,xe),y.attachedNode.getWorldMatrix().copyFrom(u.a.Compose(Le,xe,Ne)),J.copyFrom(Se.dragPlanePoint),at&&(fe.snapDistance=rt,y.onSnapObservable.notifyObservers(fe)),y._matrixChanged()}});var Pe=i._getSharedGizmoLight();Pe.includedOnlyMeshes=Pe.includedOnlyMeshes.concat(y._rootMesh.getChildMeshes(!1));var Ee={colliderMeshes:[U],gizmoMeshes:[O],material:y._coloredMaterial,hoverMaterial:y._hoverMaterial,disableMaterial:y._disableMaterial,active:!1};return(p=y._parent)===null||p===void 0||p.addToAxisCache(y._gizmoMesh,Ee),y._pointerObserver=i.utilityLayerScene.onPointerObservable.add(function(Se){var Le;if(!y._customMeshSet&&(y._isHovered=Ee.colliderMeshes.indexOf((Le=Se?.pickInfo)===null||Le===void 0?void 0:Le.pickedMesh)!=-1,!y._parent)){var xe=y._isHovered||y._dragging?y._hoverMaterial:y._coloredMaterial;Ee.gizmoMeshes.forEach(function(Ne){Ne.material=xe,Ne.color&&(Ne.color=xe.diffuseColor)})}}),y}return Object(c.d)(t,r),t.prototype._createGizmoMesh=function(e,n,i){var o=De.a.CreateTorus("ignore",.6,.03*n,i,this.gizmoLayer.utilityLayerScene);o.visibility=0;var a=De.a.CreateTorus("",.6,.005*n,i,this.gizmoLayer.utilityLayerScene);return a.material=this._coloredMaterial,a.rotation.x=Math.PI/2,o.rotation.x=Math.PI/2,e.addChild(a),e.addChild(o),{rotationMesh:a,collider:o}},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},t.prototype.setupRotationCircle=function(e,n){for(var i=t._CircleConstants.pi2/t._CircleConstants.tessellation,o=-Math.PI/2;o0?p:-1*p,P=n>0?a:-1*a;s[d].set(t._CircleConstants.radius*Math.sin(y)*Math.cos(P),0,t._CircleConstants.radius*Math.cos(y)*Math.cos(P))}else s[d].set(0,0,0);d++}o++}},t.prototype.updateRotationCircle=function(e,n,i,o){this.updateRotationPath(n,i),De.a.CreateRibbon("rotationCircle",n,!1,!1,0,this.gizmoLayer.utilityLayerScene,void 0,void 0,e.geometry?e:void 0)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationCircle&&this._rotationCircle.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()}),r.prototype.dispose.call(this)},t._CircleConstants={radius:.3,pi2:2*Math.PI,tessellation:70,rotationCircleRange:4},t}(Ln.a),yu=function(r){function t(e,n,i,o,a){e===void 0&&(e=xn.a.DefaultUtilityLayer),n===void 0&&(n=32),i===void 0&&(i=!1),o===void 0&&(o=1);var s=r.call(this,e)||this;return s.onDragStartObservable=new x.c,s.onDragEndObservable=new x.c,s._observables=[],s._gizmoAxisCache=new Map,s.xGizmo=new Zo(new u.e(1,0,0),M.a.Red().scale(.5),e,n,s,i,o),s.yGizmo=new Zo(new u.e(0,1,0),M.a.Green().scale(.5),e,n,s,i,o),s.zGizmo=new Zo(new u.e(0,0,1),M.a.Blue().scale(.5),e,n,s,i,o),[s.xGizmo,s.yGizmo,s.zGizmo].forEach(function(d){d.dragBehavior.onDragStartObservable.add(function(){s.onDragStartObservable.notifyObservers({})}),d.dragBehavior.onDragEndObservable.add(function(){s.onDragEndObservable.notifyObservers({})})}),s.attachedMesh=null,s.attachedNode=null,a?a.addToAxisCache(s._gizmoAxisCache):Ln.a.GizmoAxisPointerObserver(e,s._gizmoAxisCache),s}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(n){n.isEnabled?n.attachedMesh=e:n.attachedMesh=null})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(n){n.isEnabled?n.attachedNode=e:n.attachedNode=null})},enumerable:!1,configurable:!0}),t.prototype._checkBillboardTransform=function(){this._nodeAttached&&this._nodeAttached.billboardMode&&console.log("Rotation Gizmo will not work with transforms in billboard mode.")},Object.defineProperty(t.prototype,"isHovered",{get:function(){var e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(n){e=e||n.isHovered}),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this.xGizmo.snapDistance},set:function(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this.xGizmo.scaleRatio},set:function(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)},enumerable:!1,configurable:!0}),t.prototype.addToAxisCache=function(e,n){this._gizmoAxisCache.set(e,n)},t.prototype.dispose=function(){var e=this;this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach(function(n){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(n)})},t.prototype.setCustomMesh=function(e){l.a.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)")},t}(Ln.a),Tr=f(46),Ls=f(84),Jo=function(r){function t(e,n,i,o){var a;n===void 0&&(n=M.a.Gray()),i===void 0&&(i=xn.a.DefaultUtilityLayer),o===void 0&&(o=null);var s=r.call(this,i)||this;s._pointerObserver=null,s.snapDistance=0,s.onSnapObservable=new x.c,s._isEnabled=!1,s._parent=null,s._dragging=!1,s._parent=o,s._coloredMaterial=new Ft.a("",i.utilityLayerScene),s._coloredMaterial.diffuseColor=n,s._coloredMaterial.specularColor=n.subtract(new M.a(.1,.1,.1)),s._hoverMaterial=new Ft.a("",i.utilityLayerScene),s._hoverMaterial.diffuseColor=M.a.Yellow(),s._disableMaterial=new Ft.a("",i.utilityLayerScene),s._disableMaterial.diffuseColor=M.a.Gray(),s._disableMaterial.alpha=.4,s._gizmoMesh=t._CreatePlane(i.utilityLayerScene,s._coloredMaterial),s._gizmoMesh.lookAt(s._rootMesh.position.add(e)),s._gizmoMesh.scaling.scaleInPlace(1/3),s._gizmoMesh.parent=s._rootMesh;var d=0,p=new u.e,y={snapDistance:0};s.dragBehavior=new bi.a({dragPlaneNormal:e}),s.dragBehavior.moveAttached=!1,s._rootMesh.addBehavior(s.dragBehavior),s.dragBehavior.onDragObservable.add(function(U){if(s.attachedNode){if(s.snapDistance==0)s.attachedNode.getWorldMatrix().addTranslationFromFloats(U.delta.x,U.delta.y,U.delta.z);else if(d+=U.dragDistance,Math.abs(d)>s.snapDistance){var F=Math.floor(Math.abs(d)/s.snapDistance);d%=s.snapDistance,U.delta.normalizeToRef(p),p.scaleInPlace(s.snapDistance*F),s.attachedNode.getWorldMatrix().addTranslationFromFloats(p.x,p.y,p.z),y.snapDistance=s.snapDistance*F,s.onSnapObservable.notifyObservers(y)}s._matrixChanged()}}),s.dragBehavior.onDragStartObservable.add(function(){s._dragging=!0}),s.dragBehavior.onDragEndObservable.add(function(){s._dragging=!1});var P=i._getSharedGizmoLight();P.includedOnlyMeshes=P.includedOnlyMeshes.concat(s._rootMesh.getChildMeshes(!1));var O={gizmoMeshes:s._gizmoMesh.getChildMeshes(),colliderMeshes:s._gizmoMesh.getChildMeshes(),material:s._coloredMaterial,hoverMaterial:s._hoverMaterial,disableMaterial:s._disableMaterial,active:!1};return(a=s._parent)===null||a===void 0||a.addToAxisCache(s._gizmoMesh,O),s._pointerObserver=i.utilityLayerScene.onPointerObservable.add(function(U){var F;if(!s._customMeshSet&&(s._isHovered=O.colliderMeshes.indexOf((F=U?.pickInfo)===null||F===void 0?void 0:F.pickedMesh)!=-1,!s._parent)){var z=s._isHovered||s._dragging?s._hoverMaterial:s._coloredMaterial;O.gizmoMeshes.forEach(function(J){J.material=z})}}),s}return Object(c.d)(t,r),t._CreatePlane=function(e,n){var i=new Tr.a("plane",e),o=Ls.a.CreatePlane("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return o.material=n,o.parent=i,i},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),r.prototype.dispose.call(this),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(function(e){e&&e.dispose()})},t}(Ln.a),Tu=function(r){function t(e,n,i){e===void 0&&(e=xn.a.DefaultUtilityLayer),n===void 0&&(n=1);var o=r.call(this,e)||this;return o._meshAttached=null,o._nodeAttached=null,o._observables=[],o._gizmoAxisCache=new Map,o.onDragStartObservable=new x.c,o.onDragEndObservable=new x.c,o._planarGizmoEnabled=!1,o.xGizmo=new qo.a(new u.e(1,0,0),M.a.Red().scale(.5),e,o,n),o.yGizmo=new qo.a(new u.e(0,1,0),M.a.Green().scale(.5),e,o,n),o.zGizmo=new qo.a(new u.e(0,0,1),M.a.Blue().scale(.5),e,o,n),o.xPlaneGizmo=new Jo(new u.e(1,0,0),M.a.Red().scale(.5),o.gizmoLayer,o),o.yPlaneGizmo=new Jo(new u.e(0,1,0),M.a.Green().scale(.5),o.gizmoLayer,o),o.zPlaneGizmo=new Jo(new u.e(0,0,1),M.a.Blue().scale(.5),o.gizmoLayer,o),[o.xGizmo,o.yGizmo,o.zGizmo,o.xPlaneGizmo,o.yPlaneGizmo,o.zPlaneGizmo].forEach(function(a){a.dragBehavior.onDragStartObservable.add(function(){o.onDragStartObservable.notifyObservers({})}),a.dragBehavior.onDragEndObservable.add(function(){o.onDragEndObservable.notifyObservers({})})}),o.attachedMesh=null,i?i.addToAxisCache(o._gizmoAxisCache):Ln.a.GizmoAxisPointerObserver(e,o._gizmoAxisCache),o}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){n.isEnabled?n.attachedMesh=e:n.attachedMesh=null})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=null,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){n.isEnabled?n.attachedNode=e:n.attachedNode=null})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isHovered",{get:function(){var e=!1;return[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){e=e||n.isHovered}),e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"planarGizmoEnabled",{get:function(){return this._planarGizmoEnabled},set:function(e){var n=this;this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(i){i&&(i.isEnabled=e,e&&(i.attachedMesh?i.attachedMesh=n.attachedMesh:i.attachedNode=n.attachedNode))},this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){n&&(n.updateGizmoRotationToMatchAttachedMesh=e)})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){n&&(n.snapDistance=e)})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){n&&(n.scaleRatio=e)})},enumerable:!1,configurable:!0}),t.prototype.addToAxisCache=function(e,n){this._gizmoAxisCache.set(e,n)},t.prototype.dispose=function(){var e=this;[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(function(n){n&&n.dispose()}),this._observables.forEach(function(n){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(n)}),this.onDragStartObservable.clear(),this.onDragEndObservable.clear()},t.prototype.setCustomMesh=function(e){l.a.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)")},t}(Ln.a);ft.a.CreatePolyhedron=function(r){var t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};var e,n,i,o,a,s,d=r.type&&(r.type<0||r.type>=t.length)?0:r.type||0,p=r.size,y=r.sizeX||p||1,P=r.sizeY||p||1,O=r.sizeZ||p||1,U=r.custom||t[d],F=U.face.length,z=r.faceUV||new Array(F),J=r.faceColors,ie=r.flat===void 0||r.flat,se=r.sideOrientation===0?0:r.sideOrientation||ft.a.DEFAULTSIDE,ce=new Array,ue=new Array,fe=new Array,ve=new Array,Te=new Array,Oe=0,Pe=0,Ee=new Array,Se=0,Le=0;if(ie)for(Le=0;Le0&&t.forEach(function(n,i){e._gizmoAxisCache.set(i,n)})},r.prototype.dispose=function(){var t=this;for(var e in this._pointerObservers.forEach(function(i){t.scene.onPointerObservable.remove(i)}),this.gizmos){var n=this.gizmos[e];n&&n.dispose()}this._defaultKeepDepthUtilityLayer.dispose(),this._defaultUtilityLayer.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()},r}(),Ci=f(48),$o=function(r){function t(){var e=r!==null&&r.apply(this,arguments)||this;return e._needProjectionMatrixCompute=!0,e}return Object(c.d)(t,r),t.prototype._setPosition=function(e){this._position=e},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!1,configurable:!0}),t.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),t.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=u.e.Zero()),u.e.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=u.e.Zero()),u.e.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)},t.prototype.getDepthScale=function(){return 50},t.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},t.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},t.prototype.setDirectionToTarget=function(e){return this.direction=u.e.Normalize(e.subtract(this.position)),this.direction},t.prototype.getRotation=function(){this.direction.normalize();var e=u.e.Cross(this.direction,ye.a.Y),n=u.e.Cross(e,this.direction);return u.e.RotationFromAxis(e,n,this.direction)},t.prototype.needCube=function(){return!1},t.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},t.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},t.prototype._initCache=function(){r.prototype._initCache.call(this),this._cache.position=u.e.Zero()},t.prototype._isSynchronized=function(){return!!this._cache.position.equals(this.position)},t.prototype.computeWorldMatrix=function(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=u.a.Identity()),u.a.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)},t.prototype.getDepthMinZ=function(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ},t.prototype.getDepthMaxZ=function(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ},t.prototype.setShadowProjectionMatrix=function(e,n,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(n,i,e):this._setDefaultShadowProjectionMatrix(e,n,i),this},Object(c.c)([Object(L.o)()],t.prototype,"position",null),Object(c.c)([Object(L.o)()],t.prototype,"direction",null),Object(c.c)([Object(L.c)()],t.prototype,"shadowMinZ",null),Object(c.c)([Object(L.c)()],t.prototype,"shadowMaxZ",null),t}(Ci.a);Q.a.AddNodeConstructor("Light_Type_1",function(r,t){return function(){return new Ns(r,u.e.Zero(),t)}});var Ns=function(r){function t(e,n,i){var o=r.call(this,e,i)||this;return o._shadowFrustumSize=0,o._shadowOrthoScale=.1,o.autoUpdateExtends=!0,o.autoCalcShadowZBounds=!1,o._orthoLeft=Number.MAX_VALUE,o._orthoRight=Number.MIN_VALUE,o._orthoTop=Number.MIN_VALUE,o._orthoBottom=Number.MAX_VALUE,o.position=n.scale(-1),o.direction=n,o}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"DirectionalLight"},t.prototype.getTypeID=function(){return Ci.a.LIGHTTYPEID_DIRECTIONALLIGHT},t.prototype._setDefaultShadowProjectionMatrix=function(e,n,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,n,i)},t.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(e){var n=this.getScene().activeCamera;n&&u.a.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:n.minZ,this.shadowMaxZ!==void 0?this.shadowMaxZ:n.maxZ,e)},t.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(e,n,i){var o=this.getScene().activeCamera;if(o){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var a=u.e.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=Number.MAX_VALUE,d=Number.MIN_VALUE,p=0;pthis._orthoRight&&(this._orthoRight=a.x),a.y>this._orthoTop&&(this._orthoTop=a.y),this.autoCalcShadowZBounds&&(a.zd&&(d=a.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=d)}var U=this._orthoRight-this._orthoLeft,F=this._orthoTop-this._orthoBottom;u.a.OrthoOffCenterLHToRef(this._orthoLeft-U*this.shadowOrthoScale,this._orthoRight+U*this.shadowOrthoScale,this._orthoBottom-F*this.shadowOrthoScale,this._orthoTop+F*this.shadowOrthoScale,this.shadowMinZ!==void 0?this.shadowMinZ:o.minZ,this.shadowMaxZ!==void 0?this.shadowMaxZ:o.maxZ,e)}},t.prototype._buildUniformLayout=function(){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()},t.prototype.transferToEffect=function(e,n){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,n),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,n),this)},t.prototype.transferToNodeMaterialEffect=function(e,n){return this.computeTransformedInformation()?(e.setFloat3(n,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(n,this.direction.x,this.direction.y,this.direction.z),this)},t.prototype.getDepthMinZ=function(e){return 1},t.prototype.getDepthMaxZ=function(e){return 1},t.prototype.prepareLightSpecificDefines=function(e,n){e["DIRLIGHT"+n]=!0},Object(c.c)([Object(L.c)()],t.prototype,"shadowFrustumSize",null),Object(c.c)([Object(L.c)()],t.prototype,"shadowOrthoScale",null),Object(c.c)([Object(L.c)()],t.prototype,"autoUpdateExtends",void 0),Object(c.c)([Object(L.c)()],t.prototype,"autoCalcShadowZBounds",void 0),t}($o);De.a.CreateHemisphere=function(r,t,e,n){var i={segments:t,diameter:e};return ea.CreateHemisphere(r,i,n)};var ea=function(){function r(){}return r.CreateHemisphere=function(t,e,n){e.diameter||(e.diameter=1),e.segments||(e.segments=16);var i=Nn.a.CreateSphere("",{slice:.5,diameter:e.diameter,segments:e.segments},n),o=De.a.CreateDisc("",e.diameter/2,3*e.segments+(4-e.segments),n);o.rotation.x=-Math.PI/2,o.parent=i;var a=De.a.MergeMeshes([o,i],!0);return a.name=t,a},r}();Q.a.AddNodeConstructor("Light_Type_2",function(r,t){return function(){return new ws(r,u.e.Zero(),u.e.Zero(),0,0,t)}});var ws=function(r){function t(e,n,i,o,a,s){var d=r.call(this,e,s)||this;return d._innerAngle=0,d._projectionTextureMatrix=u.a.Zero(),d._projectionTextureLightNear=1e-6,d._projectionTextureLightFar=1e3,d._projectionTextureUpDirection=u.e.Up(),d._projectionTextureViewLightDirty=!0,d._projectionTextureProjectionLightDirty=!0,d._projectionTextureDirty=!0,d._projectionTextureViewTargetVector=u.e.Zero(),d._projectionTextureViewLightMatrix=u.a.Zero(),d._projectionTextureProjectionLightMatrix=u.a.Zero(),d._projectionTextureScalingMatrix=u.a.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),d.position=n,d.direction=i,d.angle=o,d.exponent=a,d}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"innerAngle",{get:function(){return this._innerAngle},set:function(e){this._innerAngle=e,this._computeAngleValues()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){var n=this;this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(t._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(function(){n._markMeshesAsLightDirty()}):t._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(function(){n._markMeshesAsLightDirty()})))},enumerable:!1,configurable:!0}),t._IsProceduralTexture=function(e){return e.onGeneratedObservable!==void 0},t._IsTexture=function(e){return e.onLoadObservable!==void 0},t.prototype.getClassName=function(){return"SpotLight"},t.prototype.getTypeID=function(){return Ci.a.LIGHTTYPEID_SPOTLIGHT},t.prototype._setDirection=function(e){r.prototype._setDirection.call(this,e),this._projectionTextureViewLightDirty=!0},t.prototype._setPosition=function(e){r.prototype._setPosition.call(this,e),this._projectionTextureViewLightDirty=!0},t.prototype._setDefaultShadowProjectionMatrix=function(e,n,i){var o=this.getScene().activeCamera;if(o){this._shadowAngleScale=this._shadowAngleScale||1;var a=this._shadowAngleScale*this._angle;u.a.PerspectiveFovLHToRef(a,1,this.getDepthMinZ(o),this.getDepthMaxZ(o),e)}},t.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),u.a.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},t.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var e=this.projectionTextureLightFar,n=this.projectionTextureLightNear,i=e/(e-n),o=-i*n,a=1/Math.tan(this._angle/2);u.a.FromValuesToRef(a/1,0,0,0,0,a,0,0,0,0,i,1,0,0,o,0,this._projectionTextureProjectionLightMatrix)},t.prototype._computeProjectionTextureMatrix=function(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof we.a){var e=this._projectionTexture.uScale/2,n=this._projectionTexture.vScale/2;u.a.FromValuesToRef(e,0,0,0,0,n,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},t.prototype._buildUniformLayout=function(){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()},t.prototype._computeAngleValues=function(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale},t.prototype.transferTexturesToEffect=function(e,n){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+n,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+n,this.projectionTexture)),this},t.prototype.transferToEffect=function(e,n){var i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,n),i=u.e.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,n),i=u.e.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,n),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,n),this},t.prototype.transferToNodeMaterialEffect=function(e,n){var i;return i=this.computeTransformedInformation()?u.e.Normalize(this.transformedDirection):u.e.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(n,-i.x,-i.y,-i.z):e.setFloat3(n,i.x,i.y,i.z),this},t.prototype.dispose=function(){r.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},t.prototype.prepareLightSpecificDefines=function(e,n){e["SPOTLIGHT"+n]=!0,e["PROJECTEDLIGHTTEXTURE"+n]=!(!this.projectionTexture||!this.projectionTexture.isReady())},Object(c.c)([Object(L.c)()],t.prototype,"angle",null),Object(c.c)([Object(L.c)()],t.prototype,"innerAngle",null),Object(c.c)([Object(L.c)()],t.prototype,"shadowAngleScale",null),Object(c.c)([Object(L.c)()],t.prototype,"exponent",void 0),Object(c.c)([Object(L.c)()],t.prototype,"projectionTextureLightNear",null),Object(c.c)([Object(L.c)()],t.prototype,"projectionTextureLightFar",null),Object(c.c)([Object(L.c)()],t.prototype,"projectionTextureUpDirection",null),Object(c.c)([Object(L.m)("projectedLightTexture")],t.prototype,"_projectionTexture",void 0),t}($o),wp=function(r){function t(e){e===void 0&&(e=xn.a.DefaultUtilityLayer);var n=r.call(this,e)||this;return n._cachedPosition=new u.e,n._cachedForward=new u.e(0,0,1),n._pointerObserver=null,n.onClickedObservable=new x.c,n._light=null,n.attachedMesh=new Dt.a("",n.gizmoLayer.utilityLayerScene),n._attachedMeshParent=new Tr.a("parent",n.gizmoLayer.utilityLayerScene),n.attachedMesh.parent=n._attachedMeshParent,n._material=new Ft.a("light",n.gizmoLayer.utilityLayerScene),n._material.diffuseColor=new M.a(.5,.5,.5),n._material.specularColor=new M.a(.1,.1,.1),n._pointerObserver=e.utilityLayerScene.onPointerObservable.add(function(i){n._light&&(n._isHovered=!(!i.pickInfo||n._rootMesh.getChildMeshes().indexOf(i.pickInfo.pickedMesh)==-1),n._isHovered&&i.event.button===0&&n.onClickedObservable.notifyObservers(n._light))},Tt.a.POINTERDOWN),n}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"light",{get:function(){return this._light},set:function(e){var n=this;if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof zo.a?this._lightMesh=t._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=e instanceof Ns?t._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof ws?t._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):t._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(function(o){o.material=n._material}),this._lightMesh.parent=this._rootMesh;var i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new u.b,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction&&(this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward)),this._update()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},enumerable:!1,configurable:!0}),t.prototype._update=function(){r.prototype._update.call(this),this._light&&(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position&&(this.attachedMesh.position.equals(this._cachedPosition)?(this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)):(this._light.position.copyFrom(this.attachedMesh.position),this._cachedPosition.copyFrom(this.attachedMesh.position))),this._light.direction&&(u.e.DistanceSquared(this.attachedMesh.forward,this._cachedForward)>1e-4?(this._light.direction.copyFrom(this.attachedMesh.forward),this._cachedForward.copyFrom(this.attachedMesh.forward)):u.e.DistanceSquared(this.attachedMesh.forward,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward))))},t.prototype.dispose=function(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),r.prototype.dispose.call(this),this._attachedMeshParent.dispose()},t._CreateHemisphericLightMesh=function(e){var n=new De.a("hemisphereLight",e),i=ea.CreateHemisphere(n.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=n;var o=this._CreateLightLines(3,e);return o.parent=n,o.position.z,n.scaling.scaleInPlace(t._Scale),n.rotation.x=Math.PI/2,n},t._CreatePointLightMesh=function(e){var n=new De.a("pointLight",e),i=Nn.a.CreateSphere(n.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=n,this._CreateLightLines(5,e).parent=n,n.scaling.scaleInPlace(t._Scale),n.rotation.x=Math.PI/2,n},t._CreateSpotLightMesh=function(e){var n=new De.a("spotLight",e);Nn.a.CreateSphere(n.name,{segments:10,diameter:1},e).parent=n;var i=ea.CreateHemisphere(n.name,{segments:10,diameter:2},e);return i.parent=n,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=n,n.scaling.scaleInPlace(t._Scale),n.rotation.x=Math.PI/2,n},t._CreateDirectionalLightMesh=function(e){var n=new De.a("directionalLight",e),i=new De.a(n.name,e);i.parent=n,Nn.a.CreateSphere(n.name,{diameter:1.2,segments:10},e).parent=i;var o=De.a.CreateCylinder(n.name,6,.3,.3,6,1,e);o.parent=i,(a=o.clone(n.name)).scaling.y=.5,a.position.x+=1.25,(s=o.clone(n.name)).scaling.y=.5,s.position.x+=-1.25;var a,s,d=De.a.CreateCylinder(n.name,1,0,.6,6,1,e);return d.position.y+=3,d.parent=i,(a=d.clone(n.name)).position.y=1.5,a.position.x+=1.25,(s=d.clone(n.name)).position.y=1.5,s.position.x+=-1.25,i.scaling.scaleInPlace(t._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,n},t._Scale=.007,t._CreateLightLines=function(e,n){var i=new De.a("root",n);i.rotation.x=Math.PI/2;var o=new De.a("linePivot",n);o.parent=i;var a=De.a.CreateCylinder("line",2,.2,.3,6,1,n);if(a.position.y=a.scaling.y/2+1.2,a.parent=o,e<2)return o;for(var s=0;s<4;s++)(d=o.clone("lineParentClone")).rotation.z=Math.PI/4,d.rotation.y=Math.PI/2+Math.PI/2*s,d.getChildMeshes()[0].scaling.y=.5,d.getChildMeshes()[0].scaling.x=d.getChildMeshes()[0].scaling.z=.8,d.getChildMeshes()[0].position.y=d.getChildMeshes()[0].scaling.y/2+1.2;if(e<3)return i;for(s=0;s<4;s++)(d=o.clone("linePivotClone")).rotation.z=Math.PI/2,d.rotation.y=Math.PI/2*s;if(e<4)return i;for(s=0;s<4;s++){var d;(d=o.clone("linePivotClone")).rotation.z=Math.PI+Math.PI/4,d.rotation.y=Math.PI/2+Math.PI/2*s,d.getChildMeshes()[0].scaling.y=.5,d.getChildMeshes()[0].scaling.x=d.getChildMeshes()[0].scaling.z=.8,d.getChildMeshes()[0].position.y=d.getChildMeshes()[0].scaling.y/2+1.2}return e<5||((d=o.clone("linePivotClone")).rotation.z=Math.PI),i},t}(Ln.a),Fs=function(){function r(t,e){t===void 0&&(t=u.e.Zero()),e===void 0&&(e=u.e.Up()),this.position=t,this.normal=e}return r.prototype.clone=function(){return new r(this.position.clone(),this.normal.clone())},r}(),Fp=function(){function r(t,e,n){t===void 0&&(t=u.e.Zero()),e===void 0&&(e=u.e.Up()),n===void 0&&(n=u.d.Zero()),this.position=t,this.normal=e,this.uv=n}return r.prototype.clone=function(){return new r(this.position.clone(),this.normal.clone(),this.uv.clone())},r}(),Bp=function(r){function t(e){e===void 0&&(e=xn.a.DefaultUtilityLayer);var n=r.call(this,e)||this;return n._pointerObserver=null,n.onClickedObservable=new x.c,n._camera=null,n._invProjection=new u.a,n._material=new Ft.a("cameraGizmoMaterial",n.gizmoLayer.utilityLayerScene),n._material.diffuseColor=new M.a(.5,.5,.5),n._material.specularColor=new M.a(.1,.1,.1),n._pointerObserver=e.utilityLayerScene.onPointerObservable.add(function(i){n._camera&&(n._isHovered=!(!i.pickInfo||n._rootMesh.getChildMeshes().indexOf(i.pickInfo.pickedMesh)==-1),n._isHovered&&i.event.button===0&&n.onClickedObservable.notifyObservers(n._camera))},Tt.a.POINTERDOWN),n}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"displayFrustum",{get:function(){return this._cameraLinesMesh.isEnabled()},set:function(e){this._cameraLinesMesh.setEnabled(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"camera",{get:function(){return this._camera},set:function(e){var n=this;if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=t._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=t._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(function(o){o.material=n._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;var i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},enumerable:!1,configurable:!0}),t.prototype._update=function(){r.prototype._update.call(this),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)},t.prototype.dispose=function(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),r.prototype.dispose.call(this)},t._CreateCameraMesh=function(e){var n=new De.a("rootCameraGizmo",e),i=new De.a(n.name,e);i.parent=n,yr.a.CreateBox(n.name,{width:1,height:.8,depth:.5},e).parent=i;var o=ui.a.CreateCylinder(n.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);o.parent=i,o.position.y=.3,o.position.x=-.6,o.rotation.x=.5*Math.PI;var a=ui.a.CreateCylinder(n.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;var s=ui.a.CreateCylinder(n.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return s.parent=i,s.position.y=0,s.position.x=.6,s.rotation.z=.5*Math.PI,n.scaling.scaleInPlace(t._Scale),i.position.x=-.9,n},t._CreateCameraFrustum=function(e){var n=new De.a("rootCameraGizmo",e),i=new De.a(n.name,e);i.parent=n;for(var o=0;o<4;o+=2)for(var a=0;a<4;a+=2){var s;(s=cn.a.CreateLines("lines",{points:[new u.e(-1+a,-1+o,-1),new u.e(-1+a,-1+o,1)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=cn.a.CreateLines("lines",{points:[new u.e(-1,-1+a,-1+o),new u.e(1,-1+a,-1+o)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=cn.a.CreateLines("lines",{points:[new u.e(-1+a,-1,-1+o),new u.e(-1+a,1,-1+o)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return n},t._Scale=.05,t}(Ln.a);je.a.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";var Up=`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); -}`;je.a.IncludesShadersStore.packingFunctions=Up;var Vp=`#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`;je.a.IncludesShadersStore.kernelBlurFragment=Vp;var kp=`#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`;je.a.IncludesShadersStore.kernelBlurFragment2=kp;var Gp=` -uniform sampler2D textureSampler; -uniform vec2 delta; - -varying vec2 sampleCenter; -#ifdef DOF -uniform sampler2D circleOfConfusionSampler; -uniform vec2 cameraMinMaxZ; -float sampleDistance(const in vec2 offset) { -float depth=texture2D(circleOfConfusionSampler,offset).g; -return cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; -} -float sampleCoC(const in vec2 offset) { -float coc=texture2D(circleOfConfusionSampler,offset).r; -return coc; -} -#endif -#include[0..varyingCount] -#ifdef PACKEDFLOAT -#include -#endif -void main(void) -{ -float computedWeight=0.0; -#ifdef PACKEDFLOAT -float blend=0.; -#else -vec4 blend=vec4(0.); -#endif -#ifdef DOF -float sumOfWeights=CENTER_WEIGHT; -float factor=0.0; - -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; -#else -blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; -#endif -#endif -#include[0..varyingCount] -#include[0..depCount] -#ifdef PACKEDFLOAT -gl_FragColor=pack(blend); -#else -gl_FragColor=blend; -#endif -#ifdef DOF -gl_FragColor/=sumOfWeights; -#endif -}`;je.a.ShadersStore.kernelBlurPixelShader=Gp,je.a.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";var zp=` -attribute vec2 position; - -uniform vec2 delta; - -varying vec2 sampleCenter; -#include[0..varyingCount] -const vec2 madd=vec2(0.5,0.5); -void main(void) { -sampleCenter=(position*madd+madd); -#include[0..varyingCount] -gl_Position=vec4(position,0.0,1.0); -}`;je.a.ShadersStore.kernelBlurVertexShader=zp;var _n=function(r){function t(e,n,i,o,a,s,d,p,y,P,O){s===void 0&&(s=we.a.BILINEAR_SAMPLINGMODE),y===void 0&&(y=h.a.TEXTURETYPE_UNSIGNED_INT),P===void 0&&(P=""),O===void 0&&(O=!1);var U=r.call(this,e,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],o,a,s,d,p,null,y,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return U.blockCompilation=O,U._packedFloat=!1,U._staticDefines="",U._staticDefines=P,U.direction=n,U.onApplyObservable.add(function(F){U._outputTexture?F.setFloat2("delta",1/U._outputTexture.width*U.direction.x,1/U._outputTexture.height*U.direction.y):F.setFloat2("delta",1/U.width*U.direction.x,1/U.height*U.direction.y)}),U.kernel=i,U}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.blockCompilation||this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this.blockCompilation||this._updateParameters())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"BlurPostProcess"},t.prototype.updateEffect=function(e,n,i,o,a,s){this._updateParameters(a,s)},t.prototype._updateParameters=function(e,n){for(var i=this._kernel,o=(i-1)/2,a=[],s=[],d=0,p=0;p0)return Math.max(a,3)}return Math.max(n,3)},t.prototype._gaussianWeight=function(e){var n=-e*e/.2222222222222222;return 1/(Math.sqrt(2*Math.PI)*(1/3))*Math.exp(n)},t.prototype._glslFloat=function(e,n){return n===void 0&&(n=8),e.toFixed(n).replace(/0+$/,"")},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.direction,e.kernel,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)},e,i,o)},Object(c.c)([Object(L.c)("kernel")],t.prototype,"_kernel",void 0),Object(c.c)([Object(L.c)("packedFloat")],t.prototype,"_packedFloat",void 0),Object(c.c)([Object(L.n)()],t.prototype,"direction",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.BlurPostProcess"]=_n;var Bs=function(r){function t(e,n,i,o,a,s,d){a===void 0&&(a=h.a.TEXTURETYPE_UNSIGNED_INT),s===void 0&&(s=we.a.BILINEAR_SAMPLINGMODE),d===void 0&&(d=!0);var p=r.call(this,e,n,i,o,!0,a,!1,s,d)||this;return p.scene=i,p.mirrorPlane=new gr.a(0,1,0,1),p._transformMatrix=u.a.Zero(),p._mirrorMatrix=u.a.Zero(),p._adaptiveBlurKernel=0,p._blurKernelX=0,p._blurKernelY=0,p._blurRatio=1,p.ignoreCameraViewport=!0,p._updateGammaSpace(),p._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(function(){p._updateGammaSpace}),p.onBeforeRenderObservable.add(function(){u.a.ReflectionToRef(p.mirrorPlane,p._mirrorMatrix),p._savedViewMatrix=i.getViewMatrix(),p._mirrorMatrix.multiplyToRef(p._savedViewMatrix,p._transformMatrix),i.setTransformMatrix(p._transformMatrix,i.getProjectionMatrix()),i.clipPlane=p.mirrorPlane,i.getEngine().cullBackFaces=!1,i._mirroredCameraPosition=u.e.TransformCoordinates(i.activeCamera.globalPosition,p._mirrorMatrix)}),p.onAfterRenderObservable.add(function(){i.setTransformMatrix(p._savedViewMatrix,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!0,i._mirroredCameraPosition=null,i.clipPlane=null}),p}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),t.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),n=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*n,this.blurKernelY=this._adaptiveBlurKernel*i},t.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},t.prototype._updateGammaSpace=function(){this.gammaSpace=!this.scene.imageProcessingConfiguration.isEnabled||!this.scene.imageProcessingConfiguration.applyByPostProcess},t.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var e=this.getScene().getEngine(),n=e.getCaps().textureFloatRender?h.a.TEXTURETYPE_FLOAT:h.a.TEXTURETYPE_HALF_FLOAT;this._blurX=new _n("horizontal blur",new u.d(1,0),this._blurKernelX,this._blurRatio,null,we.a.BILINEAR_SAMPLINGMODE,e,!1,n),this._blurX.autoClear=!1,this._blurRatio===1&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new _n("vertical blur",new u.d(0,1),this._blurKernelY,this._blurRatio,null,we.a.BILINEAR_SAMPLINGMODE,e,!1,n),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=this._blurRatio!==1,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var n=this.getSize(),i=new t(this.name,n.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},t.prototype.serialize=function(){if(!this.name)return null;var e=r.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},t.prototype.dispose=function(){r.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},t}(sn);we.a._CreateMirror=function(r,t,e,n){return new Bs(r,t,e,n)};var Xn=f(34),ni=function(r){function t(e,n,i,o,a,s,d,p,y,P,O,U,F,z){var J;i===void 0&&(i=null),o===void 0&&(o=!1),a===void 0&&(a=null),s===void 0&&(s=null),d===void 0&&(d=null),p===void 0&&(p=h.a.TEXTUREFORMAT_RGBA),y===void 0&&(y=!1),P===void 0&&(P=null),O===void 0&&(O=!1),U===void 0&&(U=.8),F===void 0&&(F=0);var ie=r.call(this,n)||this;if(ie.onLoadObservable=new x.c,ie.boundingBoxPosition=u.e.Zero(),ie._rotationY=0,ie._files=null,ie._forcedExtension=null,ie._extensions=null,ie.name=e,ie.url=e,ie._noMipmap=o,ie.hasAlpha=!1,ie._format=p,ie.isCube=!0,ie._textureMatrix=u.a.Identity(),ie._createPolynomials=O,ie.coordinatesMode=we.a.CUBIC_MODE,ie._extensions=i,ie._files=a,ie._forcedExtension=P,ie._loaderOptions=z,!e&&!a)return ie;var se=e.lastIndexOf("."),ce=P||(se>-1?e.substring(se).toLowerCase():""),ue=ce===".dds",fe=ce===".env";if(fe?(ie.gammaSpace=!1,ie._prefiltered=!1,ie.anisotropicFilteringLevel=1):(ie._prefiltered=y,y&&(ie.gammaSpace=!1,ie.anisotropicFilteringLevel=1)),ie._texture=ie._getFromCache(e,o),!a&&(fe||ue||i||(i=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),a=[],i))for(var ve=0;ve -#define RECIPROCAL_PI2 0.15915494 - -uniform vec3 vEyePosition; - -varying vec3 vPositionW; -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef DIFFUSE -#if DIFFUSEDIRECTUV == 1 -#define vDiffuseUV vMainUV1 -#elif DIFFUSEDIRECTUV == 2 -#define vDiffuseUV vMainUV2 -#else -varying vec2 vDiffuseUV; -#endif -uniform sampler2D diffuseSampler; -#endif - -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow; -uniform samplerCube reflectionSamplerHigh; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow; -uniform samplerCube reflectionSamplerHigh; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include -#endif - -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE; -#endif - -#ifndef SHADOWONLY -#define SHADOWONLY; -#endif -#include - -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include -#include -#include - -#include -#ifdef REFLECTIONFRESNEL -#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{ - -float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness); -return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN)); -} -#endif -void main(void) { -#include -vec3 viewDirectionW=normalize(vEyePosition-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[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),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-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 -#ifdef IMAGEPROCESSINGPOSTPROCESS - - -color.rgb=clamp(color.rgb,0.,30.0); -#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; -} -`;je.a.ShadersStore.backgroundPixelShader=Wp;var Xp=`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`;je.a.IncludesShadersStore.backgroundVertexDeclaration=Xp,f(78),f(79),f(117),f(137),f(80),f(81),f(111),f(157),f(138);var Yp=`precision highp float; -#include<__decl__backgroundVertex> -#include - -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include - -#include - -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 -varying vec2 vDiffuseUV; -#endif -#include -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -void main(void) { -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=position; -#endif -#include -#include -#ifdef MULTIVIEW -if (gl_ViewID_OVR == 0u) { -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -} else { -gl_Position=viewProjectionR*finalWorld*vec4(position,1.0); -} -#else -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#endif -vec4 worldPos=finalWorld*vec4(position,1.0); -vPositionW=vec3(worldPos); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normal); -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); -#ifdef EQUIRECTANGULAR_RELFECTION_FOV -mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection)); -vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0)); -if (fFovMultiplier<=1.0) { -vDirectionW=normalize(segment); -} else { -vDirectionW=normalize(vDirectionW+(vDirectionW-segment)); -} -#endif -#endif -#ifndef UV1 -vec2 uv=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uv; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 -if (vDiffuseInfos.x == 0.) -{ -vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0)); -} -else -{ -vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -} -#endif - -#include - -#include - -#include[0..maxSimultaneousLights] - -#ifdef VERTEXCOLOR -vColor=color; -#endif - -#ifdef POINTSIZE -gl_PointSize=pointSize; -#endif -} -`;je.a.ShadersStore.backgroundVertexShader=Yp;var Er=f(67),Kp=function(r){function t(){var e=r.call(this)||this;return e.DIFFUSE=!1,e.DIFFUSEDIRECTUV=0,e.GAMMADIFFUSE=!1,e.DIFFUSEHASALPHA=!1,e.OPACITYFRESNEL=!1,e.REFLECTIONBLUR=!1,e.REFLECTIONFRESNEL=!1,e.REFLECTIONFALLOFF=!1,e.TEXTURELODSUPPORT=!1,e.PREMULTIPLYALPHA=!1,e.USERGBCOLOR=!1,e.USEHIGHLIGHTANDSHADOWCOLORS=!1,e.BACKMAT_SHADOWONLY=!1,e.NOISE=!1,e.REFLECTIONBGR=!1,e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.EXPOSURE=!1,e.MULTIVIEW=!1,e.REFLECTION=!1,e.REFLECTIONMAP_3D=!1,e.REFLECTIONMAP_SPHERICAL=!1,e.REFLECTIONMAP_PLANAR=!1,e.REFLECTIONMAP_CUBIC=!1,e.REFLECTIONMAP_PROJECTION=!1,e.REFLECTIONMAP_SKYBOX=!1,e.REFLECTIONMAP_EXPLICIT=!1,e.REFLECTIONMAP_EQUIRECTANGULAR=!1,e.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,e.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.INVERTCUBICMAP=!1,e.REFLECTIONMAP_OPPOSITEZ=!1,e.LODINREFLECTIONALPHA=!1,e.GAMMAREFLECTION=!1,e.RGBDREFLECTION=!1,e.EQUIRECTANGULAR_RELFECTION_FOV=!1,e.MAINUV1=!1,e.MAINUV2=!1,e.UV1=!1,e.UV2=!1,e.CLIPPLANE=!1,e.CLIPPLANE2=!1,e.CLIPPLANE3=!1,e.CLIPPLANE4=!1,e.CLIPPLANE5=!1,e.CLIPPLANE6=!1,e.POINTSIZE=!1,e.FOG=!1,e.NORMAL=!1,e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.INSTANCES=!1,e.SHADOWFLOAT=!1,e.rebuild(),e}return Object(c.d)(t,r),t}(ta.a),ao=function(r){function t(e,n){var i=r.call(this,e,n)||this;return i.primaryColor=M.a.White(),i._primaryColorShadowLevel=0,i._primaryColorHighlightLevel=0,i.reflectionTexture=null,i.reflectionBlur=0,i.diffuseTexture=null,i._shadowLights=null,i.shadowLights=null,i.shadowLevel=0,i.sceneCenter=u.e.Zero(),i.opacityFresnel=!0,i.reflectionFresnel=!1,i.reflectionFalloffDistance=0,i.reflectionAmount=1,i.reflectionReflectance0=.05,i.reflectionReflectance90=.5,i.useRGBColor=!0,i.enableNoise=!1,i._fovMultiplier=1,i.useEquirectangularFOV=!1,i._maxSimultaneousLights=4,i.maxSimultaneousLights=4,i._shadowOnly=!1,i.shadowOnly=!1,i._imageProcessingObserver=null,i.switchToBGR=!1,i._renderTargets=new li.a(16),i._reflectionControls=u.f.Zero(),i._white=M.a.White(),i._primaryShadowColor=M.a.Black(),i._primaryHighlightColor=M.a.Black(),i._attachImageProcessingConfiguration(null),i.getRenderTargetTextures=function(){return i._renderTargets.reset(),i._diffuseTexture&&i._diffuseTexture.isRenderTarget&&i._renderTargets.push(i._diffuseTexture),i._reflectionTexture&&i._reflectionTexture.isRenderTarget&&i._renderTargets.push(i._reflectionTexture),i._renderTargets},i}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflectionStandardFresnelWeight",{set:function(e){var n=e;n<.5?(n*=2,this.reflectionReflectance0=t.StandardReflectance0*n,this.reflectionReflectance90=t.StandardReflectance90*n):(n=2*n-1,this.reflectionReflectance0=t.StandardReflectance0+(1-t.StandardReflectance0)*n,this.reflectionReflectance90=t.StandardReflectance90+(1-t.StandardReflectance90)*n)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var n=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){n._computePrimaryColorFromPerceptualColor(),n._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)},enumerable:!1,configurable:!0}),t.prototype.needAlphaTesting=function(){return!0},t.prototype.needAlphaBlending=function(){return this.alpha<1||this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._shadowOnly},t.prototype.isReadyForSubMesh=function(e,n,i){var o=this;if(i===void 0&&(i=!1),n.effect&&this.isFrozen&&n.effect._wasPreviouslyReady)return!0;n._materialDefines||(n._materialDefines=new Kp);var a=this.getScene(),s=n._materialDefines;if(this._isReadyForSubMesh(n))return!0;var d=a.getEngine();if(tt.a.PrepareDefinesForLights(a,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,tt.a.PrepareDefinesForMultiview(a,s),s._areTexturesDirty){if(s._needUVs=!1,a.texturesEnabled){if(a.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&ht.a.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;tt.a.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;var p=this._reflectionTexture;if(p&&ht.a.ReflectionTextureEnabled){if(!p.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=p.gammaSpace,s.RGBDREFLECTION=p.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!p.invertZ:p.invertZ,s.LODINREFLECTIONALPHA=p.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,p.coordinatesMode===we.a.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=p.isCube,p.coordinatesMode){case we.a.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case we.a.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case we.a.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case we.a.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case we.a.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case we.a.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case we.a.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case we.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case we.a.CUBIC_MODE:case we.a.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=this.alphaMode===h.a.ALPHA_PREMULTIPLIED||this.alphaMode===h.a.ALPHA_PREMULTIPLIED_PORTERDUFF,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(tt.a.PrepareDefinesForMisc(e,a,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),tt.a.PrepareDefinesForFrameBoundValues(a,d,s,i,null,n.getRenderingMesh().hasThinInstances),tt.a.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&(a.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Me.b.NormalKind)||(e.createNormals(!0),l.a.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),s.isDirty){s.markAsProcessed(),a.resetCachedMaterial();var y=new Er.a;s.FOG&&y.addFallback(0,"FOG"),s.POINTSIZE&&y.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&y.addFallback(0,"MULTIVIEW"),tt.a.HandleFallbacksForShadows(s,y,this._maxSimultaneousLights);var P=[Me.b.PositionKind];s.NORMAL&&P.push(Me.b.NormalKind),s.UV1&&P.push(Me.b.UVKind),s.UV2&&P.push(Me.b.UV2Kind),tt.a.PrepareAttributesForBones(P,e,s,y),tt.a.PrepareAttributesForInstances(P,s);var O=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],U=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],F=["Material","Scene"];vn.a&&(vn.a.PrepareUniforms(O,s),vn.a.PrepareSamplers(U,s)),tt.a.PrepareUniformsAndSamplersList({uniformsNames:O,uniformBuffersNames:F,samplers:U,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});var z=s.toString();n.setEffect(a.getEngine().createEffect("background",{attributes:P,uniformsNames:O,uniformBuffersNames:F,samplers:U,defines:z,fallbacks:y,onCompiled:function(J){o.onCompiled&&o.onCompiled(J),o.bindSceneUniformBuffer(J,a.getSceneUniformBuffer())},onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},d),s),this.buildUniformLayout()}return!(!n.effect||!n.effect.isReady())&&(s._renderId=a.getRenderId(),n.effect._wasPreviouslyReady=!0,!0)},t.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},t.prototype._computePrimaryColors=function(){this._primaryColorShadowLevel===0&&this._primaryColorHighlightLevel===0||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},t.prototype.buildUniformLayout=function(){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()},t.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),r.prototype.unbind.call(this)},t.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},t.prototype.bindForSubMesh=function(e,n,i){var o=this.getScene(),a=i._materialDefines;if(a){var s=i.effect;if(s){this._activeEffect=s,this.bindOnlyWorldMatrix(e),tt.a.BindBonesParameters(n,this._activeEffect);var d=this._mustRebind(o,s,n.visibility);if(d){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s);var p=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(o.texturesEnabled&&(this._diffuseTexture&&ht.a.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),tt.a.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),p&&ht.a.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",p.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",p.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",p.getSize().width,p.lodGenerationScale,p.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),a.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),o.texturesEnabled&&(this._diffuseTexture&&ht.a.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),p&&ht.a.ReflectionTextureEnabled&&(a.REFLECTIONBLUR&&a.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",p):a.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",p._lodTextureMid||p),this._uniformBuffer.setTexture("reflectionSamplerLow",p._lodTextureLow||p),this._uniformBuffer.setTexture("reflectionSamplerHigh",p._lodTextureHigh||p)):this._uniformBuffer.setTexture("reflectionSampler",p),a.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)))),tt.a.BindClipPlane(this._activeEffect,o),tt.a.BindEyePosition(s,o)}!d&&this.isFrozen||(o.lightsEnabled&&tt.a.BindLights(o,n,this._activeEffect,a,this._maxSimultaneousLights,!1),this.bindView(s),tt.a.BindFogParameters(o,n,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(n,this._activeEffect)}}},t.prototype.hasTexture=function(e){return!!r.prototype.hasTexture.call(this,e)||this._reflectionTexture===e||this._diffuseTexture===e},t.prototype.dispose=function(e,n){e===void 0&&(e=!1),n===void 0&&(n=!1),n&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),r.prototype.dispose.call(this,e)},t.prototype.clone=function(e){var n=this;return L.a.Clone(function(){return new t(e,n.getScene())},this)},t.prototype.serialize=function(){var e=L.a.Serialize(this);return e.customType="BABYLON.BackgroundMaterial",e},t.prototype.getClassName=function(){return"BackgroundMaterial"},t.Parse=function(e,n,i){return L.a.Parse(function(){return new t(e.name,n)},e,n,i)},t.StandardReflectance0=.05,t.StandardReflectance90=.5,Object(c.c)([Object(L.e)()],t.prototype,"_primaryColor",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColor",void 0),Object(c.c)([Object(L.e)()],t.prototype,"__perceptualColor",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_primaryColorShadowLevel",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_primaryColorHighlightLevel",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColorHighlightLevel",null),Object(c.c)([Object(L.m)()],t.prototype,"_reflectionTexture",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_reflectionBlur",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionBlur",void 0),Object(c.c)([Object(L.m)()],t.prototype,"_diffuseTexture",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLights",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_shadowLevel",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLevel",void 0),Object(c.c)([Object(L.o)()],t.prototype,"_sceneCenter",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"sceneCenter",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_opacityFresnel",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"opacityFresnel",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_reflectionFresnel",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFresnel",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_reflectionFalloffDistance",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFalloffDistance",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_reflectionAmount",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionAmount",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_reflectionReflectance0",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance0",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_reflectionReflectance90",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance90",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_useRGBColor",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRGBColor",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_enableNoise",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableNoise",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_maxSimultaneousLights",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_shadowOnly",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"shadowOnly",void 0),Object(c.c)([Object(L.i)()],t.prototype,"_imageProcessingConfiguration",void 0),t}(na.a);R.a.RegisteredTypes["BABYLON.BackgroundMaterial"]=ao;var Us=function(){function r(t,e){var n=this;this._errorHandler=function(i,o){n.onErrorObservable.notifyObservers({message:i,exception:o})},this._options=Object(c.a)(Object(c.a)({},r._getDefaultOptions()),t),this._scene=e,this.onErrorObservable=new x.c,this._setupBackground(),this._setupImageProcessing()}return r._getDefaultOptions=function(){return{createGround:!0,groundSize:15,groundTexture:this._groundTextureCDNUrl,groundColor:new M.a(.2,.2,.3).toLinearSpace().scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:h.a.TEXTURETYPE_UNSIGNED_INT,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._skyboxTextureCDNUrl,skyboxColor:new M.a(.2,.2,.3).toLinearSpace().scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:u.e.Zero(),setupImageProcessing:!0,environmentTexture:this._environmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}},Object.defineProperty(r.prototype,"rootMesh",{get:function(){return this._rootMesh},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"skybox",{get:function(){return this._skybox},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"skyboxTexture",{get:function(){return this._skyboxTexture},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"skyboxMaterial",{get:function(){return this._skyboxMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"ground",{get:function(){return this._ground},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"groundTexture",{get:function(){return this._groundTexture},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"groundMirror",{get:function(){return this._groundMirror},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"groundMirrorRenderList",{get:function(){return this._groundMirror?this._groundMirror.renderList:null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"groundMaterial",{get:function(){return this._groundMaterial},enumerable:!1,configurable:!0}),r.prototype.updateOptions=function(t){var e=Object(c.a)(Object(c.a)({},this._options),t);this._ground&&!e.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!e.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=e.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!e.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!e.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=e.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!e.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=e.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=e,this._setupBackground(),this._setupImageProcessing()},r.prototype.setMainColor=function(t){this.groundMaterial&&(this.groundMaterial.primaryColor=t),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=t),this.groundMirror&&(this.groundMirror.clearColor=new M.b(t.r,t.g,t.b,1))},r.prototype._setupImageProcessing=function(){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())},r.prototype._setupEnvironmentTexture=function(){if(!this._scene.environmentTexture)if(this._options.environmentTexture instanceof zn.a)this._scene.environmentTexture=this._options.environmentTexture;else{var t=ni.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=t}},r.prototype._setupBackground=function(){this._rootMesh||(this._rootMesh=new De.a("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;var t=this._getSceneSize();this._options.createGround&&(this._setupGround(t),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(t),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(t),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=t.rootPosition.x,this._rootMesh.position.z=t.rootPosition.z,this._rootMesh.position.y=t.rootPosition.y},r.prototype._getSceneSize=function(){var t=this,e=this._options.groundSize,n=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||this._scene.meshes.length===1)return{groundSize:e,skyboxSize:n,rootPosition:i};var o=this._scene.getWorldExtends(function(d){return d!==t._ground&&d!==t._rootMesh&&d!==t._skybox}),a=o.max.subtract(o.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Zi&&this._scene.activeCamera.upperRadiusLimit&&(n=e=2*this._scene.activeCamera.upperRadiusLimit);var s=a.length();s>e&&(n=e=2*s),e*=1.1,n*=1.5,(i=o.min.add(a.scale(.5))).y=o.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:n,rootPosition:i}},r.prototype._setupGround=function(t){var e=this;this._ground&&!this._ground.isDisposed()||(this._ground=De.a.CreatePlane("BackgroundPlane",t.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(function(){e._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow},r.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new ao("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=h.a.ALPHA_PREMULTIPLIED_PORTERDUFF,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)},r.prototype._setupGroundDiffuseTexture=function(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof zn.a?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new we.a(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)))},r.prototype._setupGroundMirrorTexture=function(t){var e=we.a.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Bs("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,we.a.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new gr.a(0,-1,0,t.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=e,this._groundMirror.wrapV=e,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var n=0;n0&&t.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&t.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&t.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&t.push(this._tintTexture)},r.prototype.dispose=function(t){var e,n,i,o;t&&((e=this._texture)===null||e===void 0||e.dispose(),(n=this._textureRoughness)===null||n===void 0||n.dispose(),(i=this._bumpTexture)===null||i===void 0||i.dispose(),(o=this._tintTexture)===null||o===void 0||o.dispose())},r.prototype.getClassName=function(){return"PBRClearCoatConfiguration"},r.AddFallbacks=function(t,e,n){return t.CLEARCOAT_BUMP&&e.addFallback(n++,"CLEARCOAT_BUMP"),t.CLEARCOAT_TINT&&e.addFallback(n++,"CLEARCOAT_TINT"),t.CLEARCOAT&&e.addFallback(n++,"CLEARCOAT"),n},r.AddUniforms=function(t){t.push("vClearCoatTangentSpaceParams","vClearCoatParams","vClearCoatRefractionParams","vClearCoatTintParams","clearCoatColorAtDistance","clearCoatMatrix","clearCoatRoughnessMatrix","clearCoatBumpMatrix","clearCoatTintMatrix","vClearCoatInfos","vClearCoatBumpInfos","vClearCoatTintInfos")},r.AddSamplers=function(t){t.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")},r.PrepareUniformBuffer=function(t){t.addUniform("vClearCoatParams",2),t.addUniform("vClearCoatRefractionParams",4),t.addUniform("vClearCoatInfos",4),t.addUniform("clearCoatMatrix",16),t.addUniform("clearCoatRoughnessMatrix",16),t.addUniform("vClearCoatBumpInfos",2),t.addUniform("vClearCoatTangentSpaceParams",2),t.addUniform("clearCoatBumpMatrix",16),t.addUniform("vClearCoatTintParams",4),t.addUniform("clearCoatColorAtDistance",1),t.addUniform("vClearCoatTintInfos",2),t.addUniform("clearCoatTintMatrix",16)},r.prototype.copyTo=function(t){L.a.Clone(function(){return t},this)},r.prototype.serialize=function(){return L.a.Serialize(this)},r.prototype.parse=function(t,e,n){var i=this;L.a.Parse(function(){return i},t,e,n)},r._DefaultIndexOfRefraction=1.5,Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"isEnabled",void 0),Object(c.c)([Object(L.c)()],r.prototype,"intensity",void 0),Object(c.c)([Object(L.c)()],r.prototype,"roughness",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"indexOfRefraction",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"texture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useRoughnessFromMainTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"textureRoughness",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"remapF0OnInterfaceChange",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"bumpTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"isTintEnabled",void 0),Object(c.c)([Object(L.e)()],r.prototype,"tintColor",void 0),Object(c.c)([Object(L.c)()],r.prototype,"tintColorAtDistance",void 0),Object(c.c)([Object(L.c)()],r.prototype,"tintThickness",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"tintTexture",void 0),r}(),Ar=function(){function r(t){this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new u.d(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=t}return r.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},r.prototype.isReadyForSubMesh=function(t,e){return!(t._areTexturesDirty&&e.texturesEnabled&&this._texture&&ht.a.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())},r.prototype.prepareDefines=function(t,e,n){this._isEnabled?(t.ANISOTROPIC=this._isEnabled,this._isEnabled&&!e.isVerticesDataPresent(Me.b.TangentKind)&&(t._needUVs=!0,t.MAINUV1=!0),t._areTexturesDirty&&n.texturesEnabled&&(this._texture&&ht.a.AnisotropicTextureEnabled?tt.a.PrepareDefinesForMergedUV(this._texture,t,"ANISOTROPIC_TEXTURE"):t.ANISOTROPIC_TEXTURE=!1)):(t.ANISOTROPIC=!1,t.ANISOTROPIC_TEXTURE=!1)},r.prototype.bindForSubMesh=function(t,e,n){t.useUbo&&n&&t.isSync||(this._texture&&ht.a.AnisotropicTextureEnabled&&(t.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),tt.a.BindTextureMatrix(this._texture,t,"anisotropy")),t.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),e.texturesEnabled&&this._texture&&ht.a.AnisotropicTextureEnabled&&t.setTexture("anisotropySampler",this._texture)},r.prototype.hasTexture=function(t){return this._texture===t},r.prototype.getActiveTextures=function(t){this._texture&&t.push(this._texture)},r.prototype.getAnimatables=function(t){this._texture&&this._texture.animations&&this._texture.animations.length>0&&t.push(this._texture)},r.prototype.dispose=function(t){t&&this._texture&&this._texture.dispose()},r.prototype.getClassName=function(){return"PBRAnisotropicConfiguration"},r.AddFallbacks=function(t,e,n){return t.ANISOTROPIC&&e.addFallback(n++,"ANISOTROPIC"),n},r.AddUniforms=function(t){t.push("vAnisotropy","vAnisotropyInfos","anisotropyMatrix")},r.PrepareUniformBuffer=function(t){t.addUniform("vAnisotropy",3),t.addUniform("vAnisotropyInfos",2),t.addUniform("anisotropyMatrix",16)},r.AddSamplers=function(t){t.push("anisotropySampler")},r.prototype.copyTo=function(t){L.a.Clone(function(){return t},this)},r.prototype.serialize=function(){return L.a.Serialize(this)},r.prototype.parse=function(t,e,n){var i=this;L.a.Parse(function(){return i},t,e,n)},Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"isEnabled",void 0),Object(c.c)([Object(L.c)()],r.prototype,"intensity",void 0),Object(c.c)([Object(L.n)()],r.prototype,"direction",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"texture",void 0),r}(),qp=function(){function r(t){this._useEnergyConservation=r.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=r.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=r.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=r.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=r.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=r.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=r.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=r.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=t}return r.prototype._markAllSubMeshesAsMiscDirty=function(){this._internalMarkAllSubMeshesAsMiscDirty()},r.prototype.prepareDefines=function(t){t.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,t.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,t.SPHERICAL_HARMONICS=this._useSphericalHarmonics,t.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation},r.prototype.getClassName=function(){return"PBRBRDFConfiguration"},r.prototype.copyTo=function(t){L.a.Clone(function(){return t},this)},r.prototype.serialize=function(){return L.a.Serialize(this)},r.prototype.parse=function(t,e,n){var i=this;L.a.Parse(function(){return i},t,e,n)},r.DEFAULT_USE_ENERGY_CONSERVATION=!0,r.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,r.DEFAULT_USE_SPHERICAL_HARMONICS=!0,r.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsMiscDirty")],r.prototype,"useEnergyConservation",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsMiscDirty")],r.prototype,"useSmithVisibilityHeightCorrelated",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsMiscDirty")],r.prototype,"useSphericalHarmonics",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsMiscDirty")],r.prototype,"useSpecularGlossinessInputEnergyConservation",void 0),r}(),so=function(){function r(t){this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=M.a.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=t}return r.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},r.prototype.isReadyForSubMesh=function(t,e){return!(t._areTexturesDirty&&e.texturesEnabled&&(this._texture&&ht.a.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&ht.a.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()))},r.prototype.prepareDefines=function(t,e){var n;this._isEnabled?(t.SHEEN=this._isEnabled,t.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,t.SHEEN_ROUGHNESS=this._roughness!==null,t.SHEEN_ALBEDOSCALING=this._albedoScaling,t.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,t.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((n=this._textureRoughness)===null||n===void 0?void 0:n._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),t._areTexturesDirty&&e.texturesEnabled&&(this._texture&&ht.a.SheenTextureEnabled?tt.a.PrepareDefinesForMergedUV(this._texture,t,"SHEEN_TEXTURE"):t.SHEEN_TEXTURE=!1,this._textureRoughness&&ht.a.SheenTextureEnabled?tt.a.PrepareDefinesForMergedUV(this._textureRoughness,t,"SHEEN_TEXTURE_ROUGHNESS"):t.SHEEN_TEXTURE_ROUGHNESS=!1)):(t.SHEEN=!1,t.SHEEN_TEXTURE=!1,t.SHEEN_TEXTURE_ROUGHNESS=!1,t.SHEEN_LINKWITHALBEDO=!1,t.SHEEN_ROUGHNESS=!1,t.SHEEN_ALBEDOSCALING=!1,t.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,t.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1)},r.prototype.bindForSubMesh=function(t,e,n,i){var o,a,s,d,p,y,P,O,U=i._materialDefines,F=U.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;t.useUbo&&n&&t.isSync||(F&&ht.a.SheenTextureEnabled?(t.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),tt.a.BindTextureMatrix(this._texture,t,"sheen")):(this._texture||this._textureRoughness)&&ht.a.SheenTextureEnabled&&(t.updateFloat4("vSheenInfos",(a=(o=this._texture)===null||o===void 0?void 0:o.coordinatesIndex)!==null&&a!==void 0?a:0,(d=(s=this._texture)===null||s===void 0?void 0:s.level)!==null&&d!==void 0?d:0,(y=(p=this._textureRoughness)===null||p===void 0?void 0:p.coordinatesIndex)!==null&&y!==void 0?y:0,(O=(P=this._textureRoughness)===null||P===void 0?void 0:P.level)!==null&&O!==void 0?O:0),this._texture&&tt.a.BindTextureMatrix(this._texture,t,"sheen"),!this._textureRoughness||F||U.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||tt.a.BindTextureMatrix(this._textureRoughness,t,"sheenRoughness")),t.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&t.updateFloat("vSheenRoughness",this._roughness)),e.texturesEnabled&&(this._texture&&ht.a.SheenTextureEnabled&&t.setTexture("sheenSampler",this._texture),this._textureRoughness&&!F&&!U.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ht.a.SheenTextureEnabled&&t.setTexture("sheenRoughnessSampler",this._textureRoughness))},r.prototype.hasTexture=function(t){return this._texture===t||this._textureRoughness===t},r.prototype.getActiveTextures=function(t){this._texture&&t.push(this._texture),this._textureRoughness&&t.push(this._textureRoughness)},r.prototype.getAnimatables=function(t){this._texture&&this._texture.animations&&this._texture.animations.length>0&&t.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&t.push(this._textureRoughness)},r.prototype.dispose=function(t){var e,n;t&&((e=this._texture)===null||e===void 0||e.dispose(),(n=this._textureRoughness)===null||n===void 0||n.dispose())},r.prototype.getClassName=function(){return"PBRSheenConfiguration"},r.AddFallbacks=function(t,e,n){return t.SHEEN&&e.addFallback(n++,"SHEEN"),n},r.AddUniforms=function(t){t.push("vSheenColor","vSheenRoughness","vSheenInfos","sheenMatrix","sheenRoughnessMatrix")},r.PrepareUniformBuffer=function(t){t.addUniform("vSheenColor",4),t.addUniform("vSheenRoughness",1),t.addUniform("vSheenInfos",4),t.addUniform("sheenMatrix",16),t.addUniform("sheenRoughnessMatrix",16)},r.AddSamplers=function(t){t.push("sheenSampler"),t.push("sheenRoughnessSampler")},r.prototype.copyTo=function(t){L.a.Clone(function(){return t},this)},r.prototype.serialize=function(){return L.a.Serialize(this)},r.prototype.parse=function(t,e,n){var i=this;L.a.Parse(function(){return i},t,e,n)},Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"isEnabled",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"linkSheenWithAlbedo",void 0),Object(c.c)([Object(L.c)()],r.prototype,"intensity",void 0),Object(c.c)([Object(L.e)()],r.prototype,"color",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"texture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useRoughnessFromMainTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"roughness",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"textureRoughness",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"albedoScaling",void 0),r}(),co=function(){function r(t,e,n){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._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.tintColor=M.a.White(),this.tintColorAtDistance=1,this.diffusionDistance=M.a.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._useMaskFromThicknessTextureGltf=!1,this.useMaskFromThicknessTextureGltf=!1,this._internalMarkAllSubMeshesAsTexturesDirty=t,this._internalMarkScenePrePassDirty=e,this._scene=n}return Object.defineProperty(r.prototype,"scatteringDiffusionProfile",{get:function(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null},set:function(t){this._scene.enableSubSurfaceForPrePass()&&t&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(t))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volumeIndexOfRefraction",{get:function(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction},set:function(t){this._volumeIndexOfRefraction=t>=1?t:-1},enumerable:!1,configurable:!0}),r.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},r.prototype._markScenePrePassDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()},r.prototype.isReadyForSubMesh=function(t,e){if(t._areTexturesDirty&&e.texturesEnabled){if(this._thicknessTexture&&ht.a.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;var n=this._getRefractionTexture(e);if(n&&ht.a.RefractionTextureEnabled&&!n.isReadyOrNotBlocking())return!1}return!0},r.prototype.prepareDefines=function(t,e){if(t._areTexturesDirty&&(t.SUBSURFACE=!1,t.SS_TRANSLUCENCY=this._isTranslucencyEnabled,t.SS_SCATTERING=this._isScatteringEnabled,t.SS_THICKNESSANDMASK_TEXTURE=!1,t.SS_MASK_FROM_THICKNESS_TEXTURE=!1,t.SS_MASK_FROM_THICKNESS_TEXTURE_GLTF=!1,t.SS_REFRACTION=!1,t.SS_REFRACTIONMAP_3D=!1,t.SS_GAMMAREFRACTION=!1,t.SS_RGBDREFRACTION=!1,t.SS_LINEARSPECULARREFRACTION=!1,t.SS_REFRACTIONMAP_OPPOSITEZ=!1,t.SS_LODINREFRACTIONALPHA=!1,t.SS_LINKREFRACTIONTOTRANSPARENCY=!1,t.SS_ALBEDOFORREFRACTIONTINT=!1,(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)&&(t.SUBSURFACE=!0,t._areTexturesDirty&&e.texturesEnabled&&this._thicknessTexture&&ht.a.ThicknessTextureEnabled&&tt.a.PrepareDefinesForMergedUV(this._thicknessTexture,t,"SS_THICKNESSANDMASK_TEXTURE"),t.SS_MASK_FROM_THICKNESS_TEXTURE=this._useMaskFromThicknessTexture,t.SS_MASK_FROM_THICKNESS_TEXTURE_GLTF=this._useMaskFromThicknessTextureGltf),this._isRefractionEnabled&&e.texturesEnabled)){var n=this._getRefractionTexture(e);n&&ht.a.RefractionTextureEnabled&&(t.SS_REFRACTION=!0,t.SS_REFRACTIONMAP_3D=n.isCube,t.SS_GAMMAREFRACTION=n.gammaSpace,t.SS_RGBDREFRACTION=n.isRGBD,t.SS_LINEARSPECULARREFRACTION=n.linearSpecularLOD,t.SS_REFRACTIONMAP_OPPOSITEZ=n.invertZ,t.SS_LODINREFRACTIONALPHA=n.lodLevelInAlpha,t.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,t.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction)}},r.prototype.bindForSubMesh=function(t,e,n,i,o,a){var s=this._getRefractionTexture(e);if(!t.useUbo||!i||!t.isSync){if(this._thicknessTexture&&ht.a.ThicknessTextureEnabled&&(t.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),tt.a.BindTextureMatrix(this._thicknessTexture,t,"thickness")),t.updateFloat2("vThicknessParam",this.minimumThickness,this.maximumThickness-this.minimumThickness),s&&ht.a.RefractionTextureEnabled){t.updateMatrix("refractionMatrix",s.getReflectionTextureMatrix());var d=1;s.isCube||s.depth&&(d=s.depth);var p=s.getSize().width,y=this.volumeIndexOfRefraction;t.updateFloat4("vRefractionInfos",s.level,1/y,d,this._invertRefractionY?-1:1),t.updateFloat3("vRefractionMicrosurfaceInfos",p,s.lodGenerationScale,s.lodGenerationOffset),a&&t.updateFloat2("vRefractionFilteringInfo",p,$.a.Log2(p))}this.isScatteringEnabled&&t.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),t.updateColor3("vDiffusionDistance",this.diffusionDistance),t.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,this.tintColorAtDistance),t.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}e.texturesEnabled&&(this._thicknessTexture&&ht.a.ThicknessTextureEnabled&&t.setTexture("thicknessSampler",this._thicknessTexture),s&&ht.a.RefractionTextureEnabled&&(o?t.setTexture("refractionSampler",s):(t.setTexture("refractionSampler",s._lodTextureMid||s),t.setTexture("refractionSamplerLow",s._lodTextureLow||s),t.setTexture("refractionSamplerHigh",s._lodTextureHigh||s))))},r.prototype.unbind=function(t){return!(!this._refractionTexture||!this._refractionTexture.isRenderTarget)&&(t.setTexture("refractionSampler",null),!0)},r.prototype._getRefractionTexture=function(t){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?t.environmentTexture:null},Object.defineProperty(r.prototype,"disableAlphaBlending",{get:function(){return this.isRefractionEnabled&&this._linkRefractionWithTransparency},enumerable:!1,configurable:!0}),r.prototype.fillRenderTargetTextures=function(t){ht.a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&t.push(this._refractionTexture)},r.prototype.hasTexture=function(t){return this._thicknessTexture===t||this._refractionTexture===t},r.prototype.hasRenderTargetTextures=function(){return!!(ht.a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},r.prototype.getActiveTextures=function(t){this._thicknessTexture&&t.push(this._thicknessTexture),this._refractionTexture&&t.push(this._refractionTexture)},r.prototype.getAnimatables=function(t){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&t.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&t.push(this._refractionTexture)},r.prototype.dispose=function(t){t&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())},r.prototype.getClassName=function(){return"PBRSubSurfaceConfiguration"},r.AddFallbacks=function(t,e,n){return t.SS_SCATTERING&&e.addFallback(n++,"SS_SCATTERING"),t.SS_TRANSLUCENCY&&e.addFallback(n++,"SS_TRANSLUCENCY"),n},r.AddUniforms=function(t){t.push("vDiffusionDistance","vTintColor","vSubSurfaceIntensity","vRefractionMicrosurfaceInfos","vRefractionFilteringInfo","vRefractionInfos","vThicknessInfos","vThicknessParam","refractionMatrix","thicknessMatrix","scatteringDiffusionProfile")},r.AddSamplers=function(t){t.push("thicknessSampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")},r.PrepareUniformBuffer=function(t){t.addUniform("vRefractionMicrosurfaceInfos",3),t.addUniform("vRefractionFilteringInfo",2),t.addUniform("vRefractionInfos",4),t.addUniform("refractionMatrix",16),t.addUniform("vThicknessInfos",2),t.addUniform("thicknessMatrix",16),t.addUniform("vThicknessParam",2),t.addUniform("vDiffusionDistance",3),t.addUniform("vTintColor",4),t.addUniform("vSubSurfaceIntensity",3),t.addUniform("scatteringDiffusionProfile",1)},r.prototype.copyTo=function(t){L.a.Clone(function(){return t},this)},r.prototype.serialize=function(){return L.a.Serialize(this)},r.prototype.parse=function(t,e,n){var i=this;L.a.Parse(function(){return i},t,e,n)},Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"isRefractionEnabled",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"isTranslucencyEnabled",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markScenePrePassDirty")],r.prototype,"isScatteringEnabled",void 0),Object(c.c)([Object(L.c)()],r.prototype,"_scatteringDiffusionProfileIndex",void 0),Object(c.c)([Object(L.c)()],r.prototype,"refractionIntensity",void 0),Object(c.c)([Object(L.c)()],r.prototype,"translucencyIntensity",void 0),Object(c.c)([Object(L.c)()],r.prototype,"useAlbedoToTintRefraction",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"thicknessTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"refractionTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"indexOfRefraction",void 0),Object(c.c)([Object(L.c)()],r.prototype,"_volumeIndexOfRefraction",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"volumeIndexOfRefraction",null),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"invertRefractionY",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"linkRefractionWithTransparency",void 0),Object(c.c)([Object(L.c)()],r.prototype,"minimumThickness",void 0),Object(c.c)([Object(L.c)()],r.prototype,"maximumThickness",void 0),Object(c.c)([Object(L.e)()],r.prototype,"tintColor",void 0),Object(c.c)([Object(L.c)()],r.prototype,"tintColorAtDistance",void 0),Object(c.c)([Object(L.e)()],r.prototype,"diffusionDistance",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useMaskFromThicknessTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],r.prototype,"useMaskFromThicknessTextureGltf",void 0),r}(),Vs=f(105),Ht=f(25),Zp=(f(160),`uniform vec3 vReflectionColor; -uniform vec4 vAlbedoColor; - -uniform vec4 vLightingIntensity; -uniform vec4 vReflectivityColor; -uniform vec4 vMetallicReflectanceFactors; -uniform vec3 vEmissiveColor; -uniform float visibility; - -#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) -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 - -#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 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 vec3 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 -uniform vec2 vThicknessParam; -uniform vec3 vDiffusionDistance; -uniform vec4 vTintColor; -uniform vec3 vSubSurfaceIntensity; -#endif -#ifdef PREPASS -#ifdef PREPASS_IRRADIANCE -uniform float scatteringDiffusionProfile; -#endif -#endif`);je.a.IncludesShadersStore.pbrFragmentDeclaration=Zp;var Jp=`layout(std140,column_major) uniform; -uniform Material -{ -uniform vec2 vAlbedoInfos; -uniform vec4 vAmbientInfos; -uniform vec2 vOpacityInfos; -uniform vec2 vEmissiveInfos; -uniform vec2 vLightmapInfos; -uniform vec3 vReflectivityInfos; -uniform vec2 vMicroSurfaceSamplerInfos; -uniform vec2 vReflectionInfos; -uniform vec2 vReflectionFilteringInfo; -uniform vec3 vReflectionPosition; -uniform vec3 vReflectionSize; -uniform vec3 vBumpInfos; -uniform mat4 albedoMatrix; -uniform mat4 ambientMatrix; -uniform mat4 opacityMatrix; -uniform mat4 emissiveMatrix; -uniform mat4 lightmapMatrix; -uniform mat4 reflectivityMatrix; -uniform mat4 microSurfaceSamplerMatrix; -uniform mat4 bumpMatrix; -uniform vec2 vTangentSpaceParams; -uniform mat4 reflectionMatrix; -uniform vec3 vReflectionColor; -uniform vec4 vAlbedoColor; -uniform vec4 vLightingIntensity; -uniform vec3 vReflectionMicrosurfaceInfos; -uniform float pointSize; -uniform vec4 vReflectivityColor; -uniform vec3 vEmissiveColor; -uniform float visibility; -uniform vec4 vMetallicReflectanceFactors; -uniform vec2 vMetallicReflectanceInfos; -uniform mat4 metallicReflectanceMatrix; -uniform vec2 vClearCoatParams; -uniform vec4 vClearCoatRefractionParams; -uniform vec4 vClearCoatInfos; -uniform mat4 clearCoatMatrix; -uniform mat4 clearCoatRoughnessMatrix; -uniform vec2 vClearCoatBumpInfos; -uniform vec2 vClearCoatTangentSpaceParams; -uniform mat4 clearCoatBumpMatrix; -uniform vec4 vClearCoatTintParams; -uniform float clearCoatColorAtDistance; -uniform vec2 vClearCoatTintInfos; -uniform mat4 clearCoatTintMatrix; -uniform vec3 vAnisotropy; -uniform vec2 vAnisotropyInfos; -uniform mat4 anisotropyMatrix; -uniform vec4 vSheenColor; -uniform float vSheenRoughness; -uniform vec4 vSheenInfos; -uniform mat4 sheenMatrix; -uniform mat4 sheenRoughnessMatrix; -uniform vec3 vRefractionMicrosurfaceInfos; -uniform vec2 vRefractionFilteringInfo; -uniform vec4 vRefractionInfos; -uniform mat4 refractionMatrix; -uniform vec2 vThicknessInfos; -uniform mat4 thicknessMatrix; -uniform vec2 vThicknessParam; -uniform vec3 vDiffusionDistance; -uniform vec4 vTintColor; -uniform vec3 vSubSurfaceIntensity; -uniform float scatteringDiffusionProfile; -uniform vec4 vDetailInfos; -uniform mat4 detailMatrix; -}; -uniform Scene { -mat4 viewProjection; -#ifdef MULTIVIEW -mat4 viewProjectionR; -#endif -mat4 view; -};`;je.a.IncludesShadersStore.pbrUboDeclaration=Jp;var $p=`uniform vec4 vEyePosition; -uniform vec3 vAmbientColor; -uniform vec4 vCameraInfos; - -varying vec3 vPositionW; -#if DEBUGMODE>0 -uniform vec2 vDebugMode; -varying vec4 vClipSpacePosition; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#endif -#endif -#ifdef VERTEXCOLOR -varying vec4 vColor; -#endif`;je.a.IncludesShadersStore.pbrFragmentExtraDeclaration=$p;var e_=`#ifdef ALBEDO -#if ALBEDODIRECTUV == 1 -#define vAlbedoUV vMainUV1 -#elif ALBEDODIRECTUV == 2 -#define vAlbedoUV vMainUV2 -#else -varying vec2 vAlbedoUV; -#endif -uniform sampler2D albedoSampler; -#endif -#ifdef AMBIENT -#if AMBIENTDIRECTUV == 1 -#define vAmbientUV vMainUV1 -#elif AMBIENTDIRECTUV == 2 -#define vAmbientUV vMainUV2 -#else -varying vec2 vAmbientUV; -#endif -uniform sampler2D ambientSampler; -#endif -#ifdef OPACITY -#if OPACITYDIRECTUV == 1 -#define vOpacityUV vMainUV1 -#elif OPACITYDIRECTUV == 2 -#define vOpacityUV vMainUV2 -#else -varying vec2 vOpacityUV; -#endif -uniform sampler2D opacitySampler; -#endif -#ifdef EMISSIVE -#if EMISSIVEDIRECTUV == 1 -#define vEmissiveUV vMainUV1 -#elif EMISSIVEDIRECTUV == 2 -#define vEmissiveUV vMainUV2 -#else -varying vec2 vEmissiveUV; -#endif -uniform sampler2D emissiveSampler; -#endif -#ifdef LIGHTMAP -#if LIGHTMAPDIRECTUV == 1 -#define vLightmapUV vMainUV1 -#elif LIGHTMAPDIRECTUV == 2 -#define vLightmapUV vMainUV2 -#else -varying vec2 vLightmapUV; -#endif -uniform sampler2D lightmapSampler; -#endif -#ifdef REFLECTIVITY -#if REFLECTIVITYDIRECTUV == 1 -#define vReflectivityUV vMainUV1 -#elif REFLECTIVITYDIRECTUV == 2 -#define vReflectivityUV vMainUV2 -#else -varying vec2 vReflectivityUV; -#endif -uniform sampler2D reflectivitySampler; -#endif -#ifdef MICROSURFACEMAP -#if MICROSURFACEMAPDIRECTUV == 1 -#define vMicroSurfaceSamplerUV vMainUV1 -#elif MICROSURFACEMAPDIRECTUV == 2 -#define vMicroSurfaceSamplerUV vMainUV2 -#else -varying vec2 vMicroSurfaceSamplerUV; -#endif -uniform sampler2D microSurfaceSampler; -#endif -#ifdef METALLIC_REFLECTANCE -#if METALLIC_REFLECTANCEDIRECTUV == 1 -#define vMetallicReflectanceUV vMainUV1 -#elif METALLIC_REFLECTANCEDIRECTUV == 2 -#define vMetallicReflectanceUV vMainUV2 -#else -varying vec2 vMetallicReflectanceUV; -#endif -uniform sampler2D metallicReflectanceSampler; -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) -#if CLEARCOAT_TEXTUREDIRECTUV == 1 -#define vClearCoatUV vMainUV1 -#elif CLEARCOAT_TEXTUREDIRECTUV == 2 -#define vClearCoatUV vMainUV2 -#else -varying vec2 vClearCoatUV; -#endif -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) -#if CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV == 1 -#define vClearCoatRoughnessUV vMainUV1 -#elif CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV == 2 -#define vClearCoatRoughnessUV vMainUV2 -#else -varying vec2 vClearCoatRoughnessUV; -#endif -#endif -#ifdef CLEARCOAT_TEXTURE -uniform sampler2D clearCoatSampler; -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D clearCoatRoughnessSampler; -#endif -#ifdef CLEARCOAT_BUMP -#if CLEARCOAT_BUMPDIRECTUV == 1 -#define vClearCoatBumpUV vMainUV1 -#elif CLEARCOAT_BUMPDIRECTUV == 2 -#define vClearCoatBumpUV vMainUV2 -#else -varying vec2 vClearCoatBumpUV; -#endif -uniform sampler2D clearCoatBumpSampler; -#endif -#ifdef CLEARCOAT_TINT_TEXTURE -#if CLEARCOAT_TINT_TEXTUREDIRECTUV == 1 -#define vClearCoatTintUV vMainUV1 -#elif CLEARCOAT_TINT_TEXTUREDIRECTUV == 2 -#define vClearCoatTintUV vMainUV2 -#else -varying vec2 vClearCoatTintUV; -#endif -uniform sampler2D clearCoatTintSampler; -#endif -#endif -#ifdef SHEEN -#ifdef SHEEN_TEXTURE -#if SHEEN_TEXTUREDIRECTUV == 1 -#define vSheenUV vMainUV1 -#elif SHEEN_TEXTUREDIRECTUV == 2 -#define vSheenUV vMainUV2 -#else -varying vec2 vSheenUV; -#endif -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -#if SHEEN_TEXTURE_ROUGHNESSDIRECTUV == 1 -#define vSheenRoughnessUV vMainUV1 -#elif SHEEN_TEXTURE_ROUGHNESSDIRECTUV == 2 -#define vSheenRoughnessUV vMainUV2 -#else -varying vec2 vSheenRoughnessUV; -#endif -#endif -#ifdef SHEEN_TEXTURE -uniform sampler2D sheenSampler; -#endif -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D sheenRoughnessSampler; -#endif -#endif -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_TEXTURE -#if ANISOTROPIC_TEXTUREDIRECTUV == 1 -#define vAnisotropyUV vMainUV1 -#elif ANISOTROPIC_TEXTUREDIRECTUV == 2 -#define vAnisotropyUV vMainUV2 -#else -varying vec2 vAnisotropyUV; -#endif -uniform sampler2D anisotropySampler; -#endif -#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 -#ifdef SS_THICKNESSANDMASK_TEXTURE -#if SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 1 -#define vThicknessUV vMainUV1 -#elif SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 2 -#define vThicknessUV vMainUV2 -#else -varying vec2 vThicknessUV; -#endif -uniform sampler2D thicknessSampler; -#endif -#endif`;je.a.IncludesShadersStore.pbrFragmentSamplersDeclaration=e_,f(116),je.a.IncludesShadersStore.subSurfaceScatteringFunctions=`bool testLightingForSSS(float diffusionProfile) -{ -return diffusionProfile<1.; -}`;var t_=` - - - - - - - - - - - - - - - - - - - - - - - - - - - - -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); -}`;je.a.IncludesShadersStore.importanceSampling=t_;var n_=` -#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 - - -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) { -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; - -} -#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`;je.a.IncludesShadersStore.pbrHelperFunctions=n_;var i_=`#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; - - - - - - - -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 -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; - -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`;je.a.IncludesShadersStore.harmonicsFunctions=i_;var r_=` -struct preLightingInfo -{ - -vec3 lightOffset; -float lightDistanceSquared; -float lightDistance; - -float attenuation; - -vec3 L; -vec3 H; -float NdotV; -float NdotLUnclamped; -float NdotL; -float VdotH; -float roughness; -}; -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; -}`;je.a.IncludesShadersStore.pbrDirectLightingSetupFunctions=r_;var o_=`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 -}`;je.a.IncludesShadersStore.pbrDirectLightingFalloffFunctions=o_;var a_=` -#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 - -#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) - -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 t*t; -#endif -} -#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)); -} - -#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 -`;je.a.IncludesShadersStore.pbrBRDFFunctions=a_;var s_=`#ifdef NUM_SAMPLES -#if NUM_SAMPLES>0 -#ifdef WEBGL2 - - -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); -#ifdef WEBGL2 -for(uint i=0u; i0.) { -float pdf_inversed=PI/NoL; -float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed; -float l=log4(omegaS)-log4(omegaP)+log4(K); -float mipLevel=clamp(l,0.0,maxLevel); -vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c; -} -} -result=result*NUM_SAMPLES_FLOAT_INVERSED; -return result; -} -#define inline -vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{ -vec3 n=normalize(inputN); -if (alphaG == 0.) { -vec3 c=textureCube(inputTexture,n).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -return c; -} -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.; -#ifdef WEBGL2 -for(uint i=0u; i0.) { -float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG); -float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed; -float l=log4(omegaS)-log4(omegaP)+log4(K); -float mipLevel=clamp(float(l),0.0,maxLevel); -weight+=NoL; -vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c*NoL; -} -} -result=result/weight; -return result; -} -#endif -#endif`;je.a.IncludesShadersStore.hdrFilteringFunctions=s_;var c_=`#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); -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); -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); - -float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV); - -float sheenTerm=fresnel*distribution*visibility; -return sheenTerm*info.attenuation*info.NdotL*lightColor; -} -#endif -`;je.a.IncludesShadersStore.pbrDirectLightingFunctions=c_;var l_=`#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`;je.a.IncludesShadersStore.pbrIBLFunctions=l_,f(132),f(133);var u_=`struct albedoOpacityOutParams -{ -vec3 surfaceAlbedo; -float alpha; -}; -#define pbr_inline -void albedoOpacityBlock( -const in vec4 vAlbedoColor, -#ifdef ALBEDO -const in vec4 albedoTexture, -const in vec2 albedoInfos, -#endif -#ifdef OPACITY -const in vec4 opacityMap, -const in vec2 vOpacityInfos, -#endif -#ifdef DETAIL -const in vec4 detailColor, -const in vec4 vDetailInfos, -#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 -#ifdef VERTEXCOLOR -surfaceAlbedo*=vColor.rgb; -#endif -#ifdef DETAIL -float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y); -surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALBEDO - -#ifdef OPACITY -#ifdef OPACITYRGB -alpha=getLuminance(opacityMap.rgb); -#else -alpha*=opacityMap.a; -#endif -alpha*=vOpacityInfos.y; -#endif -#ifdef VERTEXALPHA -alpha*=vColor.a; -#endif -#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) -#ifdef ALPHATEST -if (alpha0 -vec4 surfaceMetallicColorMap; -vec4 surfaceReflectivityColorMap; -vec2 metallicRoughness; -vec3 metallicF0; -#endif -}; -#define pbr_inline -void reflectivityBlock( -const in vec4 vReflectivityColor, -#ifdef METALLICWORKFLOW -const in vec3 surfaceAlbedo, -const in vec4 metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -const in vec3 reflectivityInfos, -const in vec4 surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -const in vec3 ambientOcclusionColorIn, -#endif -#ifdef MICROSURFACEMAP -const in vec4 microSurfaceTexel, -#endif -#ifdef DETAIL -const in vec4 detailColor, -const 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; -} -`;je.a.IncludesShadersStore.pbrBlockReflectivity=h_;var d_=`struct ambientOcclusionOutParams -{ -vec3 ambientOcclusionColor; -#if DEBUGMODE>0 -vec3 ambientOcclusionColorMap; -#endif -}; -#define pbr_inline -void ambientOcclusionBlock( -#ifdef AMBIENT -const in vec3 ambientOcclusionColorMap_, -const 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; -} -`;je.a.IncludesShadersStore.pbrBlockAmbientOcclusion=d_;var f_=`#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -struct alphaFresnelOutParams -{ -float alpha; -}; -#define pbr_inline -void alphaFresnelBlock( -const in vec3 normalW, -const in vec3 viewDirectionW, -const in float alpha, -const in float microSurface, -out alphaFresnelOutParams outParams -) -{ - - - -float opacityPerceptual=alpha; -#ifdef LINEARALPHAFRESNEL -float opacity0=opacityPerceptual; -#else -float opacity0=opacityPerceptual*opacityPerceptual; -#endif -float opacity90=fresnelGrazingReflectance(opacity0); -vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW); - -outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; -#ifdef ALPHATEST -if (outParams.alpha0 -vec3 anisotropyMapData; -#endif -}; -#define pbr_inline -void anisotropicBlock( -const in vec3 vAnisotropy, -#ifdef ANISOTROPIC_TEXTURE -const in vec3 anisotropyMapData, -#endif -const in mat3 TBN, -const in vec3 normalW, -const in vec3 viewDirectionW, -out anisotropicOutParams outParams -) -{ -float anisotropy=vAnisotropy.b; -vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); -#ifdef ANISOTROPIC_TEXTURE -anisotropy*=anisotropyMapData.b; -anisotropyDirection.rg*=anisotropyMapData.rg*2.0-1.0; -#if DEBUGMODE>0 -outParams.anisotropyMapData=anisotropyMapData; -#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); -} -#endif -`;je.a.IncludesShadersStore.pbrBlockAnisotropic=p_;var __=`#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( -const in vec3 vPositionW, -const in vec3 normalW, -#ifdef ANISOTROPIC -const 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( -const in float alphaG, -const in vec3 vReflectionMicrosurfaceInfos, -const in vec2 vReflectionInfos, -const in vec3 vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -const in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -const in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSampler, -const vec3 reflectionCoords, -#else -const in sampler2D reflectionSampler, -const vec2 reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSamplerLow, -const in samplerCube reflectionSamplerHigh, -#else -const in sampler2D reflectionSamplerLow, -const in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -const 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( -const in vec3 vPositionW, -const in vec3 normalW, -const in float alphaG, -const in vec3 vReflectionMicrosurfaceInfos, -const in vec2 vReflectionInfos, -const in vec3 vReflectionColor, -#ifdef ANISOTROPIC -const in anisotropicOutParams anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -const in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -const in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSampler, -#else -const in sampler2D reflectionSampler, -#endif -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -const in vec3 vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -const in mat4 reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -const in samplerCube irradianceSampler, -#else -const in sampler2D irradianceSampler, -#endif -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSamplerLow, -const in samplerCube reflectionSamplerHigh, -#else -const in sampler2D reflectionSamplerLow, -const in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -const 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 -`;je.a.IncludesShadersStore.pbrBlockReflection=__;var m_=`#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 -vec4 sheenMapData; -vec3 sheenEnvironmentReflectance; -#endif -}; -#define pbr_inline -#define inline -void sheenBlock( -const in vec4 vSheenColor, -#ifdef SHEEN_ROUGHNESS -const in float vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -const in vec4 sheenMapRoughnessData, -#endif -#endif -const in float roughness, -#ifdef SHEEN_TEXTURE -const in vec4 sheenMapData, -#endif -const in float reflectance, -#ifdef SHEEN_LINKWITHALBEDO -const in vec3 baseColor, -const in vec3 surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -const in float NdotV, -const in vec3 environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -const in vec2 AARoughnessFactors, -const in vec3 vReflectionMicrosurfaceInfos, -const in vec2 vReflectionInfos, -const in vec3 vReflectionColor, -const in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSampler, -const in vec3 reflectionCoords, -#else -const in sampler2D reflectionSampler, -const in vec2 reflectionCoords, -#endif -const in float NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSamplerLow, -const in samplerCube reflectionSamplerHigh, -#else -const in sampler2D reflectionSamplerLow, -const in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -const in vec2 vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -const in float seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -const 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 -sheenColor.rgb*=sheenMapData.rgb; -#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_ROUGHNESS -vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); -#else -vec3 environmentSheenBrdf=environmentBrdf; -#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 -`;je.a.IncludesShadersStore.pbrBlockSheen=m_;var g_=`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 -mat3 TBNClearCoat; -vec2 clearCoatMapData; -vec4 clearCoatTintMapData; -vec4 environmentClearCoatRadiance; -float clearCoatNdotV; -vec3 clearCoatEnvironmentReflectance; -#endif -}; -#ifdef CLEARCOAT -#define pbr_inline -#define inline -void clearcoatBlock( -const in vec3 vPositionW, -const in vec3 geometricNormalW, -const in vec3 viewDirectionW, -const in vec2 vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -const in vec4 clearCoatMapRoughnessData, -#endif -const in vec3 specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -const in vec2 clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -const in vec4 vClearCoatTintParams, -const in float clearCoatColorAtDistance, -const in vec4 vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -const in vec4 clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -const in vec2 vClearCoatBumpInfos, -const in vec4 clearCoatBumpMapData, -const in vec2 vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -const in mat3 vTBN, -#else -const in vec2 vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -const in mat4 normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -const in vec3 faceNormal, -#endif -#ifdef REFLECTION -const in vec3 vReflectionMicrosurfaceInfos, -const in vec2 vReflectionInfos, -const in vec3 vReflectionColor, -const in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSampler, -#else -const in sampler2D reflectionSampler, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -const in samplerCube reflectionSamplerLow, -const in samplerCube reflectionSamplerHigh, -#else -const in sampler2D reflectionSamplerLow, -const in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -const in vec2 vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -const in float ambientMonochrome, -#endif -#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 -clearCoatColor*=clearCoatTintMapData.rgb; -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 -mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,vClearCoatBumpUV,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=gl_FrontFacing ? clearCoatNormalW : -clearCoatNormalW; -#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(vPositionW,clearCoatNormalW,vClearCoatRefractionParams.y); - -outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) - -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 RADIANCEOCCLUSION -float clearCoatSeo=environmentRadianceOcclusion(ambientMonochrome,clearCoatNdotVUnclamped); -clearCoatEnvironmentReflectance*=clearCoatSeo; -#endif -#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 -`;je.a.IncludesShadersStore.pbrBlockClearcoat=g_;var v_=`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 -vec4 thicknessMap; -vec4 environmentRefraction; -vec3 refractionTransmittance; -#endif -}; -#ifdef SUBSURFACE -#define pbr_inline -#define inline -void subSurfaceBlock( -const in vec3 vSubSurfaceIntensity, -const in vec2 vThicknessParam, -const in vec4 vTintColor, -const in vec3 normalW, -const in vec3 specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -const in vec4 thicknessMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -const in mat4 reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -const in vec3 irradianceVector_, -#endif -#if defined(REALTIME_FILTERING) -const in samplerCube reflectionSampler, -const in vec2 vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -const in samplerCube irradianceSampler, -#else -const in sampler2D irradianceSampler, -#endif -#endif -#endif -#endif -#ifdef SS_REFRACTION -const in vec3 vPositionW, -const in vec3 viewDirectionW, -const in mat4 view, -const in vec3 surfaceAlbedo, -const in vec4 vRefractionInfos, -const in mat4 refractionMatrix, -const in vec3 vRefractionMicrosurfaceInfos, -const in vec4 vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -const in float alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -const in float NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -const in float roughness, -#else -const in float alphaG, -#endif -#ifdef SS_REFRACTIONMAP_3D -const in samplerCube refractionSampler, -#ifndef LODBASEDMICROSFURACE -const in samplerCube refractionSamplerLow, -const in samplerCube refractionSamplerHigh, -#endif -#else -const in sampler2D refractionSampler, -#ifndef LODBASEDMICROSFURACE -const in sampler2D refractionSamplerLow, -const in sampler2D refractionSamplerHigh, -#endif -#endif -#ifdef ANISOTROPIC -const in anisotropicOutParams anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -const in vec2 vRefractionFilteringInfo, -#endif -#endif -#ifdef SS_TRANSLUCENCY -const 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 -float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; -#if DEBUGMODE>0 -outParams.thicknessMap=thicknessMap; -#endif -#ifdef SS_MASK_FROM_THICKNESS_TEXTURE -#ifdef SS_REFRACTION -refractionIntensity*=thicknessMap.g; -#endif -#ifdef SS_TRANSLUCENCY -translucencyIntensity*=thicknessMap.b; -#endif -#elif defined(SS_MASK_FROM_THICKNESS_TEXTURE_GLTF) -#ifdef SS_REFRACTION -refractionIntensity*=thicknessMap.r; -#elif defined(SS_TRANSLUCENCY) -translucencyIntensity*=thicknessMap.r; -#endif -thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; -#endif -#else -float thickness=vThicknessParam.y; -#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 -refractionVector.y=refractionVector.y*vRefractionInfos.w; -vec3 refractionCoords=refractionVector; -refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); -#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; -#endif -#ifdef SS_LODINREFRACTIONALPHA -float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); -#elif defined(SS_LINEARSPECULARREFRACTION) -float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,roughness); -#else -float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG); -#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 -#ifdef REALTIME_FILTERING -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 - -vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance); -outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); - -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; -outParams.refractionIrradiance=refractionIrradiance.rgb; -#endif -} -#endif -`;je.a.IncludesShadersStore.pbrBlockSubSurface=v_;var b_=`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 -`;je.a.IncludesShadersStore.pbrBlockNormalGeometric=b_,f(134);var y_=`#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 -`;je.a.IncludesShadersStore.pbrBlockNormalFinal=y_,f(162);var T_=`#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 -`;je.a.IncludesShadersStore.pbrBlockLightmapInit=T_;var E_=`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 -`;je.a.IncludesShadersStore.pbrBlockGeometryInfo=E_;var S_=`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 -`;je.a.IncludesShadersStore.pbrBlockReflectance0=S_;var A_=`#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 -`;je.a.IncludesShadersStore.pbrBlockReflectance=A_;var P_=`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 -`;je.a.IncludesShadersStore.pbrBlockDirectLighting=P_;var C_=` - - - -#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 -`;je.a.IncludesShadersStore.pbrBlockFinalLitComponents=C_;var x_=` -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; -finalEmissive*=toLinearSpace(emissiveColorTex.rgb); -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; -`;je.a.IncludesShadersStore.pbrBlockFinalUnlitComponents=x_;var R_=`vec4 finalColor=vec4( -finalAmbient + -finalDiffuse + -#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 -finalEmissive, -alpha); - -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -finalColor.rgb*=lightmapColor.rgb; -#else -finalColor.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -#define CUSTOM_FRAGMENT_BEFORE_FOG - -finalColor=max(finalColor,0.0); -`;je.a.IncludesShadersStore.pbrBlockFinalColorComposition=R_,f(155);var O_=`#ifdef IMAGEPROCESSINGPOSTPROCESS - - -finalColor.rgb=clamp(finalColor.rgb,0.,30.0); -#else - -finalColor=applyImageProcessing(finalColor); -#endif -finalColor.a*=visibility; -#ifdef PREMULTIPLYALPHA - -finalColor.rgb*=finalColor.a; -#endif -`;je.a.IncludesShadersStore.pbrBlockImageProcessing=O_;var M_=`#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; -#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; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE == 24 && defined(LIGHTMAP) -gl_FragColor.rgb=lightmapColor.rgb; -#define DEBUGMODE_GAMMA -#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 == 40 && defined(SS_REFRACTION) - -gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE == 41 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; -#define DEBUGMODE_GAMMA -#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; -#define DEBUGMODE_GAMMA - -#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 == 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); -#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 -return; -} -#endif`;je.a.IncludesShadersStore.pbrDebug=M_;var I_=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#extension GL_OES_standard_derivatives : enable -#endif -#ifdef LODBASEDMICROSFURACE -#extension GL_EXT_shader_texture_lod : enable -#endif -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#include[SCENE_MRT_COUNT] -precision highp float; - -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE -#endif - -#include<__decl__pbrFragment> -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef REFLECTION -#include -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include - -#include -#include -#include - -albedoOpacityOutParams albedoOpacityOut; -#ifdef ALBEDO -vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#endif -albedoOpacityBlock( -vAlbedoColor, -#ifdef ALBEDO -albedoTexture, -vAlbedoInfos, -#endif -#ifdef OPACITY -opacityMap, -vOpacityInfos, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -albedoOpacityOut -); -vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo; -float alpha=albedoOpacityOut.alpha; -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -#include -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS - -ambientOcclusionOutParams aoOut; -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; -#endif -ambientOcclusionBlock( -#ifdef AMBIENT -ambientOcclusionColorMap, -vAmbientInfos, -#endif -aoOut -); -#include -#ifdef UNLIT -vec3 diffuseBase=vec3(1.,1.,1.); -#else - -vec3 baseColor=surfaceAlbedo; -reflectivityOutParams reflectivityOut; -#if defined(REFLECTIVITY) -vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset); -vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; -#ifndef METALLICWORKFLOW -surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); -surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; -#endif -#endif -#if defined(MICROSURFACEMAP) -vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; -#endif -#ifdef METALLICWORKFLOW -vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; -#ifdef METALLIC_REFLECTANCE -vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); -metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); -metallicReflectanceFactors*=metallicReflectanceFactorsMap; -#endif -#endif -reflectivityBlock( -vReflectivityColor, -#ifdef METALLICWORKFLOW -surfaceAlbedo, -metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -vReflectivityInfos, -surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor, -#endif -#ifdef MICROSURFACEMAP -microSurfaceTexel, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -reflectivityOut -); -float microSurface=reflectivityOut.microSurface; -float roughness=reflectivityOut.roughness; -#ifdef METALLICWORKFLOW -surfaceAlbedo=reflectivityOut.surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; -#endif - -#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -alphaFresnelOutParams alphaFresnelOut; -alphaFresnelBlock( -normalW, -viewDirectionW, -alpha, -microSurface, -alphaFresnelOut -); -alpha=alphaFresnelOut.alpha; -#endif -#endif - -#include - -#ifdef ANISOTROPIC -anisotropicOutParams anisotropicOut; -#ifdef ANISOTROPIC_TEXTURE -vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; -#endif -anisotropicBlock( -vAnisotropy, -#ifdef ANISOTROPIC_TEXTURE -anisotropyMapData, -#endif -TBN, -normalW, -viewDirectionW, -anisotropicOut -); -#endif - -#ifdef REFLECTION -reflectionOutParams reflectionOut; -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 -); -#endif - -#include - -#ifdef SHEEN -sheenOutParams sheenOut; -#ifdef SHEEN_TEXTURE -vec4 sheenMapData=toLinearSpace(texture2D(sheenSampler,vSheenUV+uvOffset))*vSheenInfos.y; -#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, -#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 - -clearcoatOutParams clearcoatOut; -#ifdef CLEARCOAT -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; -#endif -#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=toLinearSpace(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 -clearcoatOut -); -#else -clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; -#endif - -#include - -subSurfaceOutParams subSurfaceOut; -#ifdef SUBSURFACE -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); -#endif -subSurfaceBlock( -vSubSurfaceIntensity, -vThicknessParam, -vTintColor, -normalW, -specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -thicknessMap, -#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 -#ifdef SS_REFRACTION -vPositionW, -viewDirectionW, -view, -surfaceAlbedo, -vRefractionInfos, -refractionMatrix, -vRefractionMicrosurfaceInfos, -vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -roughness, -#else -alphaG, -#endif -refractionSampler, -#ifndef LODBASEDMICROSFURACE -refractionSamplerLow, -refractionSamplerHigh, -#endif -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -vRefractionFilteringInfo, -#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 -#include[0..maxSimultaneousLights] - -#include -#endif -#include -#include -#include -#include(color,finalColor) -#include -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,1.0); -#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,1.0); -#endif -#ifdef PREPASS_IRRADIANCE -vec3 irradiance=finalDiffuse; -#ifndef UNLIT -#ifdef REFLECTION -irradiance+=finalIrradiance; -#endif -#endif -vec3 sqAlbedo=sqrt(surfaceAlbedo); -#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(irradiance,scatteringDiffusionProfile/255.); -#else -gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); -#endif -#ifdef PREPASS_DEPTHNORMAL -gl_FragData[PREPASS_DEPTHNORMAL_INDEX]=vec4(vViewPos.z,(view*vec4(normalW,0.0)).rgb); -#endif -#ifdef PREPASS_ALBEDO -gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(sqAlbedo,1.0); -#endif -#ifdef PREPASS_REFLECTIVITY -#if defined(REFLECTIVITY) -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(baseReflectivity.rgb,1.0); -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0); -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=finalColor; -#endif -#include -} -`;je.a.ShadersStore.pbrPixelShader=I_;var D_=`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 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 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 -#endif -`;je.a.IncludesShadersStore.pbrVertexDeclaration=D_,f(163),f(164),f(93),f(94),f(100),f(165),f(156),f(158);var L_=`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 -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include - -#include -#include -#if defined(ALBEDO) && ALBEDODIRECTUV == 0 -varying vec2 vAlbedoUV; -#endif -#if defined(DETAIL) && DETAILDIRECTUV == 0 -varying vec2 vDetailUV; -#endif -#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 -varying vec2 vAmbientUV; -#endif -#if defined(OPACITY) && OPACITYDIRECTUV == 0 -varying vec2 vOpacityUV; -#endif -#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 -varying vec2 vEmissiveUV; -#endif -#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 -varying vec2 vLightmapUV; -#endif -#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 -varying vec2 vReflectivityUV; -#endif -#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 -varying vec2 vMicroSurfaceSamplerUV; -#endif -#if defined(METALLIC_REFLECTANCE) && METALLIC_REFLECTANCEDIRECTUV == 0 -varying vec2 vMetallicReflectanceUV; -#endif -#if defined(BUMP) && BUMPDIRECTUV == 0 -varying vec2 vBumpUV; -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) && CLEARCOAT_TEXTUREDIRECTUV == 0 -varying vec2 vClearCoatUV; -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV == 0 -varying vec2 vClearCoatRoughnessUV; -#endif -#if defined(CLEARCOAT_BUMP) && CLEARCOAT_BUMPDIRECTUV == 0 -varying vec2 vClearCoatBumpUV; -#endif -#if defined(CLEARCOAT_TINT_TEXTURE) && CLEARCOAT_TINT_TEXTUREDIRECTUV == 0 -varying vec2 vClearCoatTintUV; -#endif -#endif -#ifdef SHEEN -#if defined(SHEEN_TEXTURE) && SHEEN_TEXTUREDIRECTUV == 0 -varying vec2 vSheenUV; -#endif -#if defined(SHEEN_TEXTURE_ROUGHNESS) && SHEEN_TEXTURE_ROUGHNESSDIRECTUV == 0 -varying vec2 vSheenRoughnessUV; -#endif -#endif -#ifdef ANISOTROPIC -#if defined(ANISOTROPIC_TEXTURE) && ANISOTROPIC_TEXTUREDIRECTUV == 0 -varying vec2 vAnisotropyUV; -#endif -#endif -#ifdef SUBSURFACE -#if defined(SS_THICKNESSANDMASK_TEXTURE) && SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 0 -varying vec2 vThicknessUV; -#endif -#endif - -varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#include -#endif -#endif -#ifdef VERTEXCOLOR -varying vec4 vColor; -#endif -#include -#include -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) - -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0); -#endif -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -vPositionW=vec3(worldPos); -#include -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2])); -vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR == 0u) { -gl_Position=viewProjection*worldPos; -} else { -gl_Position=viewProjectionR*worldPos; -} -#else -gl_Position=viewProjection*worldPos; -#endif -#if DEBUGMODE>0 -vClipSpacePosition=gl_Position; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif - -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(ALBEDO) && ALBEDODIRECTUV == 0 -if (vAlbedoInfos.x == 0.) -{ -vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(DETAIL) && DETAILDIRECTUV == 0 -if (vDetailInfos.x == 0.) -{ -vDetailUV=vec2(detailMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vDetailUV=vec2(detailMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 -if (vAmbientInfos.x == 0.) -{ -vAmbientUV=vec2(ambientMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(OPACITY) && OPACITYDIRECTUV == 0 -if (vOpacityInfos.x == 0.) -{ -vOpacityUV=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 -if (vEmissiveInfos.x == 0.) -{ -vEmissiveUV=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 -if (vLightmapInfos.x == 0.) -{ -vLightmapUV=vec2(lightmapMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 -if (vReflectivityInfos.x == 0.) -{ -vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 -if (vMicroSurfaceSamplerInfos.x == 0.) -{ -vMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(METALLIC_REFLECTANCE) && METALLIC_REFLECTANCEDIRECTUV == 0 -if (vMetallicReflectanceInfos.x == 0.) -{ -vMetallicReflectanceUV=vec2(metallicReflectanceMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vMetallicReflectanceUV=vec2(metallicReflectanceMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(BUMP) && BUMPDIRECTUV == 0 -if (vBumpInfos.x == 0.) -{ -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) && CLEARCOAT_TEXTUREDIRECTUV == 0 -if (vClearCoatInfos.x == 0.) -{ -vClearCoatUV=vec2(clearCoatMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vClearCoatUV=vec2(clearCoatMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV == 0 -if (vClearCoatInfos.z == 0.) -{ -vClearCoatRoughnessUV=vec2(clearCoatRoughnessMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vClearCoatRoughnessUV=vec2(clearCoatRoughnessMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(CLEARCOAT_BUMP) && CLEARCOAT_BUMPDIRECTUV == 0 -if (vClearCoatBumpInfos.x == 0.) -{ -vClearCoatBumpUV=vec2(clearCoatBumpMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vClearCoatBumpUV=vec2(clearCoatBumpMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(CLEARCOAT_TINT_TEXTURE) && CLEARCOAT_TINT_TEXTUREDIRECTUV == 0 -if (vClearCoatTintInfos.x == 0.) -{ -vClearCoatTintUV=vec2(clearCoatTintMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vClearCoatTintUV=vec2(clearCoatTintMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#endif -#ifdef SHEEN -#if defined(SHEEN_TEXTURE) && SHEEN_TEXTUREDIRECTUV == 0 -if (vSheenInfos.x == 0.) -{ -vSheenUV=vec2(sheenMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vSheenUV=vec2(sheenMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#if defined(SHEEN_TEXTURE_ROUGHNESS) && SHEEN_TEXTURE_ROUGHNESSDIRECTUV == 0 -if (vSheenInfos.z == 0.) -{ -vSheenRoughnessUV=vec2(sheenRoughnessMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vSheenRoughnessUV=vec2(sheenRoughnessMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#endif -#ifdef ANISOTROPIC -#if defined(ANISOTROPIC_TEXTURE) && ANISOTROPIC_TEXTUREDIRECTUV == 0 -if (vAnisotropyInfos.x == 0.) -{ -vAnisotropyUV=vec2(anisotropyMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vAnisotropyUV=vec2(anisotropyMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#endif -#ifdef SUBSURFACE -#if defined(SS_THICKNESSANDMASK_TEXTURE) && SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 0 -if (vThicknessInfos.x == 0.) -{ -vThicknessUV=vec2(thicknessMatrix*vec4(uvUpdated,1.0,0.0)); -} -else -{ -vThicknessUV=vec2(thicknessMatrix*vec4(uv2,1.0,0.0)); -} -#endif -#endif - -#include - -#include - -#include - -#include[0..maxSimultaneousLights] - -#ifdef VERTEXCOLOR -vColor=color; -#endif - -#ifdef POINTSIZE -gl_PointSize=pointSize; -#endif - -#include -#define CUSTOM_VERTEX_MAIN_END -}`;je.a.ShadersStore.pbrVertexShader=L_;var ra=f(92),Pr={effect:null,subMesh:null},ks=function(r){function t(){var e=r.call(this)||this;return e.PBR=!0,e.NUM_SAMPLES="0",e.REALTIME_FILTERING=!1,e.MAINUV1=!1,e.MAINUV2=!1,e.UV1=!1,e.UV2=!1,e.ALBEDO=!1,e.GAMMAALBEDO=!1,e.ALBEDODIRECTUV=0,e.VERTEXCOLOR=!1,e.DETAIL=!1,e.DETAILDIRECTUV=0,e.DETAIL_NORMALBLENDMETHOD=0,e.AMBIENT=!1,e.AMBIENTDIRECTUV=0,e.AMBIENTINGRAYSCALE=!1,e.OPACITY=!1,e.VERTEXALPHA=!1,e.OPACITYDIRECTUV=0,e.OPACITYRGB=!1,e.ALPHATEST=!1,e.DEPTHPREPASS=!1,e.ALPHABLEND=!1,e.ALPHAFROMALBEDO=!1,e.ALPHATESTVALUE="0.5",e.SPECULAROVERALPHA=!1,e.RADIANCEOVERALPHA=!1,e.ALPHAFRESNEL=!1,e.LINEARALPHAFRESNEL=!1,e.PREMULTIPLYALPHA=!1,e.EMISSIVE=!1,e.EMISSIVEDIRECTUV=0,e.REFLECTIVITY=!1,e.REFLECTIVITYDIRECTUV=0,e.SPECULARTERM=!1,e.MICROSURFACEFROMREFLECTIVITYMAP=!1,e.MICROSURFACEAUTOMATIC=!1,e.LODBASEDMICROSFURACE=!1,e.MICROSURFACEMAP=!1,e.MICROSURFACEMAPDIRECTUV=0,e.METALLICWORKFLOW=!1,e.ROUGHNESSSTOREINMETALMAPALPHA=!1,e.ROUGHNESSSTOREINMETALMAPGREEN=!1,e.METALLNESSSTOREINMETALMAPBLUE=!1,e.AOSTOREINMETALMAPRED=!1,e.METALLIC_REFLECTANCE=!1,e.METALLIC_REFLECTANCEDIRECTUV=0,e.ENVIRONMENTBRDF=!1,e.ENVIRONMENTBRDF_RGBD=!1,e.NORMAL=!1,e.TANGENT=!1,e.BUMP=!1,e.BUMPDIRECTUV=0,e.OBJECTSPACE_NORMALMAP=!1,e.PARALLAX=!1,e.PARALLAXOCCLUSION=!1,e.NORMALXYSCALE=!0,e.LIGHTMAP=!1,e.LIGHTMAPDIRECTUV=0,e.USELIGHTMAPASSHADOWMAP=!1,e.GAMMALIGHTMAP=!1,e.RGBDLIGHTMAP=!1,e.REFLECTION=!1,e.REFLECTIONMAP_3D=!1,e.REFLECTIONMAP_SPHERICAL=!1,e.REFLECTIONMAP_PLANAR=!1,e.REFLECTIONMAP_CUBIC=!1,e.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,e.REFLECTIONMAP_PROJECTION=!1,e.REFLECTIONMAP_SKYBOX=!1,e.REFLECTIONMAP_EXPLICIT=!1,e.REFLECTIONMAP_EQUIRECTANGULAR=!1,e.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,e.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.INVERTCUBICMAP=!1,e.USESPHERICALFROMREFLECTIONMAP=!1,e.USEIRRADIANCEMAP=!1,e.SPHERICAL_HARMONICS=!1,e.USESPHERICALINVERTEX=!1,e.REFLECTIONMAP_OPPOSITEZ=!1,e.LODINREFLECTIONALPHA=!1,e.GAMMAREFLECTION=!1,e.RGBDREFLECTION=!1,e.LINEARSPECULARREFLECTION=!1,e.RADIANCEOCCLUSION=!1,e.HORIZONOCCLUSION=!1,e.INSTANCES=!1,e.THIN_INSTANCES=!1,e.PREPASS=!1,e.PREPASS_IRRADIANCE=!1,e.PREPASS_IRRADIANCE_INDEX=-1,e.PREPASS_ALBEDO=!1,e.PREPASS_ALBEDO_INDEX=-1,e.PREPASS_DEPTHNORMAL=!1,e.PREPASS_DEPTHNORMAL_INDEX=-1,e.PREPASS_POSITION=!1,e.PREPASS_POSITION_INDEX=-1,e.PREPASS_VELOCITY=!1,e.PREPASS_VELOCITY_INDEX=-1,e.PREPASS_REFLECTIVITY=!1,e.PREPASS_REFLECTIVITY_INDEX=-1,e.SCENE_MRT_COUNT=0,e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE=!1,e.BONES_VELOCITY_ENABLED=!1,e.NONUNIFORMSCALING=!1,e.MORPHTARGETS=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_UV=!1,e.NUM_MORPH_INFLUENCERS=0,e.IMAGEPROCESSING=!1,e.VIGNETTE=!1,e.VIGNETTEBLENDMODEMULTIPLY=!1,e.VIGNETTEBLENDMODEOPAQUE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=!1,e.SAMPLER3DBGRMAP=!1,e.IMAGEPROCESSINGPOSTPROCESS=!1,e.EXPOSURE=!1,e.MULTIVIEW=!1,e.USEPHYSICALLIGHTFALLOFF=!1,e.USEGLTFLIGHTFALLOFF=!1,e.TWOSIDEDLIGHTING=!1,e.SHADOWFLOAT=!1,e.CLIPPLANE=!1,e.CLIPPLANE2=!1,e.CLIPPLANE3=!1,e.CLIPPLANE4=!1,e.CLIPPLANE5=!1,e.CLIPPLANE6=!1,e.POINTSIZE=!1,e.FOG=!1,e.LOGARITHMICDEPTH=!1,e.FORCENORMALFORWARD=!1,e.SPECULARAA=!1,e.CLEARCOAT=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!0,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.BRDF_V_HEIGHT_CORRELATED=!1,e.MS_BRDF_ENERGY_CONSERVATION=!1,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,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.SUBSURFACE=!1,e.SS_REFRACTION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE_GLTF=!1,e.UNLIT=!1,e.DEBUGMODE=0,e.rebuild(),e}return Object(c.d)(t,r),t.prototype.reset=function(){r.prototype.reset.call(this),this.ALPHATESTVALUE="0.5",this.PBR=!0},t}(ta.a),pn=function(r){function t(e,n){var i=r.call(this,e,n)||this;return i._directIntensity=1,i._emissiveIntensity=1,i._environmentIntensity=1,i._specularIntensity=1,i._lightingInfos=new u.f(i._directIntensity,i._emissiveIntensity,i._environmentIntensity,i._specularIntensity),i._disableBumpMap=!1,i._albedoTexture=null,i._ambientTexture=null,i._ambientTextureStrength=1,i._ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,i._opacityTexture=null,i._reflectionTexture=null,i._emissiveTexture=null,i._reflectivityTexture=null,i._metallicTexture=null,i._metallic=null,i._roughness=null,i._metallicF0Factor=1,i._metallicReflectanceColor=M.a.White(),i._metallicReflectanceTexture=null,i._microSurfaceTexture=null,i._bumpTexture=null,i._lightmapTexture=null,i._ambientColor=new M.a(0,0,0),i._albedoColor=new M.a(1,1,1),i._reflectivityColor=new M.a(1,1,1),i._reflectionColor=new M.a(1,1,1),i._emissiveColor=new M.a(0,0,0),i._microSurface=.9,i._useLightmapAsShadowmap=!1,i._useHorizonOcclusion=!0,i._useRadianceOcclusion=!0,i._useAlphaFromAlbedoTexture=!1,i._useSpecularOverAlpha=!0,i._useMicroSurfaceFromReflectivityMapAlpha=!1,i._useRoughnessFromMetallicTextureAlpha=!0,i._useRoughnessFromMetallicTextureGreen=!1,i._useMetallnessFromMetallicTextureBlue=!1,i._useAmbientOcclusionFromMetallicTextureRed=!1,i._useAmbientInGrayScale=!1,i._useAutoMicroSurfaceFromReflectivityMap=!1,i._lightFalloff=t.LIGHTFALLOFF_PHYSICAL,i._useRadianceOverAlpha=!0,i._useObjectSpaceNormalMap=!1,i._useParallax=!1,i._useParallaxOcclusion=!1,i._parallaxScaleBias=.05,i._disableLighting=!1,i._maxSimultaneousLights=4,i._invertNormalMapX=!1,i._invertNormalMapY=!1,i._twoSidedLighting=!1,i._alphaCutOff=.4,i._forceAlphaTest=!1,i._useAlphaFresnel=!1,i._useLinearAlphaFresnel=!1,i._environmentBRDFTexture=null,i._forceIrradianceInFragment=!1,i._realTimeFiltering=!1,i._realTimeFilteringQuality=h.a.TEXTURE_FILTERING_QUALITY_LOW,i._forceNormalForward=!1,i._enableSpecularAntiAliasing=!1,i._imageProcessingObserver=null,i._renderTargets=new li.a(16),i._globalAmbientColor=new M.a(0,0,0),i._useLogarithmicDepth=!1,i._unlit=!1,i._debugMode=0,i.debugMode=0,i.debugLimit=-1,i.debugFactor=1,i.clearCoat=new Sr(i._markAllSubMeshesAsTexturesDirty.bind(i)),i.anisotropy=new Ar(i._markAllSubMeshesAsTexturesDirty.bind(i)),i.brdf=new qp(i._markAllSubMeshesAsMiscDirty.bind(i)),i.sheen=new so(i._markAllSubMeshesAsTexturesDirty.bind(i)),i.detailMap=new ra.a(i._markAllSubMeshesAsTexturesDirty.bind(i)),i._rebuildInParallel=!1,i._attachImageProcessingConfiguration(null),i.getRenderTargetTextures=function(){return i._renderTargets.reset(),ht.a.ReflectionTextureEnabled&&i._reflectionTexture&&i._reflectionTexture.isRenderTarget&&i._renderTargets.push(i._reflectionTexture),i.subSurface.fillRenderTargetTextures(i._renderTargets),i._renderTargets},i._environmentBRDFTexture=ia.GetEnvironmentBRDFTexture(n),i.subSurface=new co(i._markAllSubMeshesAsTexturesDirty.bind(i),i._markScenePrePassDirty.bind(i),n),i.prePassConfiguration=new Vs.a,i}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"realTimeFiltering",{get:function(){return this._realTimeFiltering},set:function(e){this._realTimeFiltering=e,this.markAsDirty(h.a.MATERIAL_TextureDirtyFlag)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"realTimeFilteringQuality",{get:function(){return this._realTimeFilteringQuality},set:function(e){this._realTimeFilteringQuality=e,this.markAsDirty(h.a.MATERIAL_TextureDirtyFlag)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"canRenderToMRT",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var n=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){n._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!!(ht.a.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this.subSurface.hasRenderTargetTextures()},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PBRBaseMaterial"},Object.defineProperty(t.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_disableAlphaBlending",{get:function(){return this.subSurface.disableAlphaBlending||this._transparencyMode===t.PBRMATERIAL_OPAQUE||this._transparencyMode===t.PBRMATERIAL_ALPHATEST},enumerable:!1,configurable:!0}),t.prototype.needAlphaBlending=function(){return!this._disableAlphaBlending&&(this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture())},t.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest||!this.subSurface.disableAlphaBlending&&this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===t.PBRMATERIAL_ALPHATEST)},t.prototype._shouldUseAlphaFromAlbedoTexture=function(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==t.PBRMATERIAL_OPAQUE},t.prototype._hasAlphaChannel=function(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null},t.prototype.getAlphaTestTexture=function(){return this._albedoTexture},t.prototype.isReadyForSubMesh=function(e,n,i){if(n.effect&&this.isFrozen&&n.effect._wasPreviouslyReady)return!0;n._materialDefines||(n._materialDefines=new ks);var o=n._materialDefines;if(this._isReadyForSubMesh(n))return!0;var a=this.getScene(),s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(this._albedoTexture&&ht.a.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&ht.a.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&ht.a.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;var d=this._getReflectionTexture();if(d&&ht.a.ReflectionTextureEnabled&&(!d.isReadyOrNotBlocking()||d.irradianceTexture&&!d.irradianceTexture.isReadyOrNotBlocking())||this._lightmapTexture&&ht.a.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&ht.a.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(ht.a.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._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(s.getCaps().standardDerivatives&&this._bumpTexture&&ht.a.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&ht.a.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(!(this.subSurface.isReadyForSubMesh(o,a)&&this.clearCoat.isReadyForSubMesh(o,a,s,this._disableBumpMap)&&this.sheen.isReadyForSubMesh(o,a)&&this.anisotropy.isReadyForSubMesh(o,a)&&this.detailMap.isReadyForSubMesh(o,a))||o._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;s.getCaps().standardDerivatives||e.isVerticesDataPresent(Me.b.NormalKind)||(e.createNormals(!0),l.a.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));var p=n.effect,y=o._areLightsDisposed,P=this._prepareEffect(e,o,this.onCompiled,this.onError,i,null,n.getRenderingMesh().hasThinInstances);if(P)if(this._onEffectCreatedObservable&&(Pr.effect=P,Pr.subMesh=n,this._onEffectCreatedObservable.notifyObservers(Pr)),this.allowShaderHotSwapping&&p&&!P.isReady()){if(P=p,this._rebuildInParallel=!0,o.markAsUnprocessed(),y)return o._areLightsDisposed=!0,!1}else this._rebuildInParallel=!1,a.resetCachedMaterial(),n.setEffect(P,o),this.buildUniformLayout();return!(!n.effect||!n.effect.isReady())&&(o._renderId=a.getRenderId(),n.effect._wasPreviouslyReady=!0,!0)},t.prototype.isMetallicWorkflow=function(){return!(this._metallic==null&&this._roughness==null&&!this._metallicTexture)},t.prototype._prepareEffect=function(e,n,i,o,a,s,d){if(i===void 0&&(i=null),o===void 0&&(o=null),a===void 0&&(a=null),s===void 0&&(s=null),this._prepareDefines(e,n,a,s,d),!n.isDirty)return null;n.markAsProcessed();var p=this.getScene().getEngine(),y=new Er.a,P=0;n.USESPHERICALINVERTEX&&y.addFallback(P++,"USESPHERICALINVERTEX"),n.FOG&&y.addFallback(P,"FOG"),n.SPECULARAA&&y.addFallback(P,"SPECULARAA"),n.POINTSIZE&&y.addFallback(P,"POINTSIZE"),n.LOGARITHMICDEPTH&&y.addFallback(P,"LOGARITHMICDEPTH"),n.PARALLAX&&y.addFallback(P,"PARALLAX"),n.PARALLAXOCCLUSION&&y.addFallback(P++,"PARALLAXOCCLUSION"),P=Ar.AddFallbacks(n,y,P),P=Ar.AddFallbacks(n,y,P),P=co.AddFallbacks(n,y,P),P=so.AddFallbacks(n,y,P),n.ENVIRONMENTBRDF&&y.addFallback(P++,"ENVIRONMENTBRDF"),n.TANGENT&&y.addFallback(P++,"TANGENT"),n.BUMP&&y.addFallback(P++,"BUMP"),P=tt.a.HandleFallbacksForShadows(n,y,this._maxSimultaneousLights,P++),n.SPECULARTERM&&y.addFallback(P++,"SPECULARTERM"),n.USESPHERICALFROMREFLECTIONMAP&&y.addFallback(P++,"USESPHERICALFROMREFLECTIONMAP"),n.USEIRRADIANCEMAP&&y.addFallback(P++,"USEIRRADIANCEMAP"),n.LIGHTMAP&&y.addFallback(P++,"LIGHTMAP"),n.NORMAL&&y.addFallback(P++,"NORMAL"),n.AMBIENT&&y.addFallback(P++,"AMBIENT"),n.EMISSIVE&&y.addFallback(P++,"EMISSIVE"),n.VERTEXCOLOR&&y.addFallback(P++,"VERTEXCOLOR"),n.MORPHTARGETS&&y.addFallback(P++,"MORPHTARGETS"),n.MULTIVIEW&&y.addFallback(0,"MULTIVIEW");var O=[Me.b.PositionKind];n.NORMAL&&O.push(Me.b.NormalKind),n.TANGENT&&O.push(Me.b.TangentKind),n.UV1&&O.push(Me.b.UVKind),n.UV2&&O.push(Me.b.UV2Kind),n.VERTEXCOLOR&&O.push(Me.b.ColorKind),tt.a.PrepareAttributesForBones(O,e,n,y),tt.a.PrepareAttributesForInstances(O,n),tt.a.PrepareAttributesForMorphTargets(O,e,n);var U="pbr",F=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","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"],z=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler"],J=["Material","Scene"];ra.a.AddUniforms(F),ra.a.AddSamplers(z),co.AddUniforms(F),co.AddSamplers(z),Sr.AddUniforms(F),Sr.AddSamplers(z),Ar.AddUniforms(F),Ar.AddSamplers(z),so.AddUniforms(F),so.AddSamplers(z),Vs.a.AddUniforms(F),Vs.a.AddSamplers(F),vn.a&&(vn.a.PrepareUniforms(F,n),vn.a.PrepareSamplers(z,n)),tt.a.PrepareUniformsAndSamplersList({uniformsNames:F,uniformBuffersNames:J,samplers:z,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});var ie={};this.customShaderNameResolve&&(U=this.customShaderNameResolve(U,F,J,z,n,O,ie));var se=n.toString();return p.createEffect(U,{attributes:O,uniformsNames:F,uniformBuffersNames:J,samplers:z,defines:se,fallbacks:y,onCompiled:i,onError:o,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},processFinalCode:ie.processFinalCode,multiTarget:n.PREPASS},p)},t.prototype._prepareDefines=function(e,n,i,o,a){i===void 0&&(i=null),o===void 0&&(o=null),a===void 0&&(a=!1);var s=this.getScene(),d=s.getEngine();if(tt.a.PrepareDefinesForLights(s,e,n,!0,this._maxSimultaneousLights,this._disableLighting),n._needNormals=!0,tt.a.PrepareDefinesForMultiview(s,n),tt.a.PrepareDefinesForPrePass(s,n,this.canRenderToMRT),n.METALLICWORKFLOW=this.isMetallicWorkflow(),n._areTexturesDirty){if(n._needUVs=!1,s.texturesEnabled){s.getEngine().getCaps().textureLOD&&(n.LODBASEDMICROSFURACE=!0),this._albedoTexture&&ht.a.DiffuseTextureEnabled?(tt.a.PrepareDefinesForMergedUV(this._albedoTexture,n,"ALBEDO"),n.GAMMAALBEDO=this._albedoTexture.gammaSpace):n.ALBEDO=!1,this._ambientTexture&&ht.a.AmbientTextureEnabled?(tt.a.PrepareDefinesForMergedUV(this._ambientTexture,n,"AMBIENT"),n.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):n.AMBIENT=!1,this._opacityTexture&&ht.a.OpacityTextureEnabled?(tt.a.PrepareDefinesForMergedUV(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):n.OPACITY=!1;var p=this._getReflectionTexture();if(p&&ht.a.ReflectionTextureEnabled){switch(n.REFLECTION=!0,n.GAMMAREFLECTION=p.gammaSpace,n.RGBDREFLECTION=p.isRGBD,n.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!p.invertZ:p.invertZ,n.LODINREFLECTIONALPHA=p.lodLevelInAlpha,n.LINEARSPECULARREFLECTION=p.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(n.NUM_SAMPLES=""+this.realTimeFilteringQuality,d.webGLVersion>1&&(n.NUM_SAMPLES=n.NUM_SAMPLES+"u"),n.REALTIME_FILTERING=!0):n.REALTIME_FILTERING=!1,p.coordinatesMode===we.a.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=p.isCube,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,p.coordinatesMode){case we.a.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case we.a.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case we.a.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case we.a.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case we.a.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case we.a.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case we.a.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case we.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case we.a.CUBIC_MODE:case we.a.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0,n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!p.boundingBoxSize}p.coordinatesMode!==we.a.SKYBOX_MODE&&(p.irradianceTexture?(n.USEIRRADIANCEMAP=!0,n.USESPHERICALFROMREFLECTIONMAP=!1):p.isCube&&(n.USESPHERICALFROMREFLECTIONMAP=!0,n.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||s.getEngine().getCaps().maxVaryingVectors<=8?n.USESPHERICALINVERTEX=!1:n.USESPHERICALINVERTEX=!0))}else n.REFLECTION=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.USESPHERICALFROMREFLECTIONMAP=!1,n.USEIRRADIANCEMAP=!1,n.USESPHERICALINVERTEX=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1,n.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&ht.a.LightmapTextureEnabled?(tt.a.PrepareDefinesForMergedUV(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):n.LIGHTMAP=!1,this._emissiveTexture&&ht.a.EmissiveTextureEnabled?tt.a.PrepareDefinesForMergedUV(this._emissiveTexture,n,"EMISSIVE"):n.EMISSIVE=!1,ht.a.SpecularTextureEnabled?(this._metallicTexture?(tt.a.PrepareDefinesForMergedUV(this._metallicTexture,n,"REFLECTIVITY"),n.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,n.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,n.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,n.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed):this._reflectivityTexture?(tt.a.PrepareDefinesForMergedUV(this._reflectivityTexture,n,"REFLECTIVITY"),n.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,n.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):n.REFLECTIVITY=!1,this._metallicReflectanceTexture?tt.a.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,n,"METALLIC_REFLECTANCE"):n.METALLIC_REFLECTANCE=!1,this._microSurfaceTexture?tt.a.PrepareDefinesForMergedUV(this._microSurfaceTexture,n,"MICROSURFACEMAP"):n.MICROSURFACEMAP=!1):(n.REFLECTIVITY=!1,n.MICROSURFACEMAP=!1),s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&ht.a.BumpTextureEnabled&&!this._disableBumpMap?(tt.a.PrepareDefinesForMergedUV(this._bumpTexture,n,"BUMP"),this._useParallax&&this._albedoTexture&&ht.a.DiffuseTextureEnabled?(n.PARALLAX=!0,n.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):n.PARALLAX=!1,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):n.BUMP=!1,this._environmentBRDFTexture&&ht.a.ReflectionTextureEnabled?(n.ENVIRONMENTBRDF=!0,n.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(n.ENVIRONMENTBRDF=!1,n.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?n.ALPHAFROMALBEDO=!0:n.ALPHAFROMALBEDO=!1}n.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===t.LIGHTFALLOFF_STANDARD?(n.USEPHYSICALLIGHTFALLOFF=!1,n.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===t.LIGHTFALLOFF_GLTF?(n.USEPHYSICALLIGHTFALLOFF=!1,n.USEGLTFLIGHTFALLOFF=!0):(n.USEPHYSICALLIGHTFALLOFF=!0,n.USEGLTFLIGHTFALLOFF=!1),n.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?n.TWOSIDEDLIGHTING=!0:n.TWOSIDEDLIGHTING=!1,n.SPECULARAA=s.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(n._areTexturesDirty||n._areMiscDirty)&&(n.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),n.PREMULTIPLYALPHA=this.alphaMode===h.a.ALPHA_PREMULTIPLIED||this.alphaMode===h.a.ALPHA_PREMULTIPLIED_PORTERDUFF,n.ALPHABLEND=this.needAlphaBlendingForMesh(e),n.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,n.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),n._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(n),n.FORCENORMALFORWARD=this._forceNormalForward,n.RADIANCEOCCLUSION=this._useRadianceOcclusion,n.HORIZONOCCLUSION=this._useHorizonOcclusion,n._areMiscDirty&&(tt.a.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n),n.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Me.b.NormalKind),n.DEBUGMODE=this._debugMode),this.detailMap.prepareDefines(n,s),this.subSurface.prepareDefines(n,s),this.clearCoat.prepareDefines(n,s),this.anisotropy.prepareDefines(n,e,s),this.brdf.prepareDefines(n),this.sheen.prepareDefines(n,s),tt.a.PrepareDefinesForFrameBoundValues(s,d,n,!!i,o,a),tt.a.PrepareDefinesForAttributes(e,n,!0,!0,!0,this._transparencyMode!==t.PBRMATERIAL_OPAQUE)},t.prototype.forceCompilation=function(e,n,i){var o=this,a=Object(c.a)({clipPlane:!1,useInstances:!1},i),s=new ks,d=this._prepareEffect(e,s,void 0,void 0,a.useInstances,a.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Pr.effect=d,Pr.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Pr)),d.isReady()?n&&n(this):d.onCompileObservable.add(function(){n&&n(o)})},t.prototype.buildUniformLayout=function(){var 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("visibility",1),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),Sr.PrepareUniformBuffer(e),Ar.PrepareUniformBuffer(e),so.PrepareUniformBuffer(e),co.PrepareUniformBuffer(e),ra.a.PrepareUniformBuffer(e),e.create()},t.prototype.unbind=function(){if(this._activeEffect){var e=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),e=!0),this.subSurface.unbind(this._activeEffect)&&(e=!0),e&&this._markAllSubMeshesAsTexturesDirty()}r.prototype.unbind.call(this)},t.prototype.bindForSubMesh=function(e,n,i){var o=this.getScene(),a=i._materialDefines;if(a){var s=i.effect;if(s){this._activeEffect=s,a.INSTANCES&&!a.THIN_INSTANCES||this.bindOnlyWorldMatrix(e),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,n,e,this.isFrozen),a.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var d=this._mustRebind(o,s,n.visibility);tt.a.BindBonesParameters(n,this._activeEffect,this.prePassConfiguration);var p=null,y=this._uniformBuffer;if(d){var P=o.getEngine();if(y.bindToEffect(s,"Material"),this.bindViewProjection(s),p=this._getReflectionTexture(),!y.useUbo||!this.isFrozen||!y.isSync){if(o.texturesEnabled){if(this._albedoTexture&&ht.a.DiffuseTextureEnabled&&(y.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),tt.a.BindTextureMatrix(this._albedoTexture,y,"albedo")),this._ambientTexture&&ht.a.AmbientTextureEnabled&&(y.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),tt.a.BindTextureMatrix(this._ambientTexture,y,"ambient")),this._opacityTexture&&ht.a.OpacityTextureEnabled&&(y.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),tt.a.BindTextureMatrix(this._opacityTexture,y,"opacity")),p&&ht.a.ReflectionTextureEnabled){if(y.updateMatrix("reflectionMatrix",p.getReflectionTextureMatrix()),y.updateFloat2("vReflectionInfos",p.level,0),p.boundingBoxSize){var O=p;y.updateVector3("vReflectionPosition",O.boundingBoxPosition),y.updateVector3("vReflectionSize",O.boundingBoxSize)}if(this.realTimeFiltering){var U=p.getSize().width;y.updateFloat2("vReflectionFilteringInfo",U,$.a.Log2(U))}if(!a.USEIRRADIANCEMAP){var F=p.sphericalPolynomial;if(a.USESPHERICALFROMREFLECTIONMAP&&F)if(a.SPHERICAL_HARMONICS){var z=F.preScaledHarmonics;this._activeEffect.setVector3("vSphericalL00",z.l00),this._activeEffect.setVector3("vSphericalL1_1",z.l1_1),this._activeEffect.setVector3("vSphericalL10",z.l10),this._activeEffect.setVector3("vSphericalL11",z.l11),this._activeEffect.setVector3("vSphericalL2_2",z.l2_2),this._activeEffect.setVector3("vSphericalL2_1",z.l2_1),this._activeEffect.setVector3("vSphericalL20",z.l20),this._activeEffect.setVector3("vSphericalL21",z.l21),this._activeEffect.setVector3("vSphericalL22",z.l22)}else this._activeEffect.setFloat3("vSphericalX",F.x.x,F.x.y,F.x.z),this._activeEffect.setFloat3("vSphericalY",F.y.x,F.y.y,F.y.z),this._activeEffect.setFloat3("vSphericalZ",F.z.x,F.z.y,F.z.z),this._activeEffect.setFloat3("vSphericalXX_ZZ",F.xx.x-F.zz.x,F.xx.y-F.zz.y,F.xx.z-F.zz.z),this._activeEffect.setFloat3("vSphericalYY_ZZ",F.yy.x-F.zz.x,F.yy.y-F.zz.y,F.yy.z-F.zz.z),this._activeEffect.setFloat3("vSphericalZZ",F.zz.x,F.zz.y,F.zz.z),this._activeEffect.setFloat3("vSphericalXY",F.xy.x,F.xy.y,F.xy.z),this._activeEffect.setFloat3("vSphericalYZ",F.yz.x,F.yz.y,F.yz.z),this._activeEffect.setFloat3("vSphericalZX",F.zx.x,F.zx.y,F.zx.z)}y.updateFloat3("vReflectionMicrosurfaceInfos",p.getSize().width,p.lodGenerationScale,p.lodGenerationOffset)}this._emissiveTexture&&ht.a.EmissiveTextureEnabled&&(y.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),tt.a.BindTextureMatrix(this._emissiveTexture,y,"emissive")),this._lightmapTexture&&ht.a.LightmapTextureEnabled&&(y.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),tt.a.BindTextureMatrix(this._lightmapTexture,y,"lightmap")),ht.a.SpecularTextureEnabled&&(this._metallicTexture?(y.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),tt.a.BindTextureMatrix(this._metallicTexture,y,"reflectivity")):this._reflectivityTexture&&(y.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),tt.a.BindTextureMatrix(this._reflectivityTexture,y,"reflectivity")),this._metallicReflectanceTexture&&(y.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),tt.a.BindTextureMatrix(this._metallicReflectanceTexture,y,"metallicReflectance")),this._microSurfaceTexture&&(y.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),tt.a.BindTextureMatrix(this._microSurfaceTexture,y,"microSurfaceSampler"))),this._bumpTexture&&P.getCaps().standardDerivatives&&ht.a.BumpTextureEnabled&&!this._disableBumpMap&&(y.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),tt.a.BindTextureMatrix(this._bumpTexture,y,"bump"),o._mirroredCameraPosition?y.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):y.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&y.updateFloat("pointSize",this.pointSize),a.METALLICWORKFLOW){M.c.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,M.c.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,y.updateColor4("vReflectivityColor",M.c.Color3[0],1);var J=this.subSurface.indexOfRefraction,ie=Math.pow((J-1)/(J+1),2);this._metallicReflectanceColor.scaleToRef(ie*this._metallicF0Factor,M.c.Color3[0]);var se=this._metallicF0Factor;y.updateColor4("vMetallicReflectanceFactors",M.c.Color3[0],se)}else y.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);y.updateColor3("vEmissiveColor",ht.a.EmissiveTextureEnabled?this._emissiveColor:M.a.BlackReadOnly),y.updateColor3("vReflectionColor",this._reflectionColor),!a.SS_REFRACTION&&this.subSurface.linkRefractionWithTransparency?y.updateColor4("vAlbedoColor",this._albedoColor,1):y.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,y.updateVector4("vLightingIntensity",this._lightingInfos)}y.updateFloat("visibility",n.visibility),o.texturesEnabled&&(this._albedoTexture&&ht.a.DiffuseTextureEnabled&&y.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&ht.a.AmbientTextureEnabled&&y.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ht.a.OpacityTextureEnabled&&y.setTexture("opacitySampler",this._opacityTexture),p&&ht.a.ReflectionTextureEnabled&&(a.LODBASEDMICROSFURACE?y.setTexture("reflectionSampler",p):(y.setTexture("reflectionSampler",p._lodTextureMid||p),y.setTexture("reflectionSamplerLow",p._lodTextureLow||p),y.setTexture("reflectionSamplerHigh",p._lodTextureHigh||p)),a.USEIRRADIANCEMAP&&y.setTexture("irradianceSampler",p.irradianceTexture)),a.ENVIRONMENTBRDF&&y.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&ht.a.EmissiveTextureEnabled&&y.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ht.a.LightmapTextureEnabled&&y.setTexture("lightmapSampler",this._lightmapTexture),ht.a.SpecularTextureEnabled&&(this._metallicTexture?y.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&y.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&y.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._microSurfaceTexture&&y.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&P.getCaps().standardDerivatives&&ht.a.BumpTextureEnabled&&!this._disableBumpMap&&y.setTexture("bumpSampler",this._bumpTexture)),this.detailMap.bindForSubMesh(y,o,this.isFrozen),this.subSurface.bindForSubMesh(y,o,P,this.isFrozen,a.LODBASEDMICROSFURACE,this.realTimeFiltering),this.clearCoat.bindForSubMesh(y,o,P,this._disableBumpMap,this.isFrozen,this._invertNormalMapX,this._invertNormalMapY,i),this.anisotropy.bindForSubMesh(y,o,this.isFrozen),this.sheen.bindForSubMesh(y,o,this.isFrozen,i),tt.a.BindClipPlane(this._activeEffect,o),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var ce=o._forcedViewPosition?o._forcedViewPosition:o._mirroredCameraPosition?o._mirroredCameraPosition:o.activeCamera.globalPosition,ue=o.useRightHandedSystem===(o._mirroredCameraPosition!=null);s.setFloat4("vEyePosition",ce.x,ce.y,ce.z,ue?-1:1),s.setColor3("vAmbientColor",this._globalAmbientColor),s.setFloat2("vDebugMode",this.debugLimit,this.debugFactor)}!d&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&tt.a.BindLights(o,n,this._activeEffect,a,this._maxSimultaneousLights,this._rebuildInParallel),(o.fogEnabled&&n.applyFog&&o.fogMode!==_e.a.FOGMODE_NONE||p)&&this.bindView(s),tt.a.BindFogParameters(o,n,this._activeEffect,!0),a.NUM_MORPH_INFLUENCERS&&tt.a.BindMorphTargetParameters(n,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),tt.a.BindLogDepth(a,this._activeEffect,o)),y.update(),this._afterBind(n,this._activeEffect)}}},t.prototype.getAnimatables=function(){var e=[];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.detailMap.getAnimatables(e),this.subSurface.getAnimatables(e),this.clearCoat.getAnimatables(e),this.sheen.getAnimatables(e),this.anisotropy.getAnimatables(e),e},t.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},t.prototype.getActiveTextures=function(){var e=r.prototype.getActiveTextures.call(this);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._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this.detailMap.getActiveTextures(e),this.subSurface.getActiveTextures(e),this.clearCoat.getActiveTextures(e),this.sheen.getActiveTextures(e),this.anisotropy.getActiveTextures(e),e},t.prototype.hasTexture=function(e){return!!r.prototype.hasTexture.call(this,e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this.detailMap.hasTexture(e)||this.subSurface.hasTexture(e)||this.clearCoat.hasTexture(e)||this.sheen.hasTexture(e)||this.anisotropy.hasTexture(e)},t.prototype.setPrePassRenderer=function(e){if(this.subSurface.isScatteringEnabled){var n=this.getScene().enableSubSurfaceForPrePass();return n&&(n.enabled=!0),!0}return!1},t.prototype.dispose=function(e,n){var i,o,a,s,d,p,y,P,O,U,F;n&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)===null||i===void 0||i.dispose(),(o=this._ambientTexture)===null||o===void 0||o.dispose(),(a=this._opacityTexture)===null||a===void 0||a.dispose(),(s=this._reflectionTexture)===null||s===void 0||s.dispose(),(d=this._emissiveTexture)===null||d===void 0||d.dispose(),(p=this._metallicTexture)===null||p===void 0||p.dispose(),(y=this._reflectivityTexture)===null||y===void 0||y.dispose(),(P=this._bumpTexture)===null||P===void 0||P.dispose(),(O=this._lightmapTexture)===null||O===void 0||O.dispose(),(U=this._metallicReflectanceTexture)===null||U===void 0||U.dispose(),(F=this._microSurfaceTexture)===null||F===void 0||F.dispose()),this.detailMap.dispose(n),this.subSurface.dispose(n),this.clearCoat.dispose(n),this.sheen.dispose(n),this.anisotropy.dispose(n),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),r.prototype.dispose.call(this,e,n)},t.PBRMATERIAL_OPAQUE=Ht.a.MATERIAL_OPAQUE,t.PBRMATERIAL_ALPHATEST=Ht.a.MATERIAL_ALPHATEST,t.PBRMATERIAL_ALPHABLEND=Ht.a.MATERIAL_ALPHABLEND,t.PBRMATERIAL_ALPHATESTANDBLEND=Ht.a.MATERIAL_ALPHATESTANDBLEND,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,t.LIGHTFALLOFF_PHYSICAL=0,t.LIGHTFALLOFF_GLTF=1,t.LIGHTFALLOFF_STANDARD=2,Object(c.c)([Object(L.i)()],t.prototype,"_imageProcessingConfiguration",void 0),Object(c.c)([Object(L.b)("_markAllSubMeshesAsMiscDirty")],t.prototype,"debugMode",void 0),Object(c.c)([Object(L.c)()],t.prototype,"useLogarithmicDepth",null),t}(na.a),lo=function(r){function t(e,n){var i=r.call(this,e,n)||this;return i.directIntensity=1,i.emissiveIntensity=1,i.environmentIntensity=1,i.specularIntensity=1,i.disableBumpMap=!1,i.ambientTextureStrength=1,i.ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,i.metallicF0Factor=1,i.metallicReflectanceColor=M.a.White(),i.ambientColor=new M.a(0,0,0),i.albedoColor=new M.a(1,1,1),i.reflectivityColor=new M.a(1,1,1),i.reflectionColor=new M.a(1,1,1),i.emissiveColor=new M.a(0,0,0),i.microSurface=1,i.useLightmapAsShadowmap=!1,i.useAlphaFromAlbedoTexture=!1,i.forceAlphaTest=!1,i.alphaCutOff=.4,i.useSpecularOverAlpha=!0,i.useMicroSurfaceFromReflectivityMapAlpha=!1,i.useRoughnessFromMetallicTextureAlpha=!0,i.useRoughnessFromMetallicTextureGreen=!1,i.useMetallnessFromMetallicTextureBlue=!1,i.useAmbientOcclusionFromMetallicTextureRed=!1,i.useAmbientInGrayScale=!1,i.useAutoMicroSurfaceFromReflectivityMap=!1,i.useRadianceOverAlpha=!0,i.useObjectSpaceNormalMap=!1,i.useParallax=!1,i.useParallaxOcclusion=!1,i.parallaxScaleBias=.05,i.disableLighting=!1,i.forceIrradianceInFragment=!1,i.maxSimultaneousLights=4,i.invertNormalMapX=!1,i.invertNormalMapY=!1,i.twoSidedLighting=!1,i.useAlphaFresnel=!1,i.useLinearAlphaFresnel=!1,i.environmentBRDFTexture=null,i.forceNormalForward=!1,i.enableSpecularAntiAliasing=!1,i.useHorizonOcclusion=!0,i.useRadianceOcclusion=!0,i.unlit=!1,i._environmentBRDFTexture=ia.GetEnvironmentBRDFTexture(n),i}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this.subSurface.refractionTexture},set:function(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return this.subSurface.indexOfRefraction},set:function(e){this.subSurface.indexOfRefraction=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"invertRefractionY",{get:function(){return this.subSurface.invertRefractionY},set:function(e){this.subSurface.invertRefractionY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"linkRefractionWithTransparency",{get:function(){return this.subSurface.linkRefractionWithTransparency},set:function(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"usePhysicalLightFalloff",{get:function(){return this._lightFalloff===pn.LIGHTFALLOFF_PHYSICAL},set:function(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?pn.LIGHTFALLOFF_PHYSICAL:pn.LIGHTFALLOFF_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useGLTFLightFalloff",{get:function(){return this._lightFalloff===pn.LIGHTFALLOFF_GLTF},set:function(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?pn.LIGHTFALLOFF_GLTF:pn.LIGHTFALLOFF_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PBRMaterial"},t.prototype.clone=function(e){var n=this,i=L.a.Clone(function(){return new t(e,n.getScene())},this);return i.id=e,i.name=e,this.clearCoat.copyTo(i.clearCoat),this.anisotropy.copyTo(i.anisotropy),this.brdf.copyTo(i.brdf),this.sheen.copyTo(i.sheen),this.subSurface.copyTo(i.subSurface),i},t.prototype.serialize=function(){var e=L.a.Serialize(this);return e.customType="BABYLON.PBRMaterial",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},t.Parse=function(e,n,i){var o=L.a.Parse(function(){return new t(e.name,n)},e,n,i);return e.clearCoat&&o.clearCoat.parse(e.clearCoat,n,i),e.anisotropy&&o.anisotropy.parse(e.anisotropy,n,i),e.brdf&&o.brdf.parse(e.brdf,n,i),e.sheen&&o.sheen.parse(e.sheen,n,i),e.subSurface&&o.subSurface.parse(e.subSurface,n,i),o},t.PBRMATERIAL_OPAQUE=pn.PBRMATERIAL_OPAQUE,t.PBRMATERIAL_ALPHATEST=pn.PBRMATERIAL_ALPHATEST,t.PBRMATERIAL_ALPHABLEND=pn.PBRMATERIAL_ALPHABLEND,t.PBRMATERIAL_ALPHATESTANDBLEND=pn.PBRMATERIAL_ALPHATESTANDBLEND,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=pn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"directIntensity",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveIntensity",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentIntensity",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularIntensity",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"disableBumpMap",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureStrength",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallic",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicF0Factor",void 0),Object(c.c)([Object(L.e)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicReflectanceColor",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicReflectanceTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurfaceTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty",null)],t.prototype,"lightmapTexture",void 0),Object(c.c)([Object(L.e)("ambient"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientColor",void 0),Object(c.c)([Object(L.e)("albedo"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoColor",void 0),Object(c.c)([Object(L.e)("reflectivity"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityColor",void 0),Object(c.c)([Object(L.e)("reflection"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionColor",void 0),Object(c.c)([Object(L.e)("emissive"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveColor",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurface",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"useAlphaFromAlbedoTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"forceAlphaTest",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"alphaCutOff",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureGreen",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMetallnessFromMetallicTextureBlue",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientInGrayScale",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),Object(c.c)([Object(L.c)()],t.prototype,"usePhysicalLightFalloff",null),Object(c.c)([Object(L.c)()],t.prototype,"useGLTFLightFalloff",null),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOverAlpha",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"parallaxScaleBias",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceIrradianceInFragment",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAlphaFresnel",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLinearAlphaFresnel",void 0),Object(c.c)([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentBRDFTexture",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceNormalForward",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableSpecularAntiAliasing",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useHorizonOcclusion",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOcclusion",void 0),Object(c.c)([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsMiscDirty")],t.prototype,"unlit",void 0),t}(pn);R.a.RegisteredTypes["BABYLON.PBRMaterial"]=lo;function oa(r){return r.charCodeAt(0)+(r.charCodeAt(1)<<8)+(r.charCodeAt(2)<<16)+(r.charCodeAt(3)<<24)}var Au=oa("DXT1"),Pu=oa("DXT3"),Cu=oa("DXT5"),Gs=oa("DX10"),Ui=function(){function r(){}return r.GetDDSInfo=function(t){var e=new Int32Array(t.buffer,t.byteOffset,31),n=new Int32Array(t.buffer,t.byteOffset,35),i=1;131072&e[2]&&(i=Math.max(1,e[7]));var o=e[21],a=o===Gs?n[32]:0,s=h.a.TEXTURETYPE_UNSIGNED_INT;switch(o){case 113:s=h.a.TEXTURETYPE_HALF_FLOAT;break;case 116:s=h.a.TEXTURETYPE_FLOAT;break;case Gs:if(a===10){s=h.a.TEXTURETYPE_HALF_FLOAT;break}if(a===2){s=h.a.TEXTURETYPE_FLOAT;break}}return{width:e[4],height:e[3],mipmapCount:i,isFourCC:(4&e[20])==4,isRGB:(64&e[20])==64,isLuminance:(131072&e[20])==131072,isCube:(512&e[28])==512,isCompressed:o===Au||o===Pu||o===Cu,dxgiFormat:a,textureType:s}},r._ToHalfFloat=function(t){r._FloatView||(r._FloatView=new Float32Array(1),r._Int32View=new Int32Array(r._FloatView.buffer)),r._FloatView[0]=t;var e=r._Int32View[0],n=e>>16&32768,i=e>>12&2047,o=e>>23&255;return o<103?n:o>142?(n|=31744,n|=(o==255?0:1)&&8388607&e):o<113?n|=((i|=2048)>>114-o)+(i>>113-o&1):(n|=o-112<<10|i>>1,n+=1&i)},r._FromHalfFloat=function(t){var e=(32768&t)>>15,n=(31744&t)>>10,i=1023&t;return n===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):n==31?i?NaN:1/0*(e?-1:1):(e?-1:1)*Math.pow(2,n-15)*(1+i/Math.pow(2,10))},r._GetHalfFloatAsFloatRGBAArrayBuffer=function(t,e,n,i,o,a){for(var s=new Float32Array(i),d=new Uint16Array(o,n),p=0,y=0;y>8)},r._GetRGBArrayBuffer=function(t,e,n,i,o,a,s,d){for(var p=new Uint8Array(i),y=new Uint8Array(o,n),P=0,O=0;O>8&255,Te>>16&255,Te>>24&255)))}var Ee=r._ExtractLongWordOrder(se[23]),Se=r._ExtractLongWordOrder(se[24]),Le=r._ExtractLongWordOrder(se[25]),xe=r._ExtractLongWordOrder(se[26]);Oe&&(ue=t._getRGBABufferInternalSizedFormat(i.textureType)),z=1,131072&se[2]&&o!==!1&&(z=Math.max(1,se[7]));for(var Ne=d||0;Ne0?i.sphericalPolynomial=Xo.ConvertCubeMapToSphericalPolynomial({size:se[4],right:p[0],left:p[1],up:p[2],down:p[3],front:p[4],back:p[5],format:h.a.TEXTUREFORMAT_RGBA,type:h.a.TEXTURETYPE_FLOAT,gammaSpace:!1}):i.sphericalPolynomial=void 0}else l.a.Error("Compressed textures are not supported on this platform.");else l.a.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");else l.a.Error("Invalid magic number in DDS header")},r.StoreLODInAlphaChannel=!1,r}();Bt.a.prototype.createPrefilteredCubeTexture=function(r,t,e,n,i,o,a,s,d){var p=this;return i===void 0&&(i=null),o===void 0&&(o=null),s===void 0&&(s=null),d===void 0&&(d=!0),this.createCubeTexture(r,t,null,!1,function(y){if(y){var P=y.texture;if(d?y.info.sphericalPolynomial&&(P._sphericalPolynomial=y.info.sphericalPolynomial):P._sphericalPolynomial=new io,P._source=xt.b.CubePrefiltered,p.getCaps().textureLOD)i&&i(P);else{var O=p._gl,U=y.width;if(U){for(var F=[],z=0;z<3;z++){var J=1-z/2,ie=n,se=$.a.Log2(U)*e+n,ce=ie+(se-ie)*J,ue=Math.round(Math.min(Math.max(ce,0),se)),fe=new xt.a(p,xt.b.Temp);if(fe.type=P.type,fe.format=P.format,fe.width=Math.pow(2,Math.max($.a.Log2(U)-ue,0)),fe.height=fe.width,fe.isCube=!0,p._bindTextureDirectly(O.TEXTURE_CUBE_MAP,fe,!0),fe.samplingMode=h.a.TEXTURE_LINEAR_LINEAR,O.texParameteri(O.TEXTURE_CUBE_MAP,O.TEXTURE_MAG_FILTER,O.LINEAR),O.texParameteri(O.TEXTURE_CUBE_MAP,O.TEXTURE_MIN_FILTER,O.LINEAR),O.texParameteri(O.TEXTURE_CUBE_MAP,O.TEXTURE_WRAP_S,O.CLAMP_TO_EDGE),O.texParameteri(O.TEXTURE_CUBE_MAP,O.TEXTURE_WRAP_T,O.CLAMP_TO_EDGE),y.isDDS){var ve=y.info,Te=y.data;p._unpackFlipY(ve.isCompressed),Ui.UploadDDSLevels(p,fe,Te,ve,!0,6,ue)}else l.a.Warn("DDS is the only prefiltered cube map supported so far.");p._bindTextureDirectly(O.TEXTURE_CUBE_MAP,null);var Oe=new zn.a(t);Oe.isCube=!0,Oe._texture=fe,fe.isReady=!0,F.push(Oe)}P._lodTextureHigh=F[2],P._lodTextureMid=F[1],P._lodTextureLow=F[0],i&&i(P)}}}else i&&i(null)},o,a,s,d,e,n)};var xu=function(){function r(){this.supportCascades=!0}return r.prototype.canLoad=function(t){return Xn.a.EndsWith(t,".dds")},r.prototype.loadCubeData=function(t,e,n,i,o){var a,s=e.getEngine(),d=!1;if(Array.isArray(t))for(var p=0;p1)&&e.generateMipMaps,s._unpackFlipY(a.isCompressed),Ui.UploadDDSLevels(s,e,y,a,d,6,-1,p),a.isFourCC||a.mipmapCount!==1||s.generateMipMapsForCubemap(e)}else{var P=t;a=Ui.GetDDSInfo(P),e.width=a.width,e.height=a.height,n&&(a.sphericalPolynomial=new io),d=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&e.generateMipMaps,s._unpackFlipY(a.isCompressed),Ui.UploadDDSLevels(s,e,P,a,d,6),a.isFourCC||a.mipmapCount!==1||s.generateMipMapsForCubemap(e,!1)}s._setCubeMapTextureParams(e,d),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),i&&i({isDDS:!0,width:e.width,info:a,data:t,texture:e})},r.prototype.loadData=function(t,e,n){var i=Ui.GetDDSInfo(t),o=(i.isRGB||i.isLuminance||i.mipmapCount>1)&&e.generateMipMaps&&i.width>>i.mipmapCount-1==1;n(i.width,i.height,o,i.isFourCC,function(){Ui.UploadDDSLevels(e.getEngine(),e,t,i,o,1)})},r}();Ue.a._TextureLoaders.push(new xu);var Ru=function(){function r(){this.supportCascades=!1}return r.prototype.canLoad=function(t){return Xn.a.EndsWith(t,".env")},r.prototype.loadCubeData=function(t,e,n,i,o){if(!Array.isArray(t)){var a=Si.GetEnvInfo(t);a?(e.width=a.width,e.height=a.width,Si.UploadEnvSpherical(e,a),Si.UploadEnvLevelsAsync(e,t,a).then(function(){e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),i&&i()})):o&&o("Can not parse the environment file",null)}},r.prototype.loadData=function(t,e,n){throw".env not supported in 2d."},r}();Ue.a._TextureLoaders.push(new Ru);var aa=function(){function r(t,e,n,i){if(this.data=t,this.isInvalid=!1,!r.IsValid(t))return this.isInvalid=!0,void l.a.Error("texture missing KTX identifier");var o=Uint32Array.BYTES_PER_ELEMENT,a=new DataView(this.data.buffer,this.data.byteOffset+12,13*o),s=a.getUint32(0,!0)===67305985;this.glType=a.getUint32(1*o,s),this.glTypeSize=a.getUint32(2*o,s),this.glFormat=a.getUint32(3*o,s),this.glInternalFormat=a.getUint32(4*o,s),this.glBaseInternalFormat=a.getUint32(5*o,s),this.pixelWidth=a.getUint32(6*o,s),this.pixelHeight=a.getUint32(7*o,s),this.pixelDepth=a.getUint32(8*o,s),this.numberOfArrayElements=a.getUint32(9*o,s),this.numberOfFaces=a.getUint32(10*o,s),this.numberOfMipmapLevels=a.getUint32(11*o,s),this.bytesOfKeyValueData=a.getUint32(12*o,s),this.glType===0?(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),this.pixelHeight!==0&&this.pixelDepth===0?this.numberOfArrayElements===0?this.numberOfFaces===e?this.loadType=r.COMPRESSED_2D:l.a.Error("number of faces expected"+e+", but found "+this.numberOfFaces):l.a.Error("texture arrays not currently supported"):l.a.Error("only 2D textures currently supported")):l.a.Error("only compressed formats currently supported")}return r.prototype.uploadLevels=function(t,e){switch(this.loadType){case r.COMPRESSED_2D:this._upload2DCompressedLevels(t,e);break;case r.TEX_2D:case r.COMPRESSED_3D:case r.TEX_3D:}},r.prototype._upload2DCompressedLevels=function(t,e){for(var n=r.HEADER_LEN+this.bytesOfKeyValueData,i=this.pixelWidth,o=this.pixelHeight,a=e?this.numberOfMipmapLevels:1,s=0;s=12){var e=new Uint8Array(t.buffer,t.byteOffset,12);if(e[0]===171&&e[1]===75&&e[2]===84&&e[3]===88&&e[4]===32&&e[5]===49&&e[6]===49&&e[7]===187&&e[8]===13&&e[9]===10&&e[10]===26&&e[11]===10)return!0}return!1},r.HEADER_LEN=64,r.COMPRESSED_2D=0,r.COMPRESSED_3D=1,r.TEX_2D=2,r.TEX_3D=3,r}(),zs=function(){function r(t){this._pendingActions=new Array,this._workerInfos=t.map(function(e){return{worker:e,active:!1}})}return r.prototype.dispose=function(){for(var t=0,e=this._workerInfos;t1,e.isReady=!0,this._engine._bindTextureDirectly(this._engine._gl.TEXTURE_2D,null)},r.IsValid=function(t){if(t.byteLength>=12){var e=new Uint8Array(t.buffer,t.byteOffset,12);if(e[0]===171&&e[1]===75&&e[2]===84&&e[3]===88&&e[4]===32&&e[5]===50&&e[6]===48&&e[7]===187&&e[8]===13&&e[9]===10&&e[10]===26&&e[11]===10)return!0}return!1},r.URLConfig={jsDecoderModule:"https://preview.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,jsMSCTranscoder:null,wasmMSCTranscoder:null},r.DefaultNumWorkers=r.GetDefaultNumWorkers(),r}();function N_(){var r;onmessage=function(t){switch(t.data.action){case"init":var e=t.data.urls;importScripts(e.jsDecoderModule),e.wasmUASTCToASTC!==null&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7!==null&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB!==null&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.jsMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder!==null&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),r=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break;case"decode":r.decode(t.data.data,t.data.caps,t.data.options).then(function(n){for(var i=[],o=0;o1&&e.generateMipMaps;a._unpackFlipY(!0),s.uploadLevels(e,e.generateMipMaps),e.width=s.pixelWidth,e.height=s.pixelHeight,a._setCubeMapTextureParams(e,d),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),i&&i()}},r.prototype.loadData=function(t,e,n,i){if(aa.IsValid(t)){e._invertVScale=!e.invertY;var o=new aa(t,1);n(o.pixelWidth,o.pixelHeight,e.generateMipMaps,!0,function(){o.uploadLevels(e,e.generateMipMaps)},o.isInvalid)}else js.IsValid(t)?new js(e.getEngine()).uploadAsync(t,e,i).then(function(){n(e.width,e.height,e.generateMipMaps,!0,function(){},!1)},function(a){l.a.Warn("Failed to load KTX2 texture data: "+a.message),n(0,0,!1,!1,function(){},!0)}):(l.a.Error("texture missing KTX identifier"),n(0,0,!1,!1,function(){},!0))},r}();Ue.a._TextureLoaders.unshift(new Ou);var Mu=function(r){function t(e,n,i){var o=r.call(this,e,u.e.Zero(),n)||this;return o._xrSessionManager=i,o._firstFrame=!1,o._referenceQuaternion=u.b.Identity(),o._referencedPosition=new u.e,o._xrInvPositionCache=new u.e,o._xrInvQuaternionCache=u.b.Identity(),o._trackingState=er.NOT_TRACKING,o.onBeforeCameraTeleport=new x.c,o.onAfterCameraTeleport=new x.c,o.onTrackingStateChanged=new x.c,o.compensateOnFirstFrame=!0,o._rotate180=new u.b(0,1,0,0),o.minZ=.1,o.rotationQuaternion=new u.b,o.cameraRigMode=gt.a.RIG_MODE_CUSTOM,o.updateUpVectorFromRotation=!0,o._updateNumberOfRigCameras(1),o.freezeProjectionMatrix(),o._xrSessionManager.onXRSessionInit.add(function(){o._referencedPosition.copyFromFloats(0,0,0),o._referenceQuaternion.copyFromFloats(0,0,0,1),o._firstFrame=o.compensateOnFirstFrame}),o._xrSessionManager.onXRFrameObservable.add(function(a){o._firstFrame&&o._updateFromXRSession(),o._updateReferenceSpace(),o._updateFromXRSession()},void 0,!0),o}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"trackingState",{get:function(){return this._trackingState},enumerable:!1,configurable:!0}),t.prototype._setTrackingState=function(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))},Object.defineProperty(t.prototype,"realWorldHeight",{get:function(){var e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0},enumerable:!1,configurable:!0}),t.prototype._updateForDualEyeDebugging=function(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Wn.a(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Wn.a(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null},t.prototype.setTransformationFromNonVRCamera=function(e,n){e===void 0&&(e=this.getScene().activeCamera),n===void 0&&(n=!0),e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,u.b.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,n&&this._xrSessionManager.resetReferenceSpace())},t.prototype.getClassName=function(){return"WebXRCamera"},t.prototype._updateFromXRSession=function(){var e=this,n=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(n){var i=n.emulatedPosition?er.TRACKING_LOST:er.TRACKING;if(this._setTrackingState(i),n.transform){var o=n.transform.position;this._referencedPosition.set(o.x,o.y,o.z);var a=n.transform.orientation;this._referenceQuaternion.set(a.x,a.y,a.z,a.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!==n.views.length&&this._updateNumberOfRigCameras(n.views.length),n.views.forEach(function(s,d){var p=e.rigCameras[d];p.isLeftCamera||p.isRightCamera||(s.eye==="right"?p._isRightCamera=!0:s.eye==="left"&&(p._isLeftCamera=!0));var y=s.transform.position,P=s.transform.orientation;if(p.position.set(y.x,y.y,y.z),p.rotationQuaternion.set(P.x,P.y,P.z,P.w),e._scene.useRightHandedSystem?p.rotationQuaternion.multiplyInPlace(e._rotate180):(p.position.z*=-1,p.rotationQuaternion.z*=-1,p.rotationQuaternion.w*=-1),u.a.FromFloat32ArrayToRefScaled(s.projectionMatrix,0,1,p._projectionMatrix),e._scene.useRightHandedSystem||p._projectionMatrix.toggleProjectionMatrixHandInPlace(),d===0&&e._projectionMatrix.copyFrom(p._projectionMatrix),e._xrSessionManager.session.renderState.baseLayer){var O=e._xrSessionManager.session.renderState.baseLayer.getViewport(s),U=e._xrSessionManager.session.renderState.baseLayer.framebufferWidth,F=e._xrSessionManager.session.renderState.baseLayer.framebufferHeight;p.viewport.width=O.width/U,p.viewport.height=O.height/F,p.viewport.x=O.x/U,p.viewport.y=O.y/F}p.outputRenderTarget=e._xrSessionManager.getRenderTargetTextureForEye(s.eye)})}else this._setTrackingState(er.NOT_TRACKING)},t.prototype._updateNumberOfRigCameras=function(e){for(e===void 0&&(e=1);this.rigCameras.lengthe;){var i=this.rigCameras.pop();i&&i.dispose()}},t.prototype._updateReferenceSpace=function(){this.position.equals(this._referencedPosition)&&this.rotationQuaternion.equals(this._referenceQuaternion)||(this.position.subtractToRef(this._referencedPosition,this._referencedPosition),this._referenceQuaternion.conjugateInPlace(),this._referenceQuaternion.multiplyToRef(this.rotationQuaternion,this._referenceQuaternion),this._updateReferenceSpaceOffset(this._referencedPosition,this._referenceQuaternion.normalize()))},t.prototype._updateReferenceSpaceOffset=function(e,n,i){if(i===void 0&&(i=!1),this._xrSessionManager.referenceSpace&&this._xrSessionManager.currentFrame){this._xrInvPositionCache.copyFrom(e),n?this._xrInvQuaternionCache.copyFrom(n):this._xrInvQuaternionCache.copyFromFloats(0,0,0,1),this._scene.useRightHandedSystem||(this._xrInvPositionCache.z*=-1,this._xrInvQuaternionCache.z*=-1,this._xrInvQuaternionCache.w*=-1),this._xrInvPositionCache.negateInPlace(),this._xrInvQuaternionCache.conjugateInPlace(),this._xrInvPositionCache.rotateByQuaternionToRef(this._xrInvQuaternionCache,this._xrInvPositionCache),i&&(this._xrInvPositionCache.y=0);var o=new XRRigidTransform({x:this._xrInvPositionCache.x,y:this._xrInvPositionCache.y,z:this._xrInvPositionCache.z},{x:this._xrInvQuaternionCache.x,y:this._xrInvQuaternionCache.y,z:this._xrInvQuaternionCache.z,w:this._xrInvQuaternionCache.w}),a=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(o),s=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(a);if(s){var d=new u.e(s.transform.position.x,s.transform.position.y,s.transform.position.z);this._scene.useRightHandedSystem||(d.z*=-1),this.position.subtractToRef(d,d),this._scene.useRightHandedSystem||(d.z*=-1),d.negateInPlace();var p=new XRRigidTransform({x:d.x,y:d.y,z:d.z});this._xrSessionManager.referenceSpace=a.getOffsetReferenceSpace(p)}}},t}(Hn),ii=function(){function r(){}return r.ANCHOR_SYSTEM="xr-anchor-system",r.BACKGROUND_REMOVER="xr-background-remover",r.HIT_TEST="xr-hit-test",r.PHYSICS_CONTROLLERS="xr-physics-controller",r.PLANE_DETECTION="xr-plane-detection",r.POINTER_SELECTION="xr-controller-pointer-selection",r.TELEPORTATION="xr-controller-teleportation",r.FEATURE_POINTS="xr-feature-points",r.HAND_TRACKING="xr-hand-tracking",r}(),Yn=function(){function r(t){var e=this;this._xrSessionManager=t,this._features={},this._xrSessionManager.onXRSessionInit.add(function(){e.getEnabledFeatures().forEach(function(n){var i=e._features[n];!i.enabled||i.featureImplementation.attached||i.featureImplementation.disableAutoAttach||e.attachFeature(n)})}),this._xrSessionManager.onXRSessionEnded.add(function(){e.getEnabledFeatures().forEach(function(n){var i=e._features[n];i.enabled&&i.featureImplementation.attached&&e.detachFeature(n)})})}return r.AddWebXRFeature=function(t,e,n,i){n===void 0&&(n=1),i===void 0&&(i=!1),this._AvailableFeatures[t]=this._AvailableFeatures[t]||{latest:n},n>this._AvailableFeatures[t].latest&&(this._AvailableFeatures[t].latest=n),i&&(this._AvailableFeatures[t].stable=n),this._AvailableFeatures[t][n]=e},r.ConstructFeature=function(t,e,n,i){e===void 0&&(e=1);var o=this._AvailableFeatures[t][e];if(!o)throw new Error("feature not found");return o(n,i)},r.GetAvailableFeatures=function(){return Object.keys(this._AvailableFeatures)},r.GetAvailableVersions=function(t){return Object.keys(this._AvailableFeatures[t])},r.GetLatestVersionOfFeature=function(t){return this._AvailableFeatures[t]&&this._AvailableFeatures[t].latest||-1},r.GetStableVersionOfFeature=function(t){return this._AvailableFeatures[t]&&this._AvailableFeatures[t].stable||-1},r.prototype.attachFeature=function(t){var e=this._features[t];e&&e.enabled&&!e.featureImplementation.attached&&e.featureImplementation.attach()},r.prototype.detachFeature=function(t){var e=this._features[t];e&&e.featureImplementation.attached&&e.featureImplementation.detach()},r.prototype.disableFeature=function(t){var e=typeof t=="string"?t:t.Name,n=this._features[e];return!(!n||!n.enabled)&&(n.enabled=!1,this.detachFeature(e),n.featureImplementation.dispose(),!0)},r.prototype.dispose=function(){var t=this;this.getEnabledFeatures().forEach(function(e){t.disableFeature(e),t._features[e].featureImplementation.dispose()})},r.prototype.enableFeature=function(t,e,n,i,o){var a=this;e===void 0&&(e="latest"),n===void 0&&(n={}),i===void 0&&(i=!0),o===void 0&&(o=!0);var s=typeof t=="string"?t:t.Name,d=0;if(typeof e=="string"){if(!e)throw new Error("Error in provided version - "+s+" ("+e+")");if((d=e==="stable"?r.GetStableVersionOfFeature(s):e==="latest"?r.GetLatestVersionOfFeature(s):+e)===-1||isNaN(d))throw new Error("feature not found - "+s+" ("+e+")")}else d=e;var p=this._features[s],y=r.ConstructFeature(s,d,this._xrSessionManager,n);if(!y)throw new Error("feature not found - "+s);p&&this.disableFeature(s);var P=y();if(P.dependsOn&&!P.dependsOn.every(function(O){return!!a._features[O]}))throw new Error("Dependant features missing. Make sure the following features are enabled - "+P.dependsOn.join(", "));if(P.isCompatible())return this._features[s]={featureImplementation:P,enabled:!0,version:d,required:o},i?this._xrSessionManager.session&&!this._features[s].featureImplementation.attached&&this.attachFeature(s):this._features[s].featureImplementation.disableAutoAttach=!0,this._features[s].featureImplementation;if(o)throw new Error("required feature not compatible");return Ye.b.Warn("Feature "+s+" not compatible with the current environment/browser and was not enabled."),P},r.prototype.getEnabledFeature=function(t){return this._features[t]&&this._features[t].featureImplementation},r.prototype.getEnabledFeatures=function(){return Object.keys(this._features)},r.prototype.extendXRSessionInitObject=function(t){var e=this;return this.getEnabledFeatures().forEach(function(n){var i=e._features[n],o=i.featureImplementation.xrNativeFeatureName;o&&(i.required?(t.requiredFeatures=t.requiredFeatures||[],t.requiredFeatures.indexOf(o)===-1&&t.requiredFeatures.push(o)):(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.indexOf(o)===-1&&t.optionalFeatures.push(o)))}),t},r._AvailableFeatures={},r}(),Iu=function(){function r(t){var e=this;this.scene=t,this._nonVRCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this.onInitialXRPoseSetObservable=new x.c,this.onStateChangedObservable=new x.c,this.state=fn.NOT_IN_XR,this.sessionManager=new ys(t),this.camera=new Mu("",t,this.sessionManager),this.featuresManager=new Yn(this.sessionManager),t.onDisposeObservable.add(function(){e.exitXRAsync()})}return r.CreateAsync=function(t){var e=new r(t);return e.sessionManager.initializeAsync().then(function(){return e._supported=!0,e}).catch(function(n){throw e._setState(fn.NOT_IN_XR),e.dispose(),n})},r.prototype.dispose=function(){this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._nonVRCamera&&(this.scene.activeCamera=this._nonVRCamera)},r.prototype.enterXRAsync=function(t,e,n,i){var o=this;if(n===void 0&&(n=this.sessionManager.getWebXRRenderTarget()),i===void 0&&(i={}),!this._supported)throw"WebXR not supported in this browser or environment";return this._setState(fn.ENTERING_XR),e!=="viewer"&&e!=="local"&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.push(e)),this.featuresManager.extendXRSessionInitObject(i),t==="immersive-ar"&&e!=="unbounded"&&l.a.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"),this.sessionManager.initializeSessionAsync(t,i).then(function(){return o.sessionManager.setReferenceSpaceTypeAsync(e)}).then(function(){return n.initializeXRLayerAsync(o.sessionManager.session)}).then(function(){return o.sessionManager.updateRenderStateAsync({depthFar:o.camera.maxZ,depthNear:o.camera.minZ,baseLayer:n.xrLayer})}).then(function(){return o.sessionManager.runXRRenderLoop(),o._originalSceneAutoClear=o.scene.autoClear,o._nonVRCamera=o.scene.activeCamera,o.scene.activeCamera=o.camera,t!=="immersive-ar"?o._nonXRToXRCamera():(o.scene.autoClear=!1,o.camera.compensateOnFirstFrame=!1),o.sessionManager.onXRSessionEnded.addOnce(function(){o.camera.rigCameras.forEach(function(a){a.outputRenderTarget=null}),o.scene.autoClear=o._originalSceneAutoClear,o.scene.activeCamera=o._nonVRCamera,t!=="immersive-ar"&&o.camera.compensateOnFirstFrame&&(o._nonVRCamera.setPosition?o._nonVRCamera.setPosition(o.camera.position):o._nonVRCamera.position.copyFrom(o.camera.position)),o._setState(fn.NOT_IN_XR)}),o.sessionManager.onXRFrameObservable.addOnce(function(){o._setState(fn.IN_XR)}),o.sessionManager}).catch(function(a){throw console.log(a),console.log(a.message),o._setState(fn.NOT_IN_XR),a})},r.prototype.exitXRAsync=function(){return this.state!==fn.IN_XR?Promise.resolve():(this._setState(fn.EXITING_XR),this.sessionManager.exitXRAsync())},r.prototype._nonXRToXRCamera=function(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)},r.prototype._setState=function(t){this.state!==t&&(this.state=t,this.onStateChangedObservable.notifyObservers(this.state))},r}(),Cr=function(){function r(t,e,n,i){n===void 0&&(n=-1),i===void 0&&(i=[]),this.id=t,this.type=e,this._buttonIndex=n,this._axesIndices=i,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new x.c,this.onButtonStateChangedObservable=new x.c}return Object.defineProperty(r.prototype,"axes",{get:function(){return this._axes},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"changes",{get:function(){return this._changes},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"hasChanges",{get:function(){return this._hasChanges},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"pressed",{get:function(){return this._pressed},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"touched",{get:function(){return this._touched},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"value",{get:function(){return this._currentValue},enumerable:!1,configurable:!0}),r.prototype.dispose=function(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()},r.prototype.isAxes=function(){return this._axesIndices.length!==0},r.prototype.isButton=function(){return this._buttonIndex!==-1},r.prototype.update=function(t){var e=!1,n=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){var i=t.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},e=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},e=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},e=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==t.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:t.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=t.axes[this._axesIndices[0]],n=!0),this._axes.y!==t.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=t.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:t.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=t.axes[this._axesIndices[1]],n=!0)),e&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),n&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))},r.BUTTON_TYPE="button",r.SQUEEZE_TYPE="squeeze",r.THUMBSTICK_TYPE="thumbstick",r.TOUCHPAD_TYPE="touchpad",r.TRIGGER_TYPE="trigger",r}(),xr=function(){function r(t,e,n,i,o){var a=this;this.scene=t,this.layout=e,this.gamepadObject=n,this.handedness=i,this._initComponent=function(s){if(s){var d=a.layout.components[s],p=d.type,y=d.gamepadIndices.button,P=[];d.gamepadIndices.xAxis!==void 0&&d.gamepadIndices.yAxis!==void 0&&P.push(d.gamepadIndices.xAxis,d.gamepadIndices.yAxis),a.components[s]=new Cr(s,p,y,P)}},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new x.c,e.components&&Object.keys(e.components).forEach(this._initComponent)}return r.prototype.dispose=function(){var t=this;this.getComponentIds().forEach(function(e){return t.getComponent(e).dispose()}),this.rootMesh&&this.rootMesh.dispose()},r.prototype.getAllComponentsOfType=function(t){var e=this;return this.getComponentIds().map(function(n){return e.components[n]}).filter(function(n){return n.type===t})},r.prototype.getComponent=function(t){return this.components[t]},r.prototype.getComponentIds=function(){return Object.keys(this.components)},r.prototype.getComponentOfType=function(t){return this.getAllComponentsOfType(t)[0]||null},r.prototype.getMainComponent=function(){return this.getComponent(this.layout.selectComponentId)},r.prototype.loadModel=function(){return Object(c.b)(this,void 0,void 0,function(){var t,e,n=this;return Object(c.e)(this,function(i){return t=!this._getModelLoadingConstraints(),e=this._getGenericFilenameAndPath(),t?l.a.Warn("Falling back to generic models"):e=this._getFilenameAndPath(),[2,new Promise(function(o,a){Ut.ImportMesh("",e.path,e.filename,n.scene,function(s){t?n._getGenericParentMesh(s):n._setRootMesh(s),n._processLoadedModel(s),n._modelReady=!0,n.onModelLoadedObservable.notifyObservers(n),o(!0)},null,function(s,d){l.a.Log(d),l.a.Warn("Failed to retrieve controller model of type "+n.profileId+" from the remote server: "+e.path+e.filename),a(d)})})]})})},r.prototype.updateFromXRFrame=function(t){var e=this;this.getComponentIds().forEach(function(n){return e.getComponent(n).update(e.gamepadObject)}),this.updateModel(t)},Object.defineProperty(r.prototype,"handness",{get:function(){return this.handedness},enumerable:!1,configurable:!0}),r.prototype.pulse=function(t,e,n){return n===void 0&&(n=0),this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[n]?this.gamepadObject.hapticActuators[n].pulse(t,e):Promise.resolve(!1)},r.prototype._getChildByName=function(t,e){return t.getChildren(function(n){return n.name===e},!1)[0]},r.prototype._getImmediateChildByName=function(t,e){return t.getChildren(function(n){return n.name==e},!0)[0]},r.prototype._lerpTransform=function(t,e,n){if(t.minMesh&&t.maxMesh&&t.valueMesh&&t.minMesh.rotationQuaternion&&t.maxMesh.rotationQuaternion&&t.valueMesh.rotationQuaternion){var i=n?.5*e+.5:e;u.b.SlerpToRef(t.minMesh.rotationQuaternion,t.maxMesh.rotationQuaternion,i,t.valueMesh.rotationQuaternion),u.e.LerpToRef(t.minMesh.position,t.maxMesh.position,i,t.valueMesh.position)}},r.prototype.updateModel=function(t){this._modelReady&&this._updateModel(t)},r.prototype._getGenericFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},r.prototype._getGenericParentMesh=function(t){var e=this;this.rootMesh=new De.a(this.profileId+" "+this.handedness,this.scene),t.forEach(function(n){n.parent||(n.isPickable=!1,n.setParent(e.rootMesh))}),this.rootMesh.rotationQuaternion=u.b.FromEulerAngles(0,Math.PI,0)},r}(),Hs=function(r){function t(e,n,i){var o=r.call(this,e,w_[i],n,i)||this;return o.profileId=t.ProfileId,o}return Object(c.d)(t,r),t.prototype._getFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){},t.prototype._setRootMesh=function(e){var n=this;this.rootMesh=new De.a(this.profileId+" "+this.handedness,this.scene),e.forEach(function(i){i.isPickable=!1,i.parent||i.setParent(n.rootMesh)}),this.rootMesh.rotationQuaternion=u.b.FromEulerAngles(0,Math.PI,0)},t.prototype._updateModel=function(){},t.ProfileId="generic-trigger",t}(xr),w_={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"}},Du=function(r){function t(e,n,i,o){var a=r.call(this,e,i.layouts[n.handedness||"none"],n.gamepad,n.handedness)||this;return a._repositoryUrl=o,a._buttonMeshMapping={},a._touchDots={},a.profileId=i.profileId,a}return Object(c.d)(t,r),t.prototype.dispose=function(){var e=this;r.prototype.dispose.call(this),Object.keys(this._touchDots).forEach(function(n){e._touchDots[n].dispose()})},t.prototype._getFilenameAndPath=function(){return{filename:this.layout.assetPath,path:this._repositoryUrl+"/profiles/"+this.profileId+"/"}},t.prototype._getModelLoadingConstraints=function(){var e=Ut.IsPluginForExtensionAvailable(".glb");return e||l.a.Warn("glTF / glb loaded was not registered, using generic controller instead"),e},t.prototype._processLoadedModel=function(e){var n=this;this.getComponentIds().forEach(function(i){var o=n.layout.components[i];n._buttonMeshMapping[i]={mainMesh:n._getChildByName(n.rootMesh,o.rootNodeName),states:{}},Object.keys(o.visualResponses).forEach(function(a){var s=o.visualResponses[a];if(s.valueNodeProperty==="transform")n._buttonMeshMapping[i].states[a]={valueMesh:n._getChildByName(n.rootMesh,s.valueNodeName),minMesh:n._getChildByName(n.rootMesh,s.minNodeName),maxMesh:n._getChildByName(n.rootMesh,s.maxNodeName)};else{var d=o.type===Cr.TOUCHPAD_TYPE&&o.touchPointNodeName?o.touchPointNodeName:s.valueNodeName;if(n._buttonMeshMapping[i].states[a]={valueMesh:n._getChildByName(n.rootMesh,d)},o.type===Cr.TOUCHPAD_TYPE&&!n._touchDots[a]){var p=Nn.a.CreateSphere(a+"dot",{diameter:.0015,segments:8},n.scene);p.material=new Ft.a(a+"mat",n.scene),p.material.diffuseColor=M.a.Red(),p.parent=n._buttonMeshMapping[i].states[a].valueMesh||null,p.isVisible=!1,n._touchDots[a]=p}}})})},t.prototype._setRootMesh=function(e){var n;this.rootMesh=new De.a(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(var i=0;io/10&&(d.isVisible=!0),(p+=n._scene.getEngine().getDeltaTime())>=o)n._scene.simulatePointerDown(i.pick,{pointerId:i.id}),y=!0,n._options.disablePointerUpOnTouchOut&&n._scene.simulatePointerUp(i.pick,{pointerId:i.id}),d.isVisible=!1;else{var P=1-p/o;d.scaling.set(P,P,P)}else y=!1,p=0;n._scene.simulatePointerMove(i.pick,{pointerId:i.id}),s=i.pick}}),this._options.renderingGroupId!==void 0&&(d.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(function(){i.pick&&!n._options.disablePointerUpOnTouchOut&&y&&n._scene.simulatePointerUp(i.pick,{pointerId:i.id}),d.dispose()})},t.prototype._attachScreenRayMode=function(e){var n=this,i=this._controllers[e.uniqueId],o=!1;i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){!i.pick||n._options.disablePointerUpOnTouchOut&&o||(o?n._scene.simulatePointerMove(i.pick,{pointerId:i.id}):(n._scene.simulatePointerDown(i.pick,{pointerId:i.id}),o=!0,n._options.disablePointerUpOnTouchOut&&n._scene.simulatePointerUp(i.pick,{pointerId:i.id})))}),e.onDisposeObservable.addOnce(function(){i.pick&&o&&!n._options.disablePointerUpOnTouchOut&&n._scene.simulatePointerUp(i.pick,{pointerId:i.id})})},t.prototype._attachTrackedPointerRayMode=function(e){var n=this,i=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);if(i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(function(){i.laserPointer.material.disableLighting=n.disablePointerLighting,i.selectionMesh.material.disableLighting=n.disableSelectionMeshLighting,i.pick&&n._scene.simulatePointerMove(i.pick,{pointerId:i.id})}),e.inputSource.gamepad){var o=function(d){n._options.overrideButtonId&&(i.selectionComponent=d.getComponent(n._options.overrideButtonId)),i.selectionComponent||(i.selectionComponent=d.getMainComponent()),i.onButtonChangedObserver=i.selectionComponent.onButtonStateChangedObservable.add(function(p){if(p.changes.pressed){var y=p.changes.pressed.current;i.pick?(n._options.enablePointerSelectionOnAllControllers||e.uniqueId===n._attachedController)&&(y?(n._scene.simulatePointerDown(i.pick,{pointerId:i.id}),i.selectionMesh.material.emissiveColor=n.selectionMeshPickedColor,i.laserPointer.material.emissiveColor=n.laserPointerPickedColor):(n._scene.simulatePointerUp(i.pick,{pointerId:i.id}),i.selectionMesh.material.emissiveColor=n.selectionMeshDefaultColor,i.laserPointer.material.emissiveColor=n.laserPointerDefaultColor)):!y||n._options.enablePointerSelectionOnAllControllers||n._options.disableSwitchOnClick||(n._attachedController=e.uniqueId)}})};e.motionController?o(e.motionController):e.onMotionControllerInitObservable.add(o)}else{var a=function(d){i.xrController&&d.inputSource===i.xrController.inputSource&&i.pick&&(n._scene.simulatePointerDown(i.pick,{pointerId:i.id}),i.selectionMesh.material.emissiveColor=n.selectionMeshPickedColor,i.laserPointer.material.emissiveColor=n.laserPointerPickedColor)},s=function(d){i.xrController&&d.inputSource===i.xrController.inputSource&&i.pick&&(n._scene.simulatePointerUp(i.pick,{pointerId:i.id}),i.selectionMesh.material.emissiveColor=n.selectionMeshDefaultColor,i.laserPointer.material.emissiveColor=n.laserPointerDefaultColor)};i.eventListeners={selectend:s,selectstart:a},this._xrSessionManager.session.addEventListener("selectstart",a),this._xrSessionManager.session.addEventListener("selectend",s)}},t.prototype._convertNormalToDirectionOfRay=function(e,n){return e&&Math.acos(u.e.Dot(e,n.direction))o},t.prototype._updatePointerDistance=function(e,n){n===void 0&&(n=100),e.scaling.y=n,this._scene.useRightHandedSystem&&(n*=-1),e.position.z=n/2+.05},Object.defineProperty(t.prototype,"lasterPointerDefaultColor",{get:function(){return this.laserPointerDefaultColor},enumerable:!1,configurable:!0}),t._idCounter=200,t.Name=ii.POINTER_SELECTION,t.Version=1,t}(ri);Yn.AddWebXRFeature(uo.Name,function(r,t){return function(){return new uo(r,t)}},uo.Version,!0);var Vi,wu=function(){function r(t,e,n){this.element=t,this.sessionMode=e,this.referenceSpaceType=n}return r.prototype.update=function(t){},r}(),B_=function(){},Fu=function(){function r(t,e){var n=this;if(this.scene=t,this.options=e,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new x.c,this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;",typeof window<"u"&&window.location&&window.location.protocol==="http:"&&Ye.b.Warn("WebXR can only be served over HTTPS"),e.customButtons)this._buttons=e.customButtons;else{var i=e.sessionMode||"immersive-vr",o=e.referenceSpaceType||"local-floor",a=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(typeof SVGSVGElement>"u"?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";a+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';var s=document.createElement("style");s.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(s);var d=document.createElement("button");d.className="babylonVRicon",d.title=i+" - "+o,this._buttons.push(new wu(d,i,o)),this._buttons[this._buttons.length-1].update=function(y){this.element.style.display=y===null||y===this?"":"none",d.className="babylonVRicon"+(y===this?" vrdisplaypresenting":"")},this._updateButtons(null)}var p=t.getEngine().getInputElement();p&&p.parentNode&&(p.parentNode.appendChild(this.overlay),t.onDisposeObservable.addOnce(function(){n.dispose()}))}return r.CreateAsync=function(t,e,n){var i=this,o=new r(t,n),a=o._buttons.map(function(s){return e.sessionManager.isSessionSupportedAsync(s.sessionMode)});return e.onStateChangedObservable.add(function(s){s==fn.NOT_IN_XR&&o._updateButtons(null)}),Promise.all(a).then(function(s){return s.forEach(function(d,p){d?(o.overlay.appendChild(o._buttons[p].element),o._buttons[p].element.onclick=function(){return Object(c.b)(i,void 0,void 0,function(){var y,P,O;return Object(c.e)(this,function(U){switch(U.label){case 0:return e.state!=fn.IN_XR?[3,2]:[4,e.exitXRAsync()];case 1:return U.sent(),o._updateButtons(null),[3,6];case 2:if(e.state!=fn.NOT_IN_XR)return[3,6];if(!n.renderTarget)return[3,6];U.label=3;case 3:return U.trys.push([3,5,,6]),[4,e.enterXRAsync(o._buttons[p].sessionMode,o._buttons[p].referenceSpaceType,n.renderTarget,{optionalFeatures:n.optionalFeatures,requiredFeatures:n.requiredFeatures})];case 4:return U.sent(),o._updateButtons(o._buttons[p]),[3,6];case 5:return y=U.sent(),o._updateButtons(null),P=o._buttons[p].element,O=P.title,P.title="Error entering XR session : "+O,P.classList.add("xr-error"),n.onError&&n.onError(y),[3,6];case 6:return[2]}})})}):Ye.b.Warn('Session mode "'+o._buttons[p].sessionMode+'" not supported in browser')}),o})},r.prototype.dispose=function(){var t=this.scene.getEngine().getInputElement();t&&t.parentNode&&t.parentNode.contains(this.overlay)&&t.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear()},r.prototype._updateButtons=function(t){var e=this;this._activeButton=t,this._buttons.forEach(function(n){n.update(e._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)},r}();function Ws(r){var t,e=0,n=Date.now();r.observableParameters=(t=r.observableParameters)!==null&&t!==void 0?t:{};var i=r.contextObservable.add(function(o){var a=Date.now(),s={startTime:n,currentTime:a,deltaTime:e=a-n,completeRate:e/r.timeout,payload:o};r.onTick&&r.onTick(s),r.breakCondition&&r.breakCondition()&&(r.contextObservable.remove(i),r.onAborted&&r.onAborted(s)),e>=r.timeout&&(r.contextObservable.remove(i),r.onEnded&&r.onEnded(s))},r.observableParameters.mask,r.observableParameters.insertFirst,r.observableParameters.scope);return i}(function(r){r[r.INIT=0]="INIT",r[r.STARTED=1]="STARTED",r[r.ENDED=2]="ENDED"})(Vi||(Vi={}));var U_=function(){function r(t){var e,n,i=this;this.onEachCountObservable=new x.c,this.onTimerAbortedObservable=new x.c,this.onTimerEndedObservable=new x.c,this.onStateChangedObservable=new x.c,this._observer=null,this._breakOnNextTick=!1,this._tick=function(o){var a=Date.now();i._timer=a-i._startTime;var s={startTime:i._startTime,currentTime:a,deltaTime:i._timer,completeRate:i._timer/i._timeToEnd,payload:o},d=i._breakOnNextTick||i._breakCondition(s);d||i._timer>=i._timeToEnd?i._stop(s,d):i.onEachCountObservable.notifyObservers(s)},this._setState(Vi.INIT),this._contextObservable=t.contextObservable,this._observableParameters=(e=t.observableParameters)!==null&&e!==void 0?e:{},this._breakCondition=(n=t.breakCondition)!==null&&n!==void 0?n:function(){return!1},t.onEnded&&this.onTimerEndedObservable.add(t.onEnded),t.onTick&&this.onEachCountObservable.add(t.onTick),t.onAborted&&this.onTimerAbortedObservable.add(t.onAborted)}return Object.defineProperty(r.prototype,"breakCondition",{set:function(t){this._breakCondition=t},enumerable:!1,configurable:!0}),r.prototype.clearObservables=function(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()},r.prototype.start=function(t){if(t===void 0&&(t=this._timeToEnd),this._state===Vi.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=t,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(Vi.STARTED)},r.prototype.stop=function(){this._state===Vi.STARTED&&(this._breakOnNextTick=!0)},r.prototype.dispose=function(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()},r.prototype._setState=function(t){this._state=t,this.onStateChangedObservable.notifyObservers(this._state)},r.prototype._stop=function(t,e){e===void 0&&(e=!1),this._contextObservable.remove(this._observer),this._setState(Vi.ENDED),e?this.onTimerAbortedObservable.notifyObservers(t):this.onTimerEndedObservable.notifyObservers(t)},r}(),ho=function(r){function t(e,n){var i=r.call(this,e)||this;return i._options=n,i._controllers={},i._snappedToPoint=!1,i._tmpRay=new dn.a(new u.e,new u.e),i._tmpVector=new u.e,i._tmpQuaternion=new u.b,i.backwardsMovementEnabled=!0,i.backwardsTeleportationDistance=.7,i.parabolicCheckRadius=5,i.parabolicRayEnabled=!0,i.straightRayEnabled=!0,i.rotationAngle=Math.PI/8,i._rotationEnabled=!0,i._attachController=function(o){if(!(i._controllers[o.uniqueId]||i._options.forceHandedness&&o.inputSource.handedness!==i._options.forceHandedness)){i._controllers[o.uniqueId]={xrController:o,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0}};var a=i._controllers[o.uniqueId];if(a.xrController.inputSource.targetRayMode==="tracked-pointer"&&a.xrController.inputSource.gamepad){var s=function(){if(o.motionController){var d=o.motionController.getComponentOfType(Cr.THUMBSTICK_TYPE)||o.motionController.getComponentOfType(Cr.TOUCHPAD_TYPE);if(!d||i._options.useMainComponentOnly){var p=o.motionController.getMainComponent();if(!p)return;a.teleportationComponent=p,a.onButtonChangedObserver=p.onButtonStateChangedObservable.add(function(){p.changes.pressed&&(p.changes.pressed.current?(a.teleportationState.forward=!0,i._currentTeleportationControllerId=a.xrController.uniqueId,a.teleportationState.baseRotation=i._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,a.teleportationState.currentRotation=0,Ws({timeout:i._options.timeToTeleport||3e3,contextObservable:i._xrSessionManager.onXRFrameObservable,breakCondition:function(){return!p.pressed},onEnded:function(){i._currentTeleportationControllerId===a.xrController.uniqueId&&a.teleportationState.forward&&i._teleportForward(o.uniqueId)}})):(a.teleportationState.forward=!1,i._currentTeleportationControllerId=""))})}else a.teleportationComponent=d,a.onAxisChangedObserver=d.onAxisValueChangedObservable.add(function(y){if(y.y<=.7&&a.teleportationState.backwards&&(a.teleportationState.backwards=!1),y.y>.7&&!a.teleportationState.forward&&i.backwardsMovementEnabled&&!i.snapPointsOnly&&!a.teleportationState.backwards){a.teleportationState.backwards=!0,i._tmpQuaternion.copyFrom(i._options.xrInput.xrCamera.rotationQuaternion),i._tmpQuaternion.toEulerAnglesToRef(i._tmpVector),i._tmpVector.x=0,i._tmpVector.z=0,u.b.FromEulerVectorToRef(i._tmpVector,i._tmpQuaternion),i._tmpVector.set(0,0,i.backwardsTeleportationDistance*(i._xrSessionManager.scene.useRightHandedSystem?1:-1)),i._tmpVector.rotateByQuaternionToRef(i._tmpQuaternion,i._tmpVector),i._tmpVector.addInPlace(i._options.xrInput.xrCamera.position),i._tmpRay.origin.copyFrom(i._tmpVector),i._tmpRay.length=i._options.xrInput.xrCamera.realWorldHeight+.1,i._tmpRay.direction.set(0,-1,0);var P=i._xrSessionManager.scene.pickWithRay(i._tmpRay,function(U){return i._floorMeshes.indexOf(U)!==-1});P&&P.pickedPoint&&(i._options.xrInput.xrCamera.position.x=P.pickedPoint.x,i._options.xrInput.xrCamera.position.z=P.pickedPoint.z)}if(y.y<-.7&&!i._currentTeleportationControllerId&&!a.teleportationState.rotating&&(a.teleportationState.forward=!0,i._currentTeleportationControllerId=a.xrController.uniqueId,a.teleportationState.baseRotation=i._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),y.x){if(a.teleportationState.forward)i._currentTeleportationControllerId===a.xrController.uniqueId&&(i.rotationEnabled?setTimeout(function(){a.teleportationState.currentRotation=Math.atan2(y.x,y.y*(i._xrSessionManager.scene.useRightHandedSystem?1:-1))}):a.teleportationState.currentRotation=0);else if(!a.teleportationState.rotating&&Math.abs(y.x)>.7){a.teleportationState.rotating=!0;var O=i.rotationAngle*(y.x>0?1:-1)*(i._xrSessionManager.scene.useRightHandedSystem?-1:1);i._options.xrInput.xrCamera.rotationQuaternion.multiplyInPlace(u.b.FromEulerAngles(0,O,0))}}else a.teleportationState.rotating=!1;y.x===0&&y.y===0&&a.teleportationState.forward&&i._teleportForward(o.uniqueId)})}};o.motionController?s():o.onMotionControllerInitObservable.addOnce(function(){s()})}else i._xrSessionManager.scene.onPointerObservable.add(function(d){d.type===Tt.a.POINTERDOWN?(a.teleportationState.forward=!0,i._currentTeleportationControllerId=a.xrController.uniqueId,a.teleportationState.baseRotation=i._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,a.teleportationState.currentRotation=0,Ws({timeout:i._options.timeToTeleport||3e3,contextObservable:i._xrSessionManager.onXRFrameObservable,onEnded:function(){i._currentTeleportationControllerId===a.xrController.uniqueId&&a.teleportationState.forward&&i._teleportForward(o.uniqueId)}})):d.type===Tt.a.POINTERUP&&(a.teleportationState.forward=!1,i._currentTeleportationControllerId="")})}},i._options.teleportationTargetMesh||i._createDefaultTargetMesh(),i._floorMeshes=i._options.floorMeshes||[],i._snapToPositions=i._options.snapPositions||[],i._setTargetMeshVisibility(!1),i}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"rotationEnabled",{get:function(){return this._rotationEnabled},set:function(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){var n=this._options.teleportationTargetMesh.getChildMeshes(!1,function(i){return i.name==="rotationCone"});n[0]&&n[0].setEnabled(e)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"teleportationTargetMesh",{get:function(){return this._options.teleportationTargetMesh||null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapPointsOnly",{get:function(){return!!this._options.snapPointsOnly},set:function(e){this._options.snapPointsOnly=e},enumerable:!1,configurable:!0}),t.prototype.addFloorMesh=function(e){this._floorMeshes.push(e)},t.prototype.addSnapPoint=function(e){this._snapToPositions.push(e)},t.prototype.attach=function(){var e=this;return!!r.prototype.attach.call(this)&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,function(n){e._detachController(n.uniqueId)}),!0)},t.prototype.detach=function(){var e=this;return!!r.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach(function(n){e._detachController(n)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)},t.prototype.dispose=function(){r.prototype.dispose.call(this),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)},t.prototype.removeFloorMesh=function(e){var n=this._floorMeshes.indexOf(e);n!==-1&&this._floorMeshes.splice(n,1)},t.prototype.removeFloorMeshByName=function(e){var n=this._xrSessionManager.scene.getMeshByName(e);n&&this.removeFloorMesh(n)},t.prototype.removeSnapPoint=function(e){var n=this._snapToPositions.indexOf(e);if(n===-1){for(var i=0;i=p.video.HAVE_CURRENT_DATA;return!d.poster||d.autoPlay&&y?y&&p._createInternalTexture():(p._texture=p._getEngine().createTexture(d.poster,!1,!p.invertY,i),p._displayingPosterTexture=!0),p}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new x.c),this._onUserActionRequestedObservable},enumerable:!1,configurable:!0}),t.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:typeof e=="object"?e.toString():e},t.prototype._getVideo=function(e){if(e instanceof HTMLVideoElement)return Ye.b.SetCorsBehavior(e.currentSrc,e),e;var n=document.createElement("video");return typeof e=="string"?(Ye.b.SetCorsBehavior(e,n),n.src=e):(Ye.b.SetCorsBehavior(e[0],n),e.forEach(function(i){var o=document.createElement("source");o.src=i,n.appendChild(o)})),n},t.prototype._rebuild=function(){this.update()},t.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},t.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},t.prototype.updateURL=function(e){this.video.src=e,this._currentSrc=e},t.prototype.clone=function(){return new t(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)},t.prototype.dispose=function(){r.prototype.dispose.call(this),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this.reset),this.video.pause()},t.CreateFromStreamAsync=function(e,n){var i=document.createElement("video");return e.getEngine()._badOS&&(document.body.appendChild(i),i.style.transform="scale(0.0001, 0.0001)",i.style.opacity="0",i.style.position="fixed",i.style.bottom="0px",i.style.right="0px"),i.setAttribute("autoplay",""),i.setAttribute("muted","true"),i.setAttribute("playsinline",""),i.muted=!0,i.mozSrcObject!==void 0?i.mozSrcObject=n:typeof i.srcObject=="object"?i.srcObject=n:(window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,i.src=window.URL&&window.URL.createObjectURL(n)),new Promise(function(o){var a=function(){o(new t("video",i,e,!0,!0)),i.removeEventListener("playing",a)};i.addEventListener("playing",a),i.play()})},t.CreateFromWebCamAsync=function(e,n,i){var o,a=this;return i===void 0&&(i=!1),n&&n.deviceId&&(o={exact:n.deviceId}),navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:n,audio:i}).then(function(s){return a.CreateFromStreamAsync(e,s)}):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:o,width:{min:n&&n.minWidth||256,max:n&&n.maxWidth||640},height:{min:n&&n.minHeight||256,max:n&&n.maxHeight||480}},audio:i},function(s){return a.CreateFromStreamAsync(e,s)},function(s){l.a.Error(s.name)}),Promise.reject("No support for userMedia on this device"))},t.CreateFromWebCam=function(e,n,i,o){o===void 0&&(o=!1),this.CreateFromWebCamAsync(e,i,o).then(function(a){n&&n(a)}).catch(function(a){l.a.Error(a.name)})},t}(we.a),G_=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"videoTexture",{get:function(){return this._texture},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"videoMode",{get:function(){return this.textureMode},set:function(e){this.textureMode=e},enumerable:!1,configurable:!0}),t.prototype._initTexture=function(e,n,i){var o=this,a={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new Uu((this.name||"videoDome")+"_texture",e,n,i.generateMipMaps,this._useDirectMapping,we.a.TRILINEAR_SAMPLINGMODE,a);return i.clickToPlay&&(n.onPointerUp=function(){o._texture.video.play()}),s},t.MODE_MONOSCOPIC=Bi.MODE_MONOSCOPIC,t.MODE_TOPBOTTOM=Bi.MODE_TOPBOTTOM,t.MODE_SIDEBYSIDE=Bi.MODE_SIDEBYSIDE,t}(Bi),jn=f(55),z_=function(){function r(t){this.engine=t,this._captureGPUFrameTime=!1,this._gpuFrameTime=new jn.a,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new jn.a,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(r.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(t){var e=this;t!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=t,t?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add(function(){e._gpuFrameTimeToken||(e._gpuFrameTimeToken=e.engine.startTimeQuery())}),this._onEndFrameObserver=this.engine.onEndFrameObservable.add(function(){if(e._gpuFrameTimeToken){var n=e.engine.endTimeQuery(e._gpuFrameTimeToken);n>-1&&(e._gpuFrameTimeToken=null,e._gpuFrameTime.fetchNewFrame(),e._gpuFrameTime.addCount(n,!0))}})):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(t){var e=this;t!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=t,t?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add(function(){e._shaderCompilationTime.fetchNewFrame(),e._shaderCompilationTime.beginMonitoring()}),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add(function(){e._shaderCompilationTime.endMonitoring()})):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!1,configurable:!0}),r.prototype.dispose=function(){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},r}(),j_=function(){function r(t){var e=this;this.scene=t,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new jn.a,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new jn.a,this._captureFrameTime=!1,this._frameTime=new jn.a,this._captureRenderTime=!1,this._renderTime=new jn.a,this._captureInterFrameTime=!1,this._interFrameTime=new jn.a,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new jn.a,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new jn.a,this._capturePhysicsTime=!1,this._physicsTime=new jn.a,this._captureAnimationsTime=!1,this._animationsTime=new jn.a,this._captureCameraRenderTime=!1,this._cameraRenderTime=new jn.a,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=t.onBeforeAnimationsObservable.add(function(){e._captureActiveMeshesEvaluationTime&&e._activeMeshesEvaluationTime.fetchNewFrame(),e._captureRenderTargetsRenderTime&&e._renderTargetsRenderTime.fetchNewFrame(),e._captureFrameTime&&(Ye.b.StartPerformanceCounter("Scene rendering"),e._frameTime.beginMonitoring()),e._captureInterFrameTime&&e._interFrameTime.endMonitoring(),e._captureParticlesRenderTime&&e._particlesRenderTime.fetchNewFrame(),e._captureSpritesRenderTime&&e._spritesRenderTime.fetchNewFrame(),e._captureAnimationsTime&&e._animationsTime.beginMonitoring(),e.scene.getEngine()._drawCalls.fetchNewFrame()}),this._onAfterRenderObserver=t.onAfterRenderObservable.add(function(){e._captureFrameTime&&(Ye.b.EndPerformanceCounter("Scene rendering"),e._frameTime.endMonitoring()),e._captureRenderTime&&e._renderTime.endMonitoring(!1),e._captureInterFrameTime&&e._interFrameTime.beginMonitoring()})}return Object.defineProperty(r.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(t){var e=this;t!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=t,t?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add(function(){Ye.b.StartPerformanceCounter("Active meshes evaluation"),e._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(function(){Ye.b.EndPerformanceCounter("Active meshes evaluation"),e._activeMeshesEvaluationTime.endMonitoring()})):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(t){var e=this;t!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=t,t?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add(function(){Ye.b.StartPerformanceCounter("Render targets rendering"),e._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(function(){Ye.b.EndPerformanceCounter("Render targets rendering"),e._renderTargetsRenderTime.endMonitoring(!1)})):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(t){var e=this;t!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=t,t?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add(function(){Ye.b.StartPerformanceCounter("Particles"),e._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(function(){Ye.b.EndPerformanceCounter("Particles"),e._particlesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(t){var e=this;t!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=t,this.scene.spriteManagers&&(t?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add(function(){Ye.b.StartPerformanceCounter("Sprites"),e._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(function(){Ye.b.EndPerformanceCounter("Sprites"),e._spritesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(t){var e=this;t!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=t,t?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add(function(){Ye.b.StartPerformanceCounter("Physics"),e._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(function(){Ye.b.EndPerformanceCounter("Physics"),e._physicsTime.endMonitoring()})):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(t){var e=this;t!==this._captureAnimationsTime&&(this._captureAnimationsTime=t,t?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add(function(){e._animationsTime.endMonitoring()}):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(t){this._captureFrameTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(t){this._captureInterFrameTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(t){var e=this;t!==this._captureRenderTime&&(this._captureRenderTime=t,t?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add(function(){e._renderTime.beginMonitoring(),Ye.b.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(function(){e._renderTime.endMonitoring(!1),Ye.b.EndPerformanceCounter("Main render")})):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(t){var e=this;t!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=t,t?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add(function(n){e._cameraRenderTime.beginMonitoring(),Ye.b.StartPerformanceCounter("Rendering camera "+n.name)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(function(n){e._cameraRenderTime.endMonitoring(!1),Ye.b.EndPerformanceCounter("Rendering camera "+n.name)})):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!1,configurable:!0}),r.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},r}(),H_=`#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; -void main(void) -{ -vec4 finalColor=glowColor; - -#ifdef DIFFUSE -vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); -#ifdef GLOW - -finalColor.a*=albedoTexture.a; -#endif -#ifdef HIGHLIGHT - -finalColor.a=albedoTexture.a; -#endif -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); -#ifdef OPACITYRGB -finalColor.a*=getLuminance(opacityMap.rgb); -#else -finalColor.a*=opacityMap.a; -#endif -finalColor.a*=opacityIntensity; -#endif -#ifdef VERTEXALPHA -finalColor.a*=vColor.a; -#endif -#ifdef ALPHATEST -if (finalColor.a -#include -#include[0..maxSimultaneousMorphTargets] - -#include -uniform mat4 viewProjection; -varying vec4 vPosition; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse; -uniform mat4 diffuseMatrix; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity; -uniform mat4 opacityMatrix; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive; -uniform mat4 emissiveMatrix; -#endif -#ifdef VERTEXALPHA -attribute vec4 color; -varying vec4 vColor; -#endif -void main(void) -{ -vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -#include -#include -#ifdef CUBEMAP -vPosition=finalWorld*vec4(positionUpdated,1.0); -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#else -vPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -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 -}`;je.a.ShadersStore.glowMapGenerationVertexShader=W_;var fo=function(){function r(t,e){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new M.b},this.neutralColor=new M.b,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new x.c,this.onBeforeRenderMainTextureObservable=new x.c,this.onBeforeComposeObservable=new x.c,this.onBeforeRenderMeshToEffect=new x.c,this.onAfterRenderMeshToEffect=new x.c,this.onAfterComposeObservable=new x.c,this.onSizeChangedObservable=new x.c,this.name=t,this._scene=e||te.a.LastCreatedScene,r._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._generateIndexBuffer(),this._generateVertexBuffer()}return Object.defineProperty(r.prototype,"camera",{get:function(){return this._effectLayerOptions.camera},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"renderingGroupId",{get:function(){return this._effectLayerOptions.renderingGroupId},set:function(t){this._effectLayerOptions.renderingGroupId=t},enumerable:!1,configurable:!0}),r.prototype._init=function(t){this._effectLayerOptions=Object(c.a)({mainTextureRatio:.5,alphaBlendingMode:h.a.ALPHA_COMBINE,camera:null,renderingGroupId:-1},t),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses(),this._mergeEffect=this._createMergeEffect()},r.prototype._generateIndexBuffer=function(){var t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=this._engine.createIndexBuffer(t)},r.prototype._generateVertexBuffer=function(){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1);var e=new Me.b(this._engine,t,Me.b.PositionKind,!1,!1,2);this._vertexBuffers[Me.b.PositionKind]=e},r.prototype._setMainTextureSize=function(){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?Ue.a.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?Ue.a.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)},r.prototype._createMainTexture=function(){var t=this;this._mainTexture=new sn("HighlightLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,h.a.TEXTURETYPE_UNSIGNED_INT),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=we.a.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=we.a.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(we.a.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.customRenderFunction=function(n,i,o,a){var s;t.onBeforeRenderMainTextureObservable.notifyObservers(t);var d=t._scene.getEngine();if(a.length){for(d.setColorWrite(!1),s=0;s4&&(a.push(Me.b.MatricesIndicesExtraKind),a.push(Me.b.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);var z=s.skeleton;z&&z.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(z?z.bones.length+1:0)),s.numBoneInfluencers>0&&F.addCPUSkinningFallback(0,s)}else o.push("#define NUM_BONE_INFLUENCERS 0");var J=s.morphTargetManager,ie=0;J&&J.numInfluencers>0&&(o.push("#define MORPHTARGETS"),ie=J.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+ie),tt.a.PrepareAttributesForMorphTargetsInfluencers(a,s,ie)),e&&(o.push("#define INSTANCES"),tt.a.PushAttributesForInstances(a),t.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this._addCustomEffectDefines(o);var se=o.join(` -`);return this._cachedDefines!==se&&(this._cachedDefines=se,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",a,["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity"],["diffuseSampler","emissiveSampler","opacitySampler","boneSampler"],se,F,void 0,void 0,{maxSimultaneousMorphTargets:ie})),this._effectLayerMapGenerationEffect.isReady()},r.prototype.render=function(){var t=this._mergeEffect;if(t.isReady()){for(var e=0;e-1&&this._scene.effectLayers.splice(e,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()},r.prototype.getClassName=function(){return"EffectLayer"},r.Parse=function(t,e,n){return Ye.b.Instantiate(t.customType).Parse(t,e,n)},r._SceneComponentInitialization=function(t){throw En.a.WarnImport("EffectLayerSceneComponent")},Object(c.c)([Object(L.c)()],r.prototype,"name",void 0),Object(c.c)([Object(L.f)()],r.prototype,"neutralColor",void 0),Object(c.c)([Object(L.c)()],r.prototype,"isEnabled",void 0),Object(c.c)([Object(L.d)()],r.prototype,"camera",null),Object(c.c)([Object(L.c)()],r.prototype,"renderingGroupId",null),Object(c.c)([Object(L.c)()],r.prototype,"disableBoundingBoxesFromEffectLayer",void 0),r}();B.a.AddParser(st.a.NAME_EFFECTLAYER,function(r,t,e,n){if(r.effectLayers){e.effectLayers||(e.effectLayers=new Array);for(var i=0;i0){this._previousStencilState=this._engine.getStencilBuffer();for(var i=0,o=n;i-1)){this._renderEffects=!0,this._needStencil=this._needStencil||a.needStencil();var s=a._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1),e=!0)}}this.scene.incrementRenderId()}return e},r.prototype._setStencil=function(){this._needStencil&&this._engine.setStencilBuffer(!0)},r.prototype._setStencilBack=function(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},r.prototype._draw=function(t){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var e=this.scene.effectLayers,n=0;n-1},t.prototype.referenceMeshToUseItsOwnMaterial=function(e){this._meshesUsingTheirOwnMaterials.push(e.uniqueId)},t.prototype.unReferenceMeshFromUsingItsOwnMaterial=function(e){for(var n=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);n>=0;)this._meshesUsingTheirOwnMaterials.splice(n,1),n=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)},t.prototype._disposeMesh=function(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)},t.prototype.getClassName=function(){return"GlowLayer"},t.prototype.serialize=function(){var e,n=L.a.Serialize(this);if(n.customType="BABYLON.GlowLayer",n.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;e0&&t.isBackground===e&&t.renderTargetTextures.indexOf(i)>-1&&(t.layerMask&n)!=0},r.prototype._drawRenderTargetBackground=function(t){var e=this;this._draw(function(n){return e._drawRenderTargetPredicate(n,!0,e.scene.activeCamera.layerMask,t)})},r.prototype._drawRenderTargetForeground=function(t){var e=this;this._draw(function(n){return e._drawRenderTargetPredicate(n,!1,e.scene.activeCamera.layerMask,t)})},r.prototype.addFromContainer=function(t){var e=this;t.layers&&t.layers.forEach(function(n){e.scene.layers.push(n)})},r.prototype.removeFromContainer=function(t,e){var n=this;e===void 0&&(e=!1),t.layers&&t.layers.forEach(function(i){var o=n.scene.layers.indexOf(i);o!==-1&&n.scene.layers.splice(o,1),e&&i.dispose()})},r}(),Q_=` -varying vec2 vUV; -uniform sampler2D textureSampler; - -uniform vec4 color; - -#include -void main(void) { -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; -}`;je.a.ShadersStore.layerPixelShader=Q_;var q_=` -attribute vec2 position; - -uniform vec2 scale; -uniform vec2 offset; -uniform mat4 textureMatrix; - -varying vec2 vUV; -const vec2 madd=vec2(0.5,0.5); -void main(void) { -vec2 shiftedPosition=position*scale+offset; -vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0)); -gl_Position=vec4(shiftedPosition,0.0,1.0); -}`;je.a.ShadersStore.layerVertexShader=q_;var Z_=function(){function r(t,e,n,i,o){this.name=t,this.scale=new u.d(1,1),this.offset=new u.d(0,0),this.alphaBlendingMode=h.a.ALPHA_COMBINE,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this._vertexBuffers={},this.onDisposeObservable=new x.c,this.onBeforeRenderObservable=new x.c,this.onAfterRenderObservable=new x.c,this.texture=e?new we.a(e,n,!0):null,this.isBackground=i===void 0||i,this.color=o===void 0?new M.b(1,1,1,1):o,this._scene=n||te.a.LastCreatedScene;var a=this._scene._getComponent(st.a.NAME_LAYER);a||(a=new Gu(this._scene),this._scene._addComponent(a)),this._scene.layers.push(this);var s=this._scene.getEngine(),d=[];d.push(1,1),d.push(-1,1),d.push(-1,-1),d.push(1,-1);var p=new Me.b(s,d,Me.b.PositionKind,!1,!1,2);this._vertexBuffers[Me.b.PositionKind]=p,this._createIndexBuffer()}return Object.defineProperty(r.prototype,"onDispose",{set:function(t){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onBeforeRender",{set:function(t){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"onAfterRender",{set:function(t){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(t)},enumerable:!1,configurable:!0}),r.prototype._createIndexBuffer=function(){var t=this._scene.getEngine(),e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=t.createIndexBuffer(e)},r.prototype._rebuild=function(){var t=this._vertexBuffers[Me.b.PositionKind];t&&t._rebuild(),this._createIndexBuffer()},r.prototype.render=function(){var t=this._scene.getEngine(),e="";this.alphaTest&&(e="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(e+=`\r -#define LINEAR`),this._previousDefines!==e&&(this._previousDefines=e,this._effect=t.createEffect("layer",[Me.b.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],e));var n=this._effect;n&&n.isReady()&&this.texture&&this.texture.isReady()&&(t=this._scene.getEngine(),this.onBeforeRenderObservable.notifyObservers(this),t.enableEffect(n),t.setState(!1),n.setTexture("textureSampler",this.texture),n.setMatrix("textureMatrix",this.texture.getTextureMatrix()),n.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),n.setVector2("offset",this.offset),n.setVector2("scale",this.scale),t.bindBuffers(this._vertexBuffers,this._indexBuffer,n),this.alphaTest?t.drawElementsType(Ht.a.TriangleFillMode,0,6):(t.setAlphaMode(this.alphaBlendingMode),t.drawElementsType(Ht.a.TriangleFillMode,0,6),t.setAlphaMode(h.a.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this))},r.prototype.dispose=function(){var t=this._vertexBuffers[Me.b.PositionKind];t&&(t.dispose(),this._vertexBuffers[Me.b.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];var e=this._scene.layers.indexOf(this);this._scene.layers.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},r}(),zu=function(){function r(t,e,n,i,o){this.size=t,this.position=e,this.alphaMode=h.a.ALPHA_ONEONE,this.color=n||new M.a(1,1,1),this.texture=i?new we.a(i,o.getScene(),!0):null,this._system=o,o.lensFlares.push(this)}return r.AddFlare=function(t,e,n,i,o){return new r(t,e,n,i,o)},r.prototype.dispose=function(){this.texture&&this.texture.dispose();var t=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(t,1)},r}(),J_=` -varying vec2 vUV; -uniform sampler2D textureSampler; - -uniform vec4 color; -void main(void) { -vec4 baseColor=texture2D(textureSampler,vUV); -gl_FragColor=baseColor*color; -}`;je.a.ShadersStore.lensFlarePixelShader=J_;var $_=` -attribute vec2 position; - -uniform mat4 viewportMatrix; - -varying vec2 vUV; -const vec2 madd=vec2(0.5,0.5); -void main(void) { -vUV=position*madd+madd; -gl_Position=viewportMatrix*vec4(position,0.0,1.0); -}`;je.a.ShadersStore.lensFlareVertexShader=$_;var Ys=function(){function r(t,e,n){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=n||te.a.LastCreatedScene,r._SceneComponentInitialization(this._scene),this._emitter=e,this.id=t,n.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(s){return n.activeCamera&&s.material&&s.isVisible&&s.isEnabled()&&s.isBlocker&&(s.layerMask&n.activeCamera.layerMask)!=0};var i=n.getEngine(),o=[];o.push(1,1),o.push(-1,1),o.push(-1,-1),o.push(1,-1),this._vertexBuffers[Me.b.PositionKind]=new Me.b(i,o,Me.b.PositionKind,!1,!1,2);var a=[];a.push(0),a.push(1),a.push(2),a.push(0),a.push(2),a.push(3),this._indexBuffer=i.createIndexBuffer(a),this._effect=i.createEffect("lensFlare",[Me.b.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(r.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(t){this._isEnabled=t},enumerable:!1,configurable:!0}),r.prototype.getScene=function(){return this._scene},r.prototype.getEmitter=function(){return this._emitter},r.prototype.setEmitter=function(t){this._emitter=t},r.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},r.prototype.computeEffectivePosition=function(t){var e=this.getEmitterPosition();return e=u.e.Project(e,u.a.Identity(),this._scene.getTransformMatrix(),t),this._positionX=e.x,this._positionY=e.y,e=u.e.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder,t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,e.x+=this.viewportBorder,e.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),e.z>0&&(this._positionX>t.x&&this._positionXt.y&&(this._positionY,t.y,t.height),!0)},r.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var t=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),e=t.length();t.normalize();var n=new dn.a(this._scene.activeCamera.globalPosition,t),i=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!i||!i.hit||i.distance>e},r.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var t,e,n=this._scene.getEngine(),i=this._scene.activeCamera.viewport.toGlobal(n.getRenderWidth(!0),n.getRenderHeight(!0));if(!this.computeEffectivePosition(i)||!this._isVisible())return!1;var o=(t=this._positionXi.x+i.width-this.borderLimit?this._positionX-i.x-i.width+this.borderLimit:0)>(e=this._positionYi.y+i.height-this.borderLimit?this._positionY-i.y-i.height+this.borderLimit:0)?t:e;(o-=this.viewportBorder)>this.borderLimit&&(o=this.borderLimit);var a=1-$.a.Clamp(o/this.borderLimit,0,1);if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(i.x+=this.viewportBorder,i.y+=this.viewportBorder,i.width-=2*this.viewportBorder,i.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var s=i.x+i.width/2,d=i.y+i.height/2,p=s-this._positionX,y=d-this._positionY;n.enableEffect(this._effect),n.setState(!1),n.setDepthBuffer(!1),n.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var P=0;P0);for(var n=0,i=e;n0)}},r}();Ys._SceneComponentInitialization=function(r){var t=r._getComponent(st.a.NAME_LENSFLARESYSTEM);t||(t=new ju(r),r._addComponent(t))};var em=` - - - - -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); -} -`;je.a.IncludesShadersStore.bayerDitherFunctions=em;var tm=`#if SM_FLOAT == 0 -#include -#endif -#if SM_SOFTTRANSPARENTSHADOW == 1 -#include -uniform float softTransparentShadowSM; -#endif -varying float vDepthMetricSM; -#if SM_USEDISTANCE == 1 -uniform vec3 lightDataSM; -varying vec3 vPositionWSM; -#endif -uniform vec3 biasAndScaleSM; -uniform vec2 depthValuesSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1 -varying float zSM; -#endif -`;je.a.IncludesShadersStore.shadowMapFragmentDeclaration=tm;var nm=` float depthSM=vDepthMetricSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1 -#if SM_USEDISTANCE == 1 -depthSM=clamp(((length(vPositionWSM-lightDataSM)+depthValuesSM.x)/(depthValuesSM.y))+biasAndScaleSM.x,0.0,1.0); -#else -depthSM=clamp(((zSM+depthValuesSM.x)/(depthValuesSM.y))+biasAndScaleSM.x,0.0,1.0); -#endif -gl_FragDepth=depthSM; -#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;`;je.a.IncludesShadersStore.shadowMapFragment=nm;var im=`#include -#ifdef ALPHATEST -varying vec2 vUV; -uniform sampler2D diffuseSampler; -#endif -#include -void main(void) -{ -#include -#ifdef ALPHATEST -float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; -if (alphaFromAlphaTexture<0.4) -discard; -#endif -#if SM_SOFTTRANSPARENTSHADOW == 1 -#ifdef ALPHATEST -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 -}`;je.a.ShadersStore.shadowMapPixelShader=im;var rm=`#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 -`;je.a.IncludesShadersStore.shadowMapVertexDeclaration=rm;var om=` -#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 -`;je.a.IncludesShadersStore.shadowMapVertexNormalBias=om;var am=`#if SM_USEDISTANCE == 1 -vPositionWSM=worldPos.xyz; -#endif -#if SM_DEPTHTEXTURE == 1 - -gl_Position.z+=biasAndScaleSM.x*gl_Position.w; -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP == 1 -zSM=gl_Position.z; -gl_Position.z=0.0; -#elif SM_USEDISTANCE == 0 - -vDepthMetricSM=((gl_Position.z+depthValuesSM.x)/(depthValuesSM.y))+biasAndScaleSM.x; -#endif -`;je.a.IncludesShadersStore.shadowMapVertexMetric=am;var sm=` -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include -#include -#include[0..maxSimultaneousMorphTargets] - -#include -#include -uniform mat4 viewProjection; -#ifdef ALPHATEST -varying vec2 vUV; -uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include -#include -void main(void) -{ -vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#include[0..maxSimultaneousMorphTargets] -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normWorldSM=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2])); -vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vec3 vNormalW=normalize(normWorldSM*normalUpdated); -#endif -#endif -#include - -gl_Position=viewProjection*worldPos; -#include -#ifdef 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 -}`;je.a.ShadersStore.shadowMapVertexShader=sm;var cm=` -varying vec2 vUV; -uniform sampler2D textureSampler; - -uniform vec2 screenSize; -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))); -}`;je.a.ShadersStore.depthBoxBlurPixelShader=cm;var lm=`#if SM_SOFTTRANSPARENTSHADOW == 1 -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; -#endif -`;je.a.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=lm;var Hu=new u.a,Wu=new u.a,Fn=function(){function r(t,e,n){this.onBeforeShadowMapRenderObservable=new x.c,this.onAfterShadowMapRenderObservable=new x.c,this.onBeforeShadowMapRenderMeshObservable=new x.c,this.onAfterShadowMapRenderMeshObservable=new x.c,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=r.FILTER_NONE,this._filteringQuality=r.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=u.e.Zero(),this._viewMatrix=u.a.Zero(),this._projectionMatrix=u.a.Zero(),this._transformMatrix=u.a.Zero(),this._cachedPosition=new u.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new u.e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=u.a.Identity(),this._mapSize=t,this._light=e,this._scene=e.getScene(),e._shadowGenerator=this,this.id=e.id,r._SceneComponentInitialization(this._scene);var i=this._scene.getEngine().getCaps();n?i.textureFloatRender&&i.textureFloatLinearFiltering?this._textureType=h.a.TEXTURETYPE_FLOAT:i.textureHalfFloatRender&&i.textureHalfFloatLinearFiltering?this._textureType=h.a.TEXTURETYPE_HALF_FLOAT:this._textureType=h.a.TEXTURETYPE_UNSIGNED_INT:i.textureHalfFloatRender&&i.textureHalfFloatLinearFiltering?this._textureType=h.a.TEXTURETYPE_HALF_FLOAT:i.textureFloatRender&&i.textureFloatLinearFiltering?this._textureType=h.a.TEXTURETYPE_FLOAT:this._textureType=h.a.TEXTURETYPE_UNSIGNED_INT,this._initializeGenerator(),this._applyFilterValues()}return Object.defineProperty(r.prototype,"bias",{get:function(){return this._bias},set:function(t){this._bias=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"normalBias",{get:function(){return this._normalBias},set:function(t){this._normalBias=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(t){this._blurBoxOffset!==t&&(this._blurBoxOffset=t,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"blurScale",{get:function(){return this._blurScale},set:function(t){this._blurScale!==t&&(this._blurScale=t,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"blurKernel",{get:function(){return this._blurKernel},set:function(t){this._blurKernel!==t&&(this._blurKernel=t,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"useKernelBlur",{get:function(){return this._useKernelBlur},set:function(t){this._useKernelBlur!==t&&(this._useKernelBlur=t,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"depthScale",{get:function(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()},set:function(t){this._depthScale=t},enumerable:!1,configurable:!0}),r.prototype._validateFilter=function(t){return t},Object.defineProperty(r.prototype,"filter",{get:function(){return this._filter},set:function(t){if(t=this._validateFilter(t),this._light.needCube()){if(t===r.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(t===r.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(t===r.FILTER_PCF||t===r.FILTER_PCSS)return void(this.usePoissonSampling=!0)}t!==r.FILTER_PCF&&t!==r.FILTER_PCSS||this._scene.getEngine().webGLVersion!==1?this._filter!==t&&(this._filter=t,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"usePoissonSampling",{get:function(){return this.filter===r.FILTER_POISSONSAMPLING},set:function(t){var e=this._validateFilter(r.FILTER_POISSONSAMPLING);(t||this.filter===r.FILTER_POISSONSAMPLING)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"useExponentialShadowMap",{get:function(){return this.filter===r.FILTER_EXPONENTIALSHADOWMAP},set:function(t){var e=this._validateFilter(r.FILTER_EXPONENTIALSHADOWMAP);(t||this.filter===r.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"useBlurExponentialShadowMap",{get:function(){return this.filter===r.FILTER_BLUREXPONENTIALSHADOWMAP},set:function(t){var e=this._validateFilter(r.FILTER_BLUREXPONENTIALSHADOWMAP);(t||this.filter===r.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"useCloseExponentialShadowMap",{get:function(){return this.filter===r.FILTER_CLOSEEXPONENTIALSHADOWMAP},set:function(t){var e=this._validateFilter(r.FILTER_CLOSEEXPONENTIALSHADOWMAP);(t||this.filter===r.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"useBlurCloseExponentialShadowMap",{get:function(){return this.filter===r.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP},set:function(t){var e=this._validateFilter(r.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(t||this.filter===r.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"usePercentageCloserFiltering",{get:function(){return this.filter===r.FILTER_PCF},set:function(t){var e=this._validateFilter(r.FILTER_PCF);(t||this.filter===r.FILTER_PCF)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"filteringQuality",{get:function(){return this._filteringQuality},set:function(t){this._filteringQuality!==t&&(this._filteringQuality=t,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"useContactHardeningShadow",{get:function(){return this.filter===r.FILTER_PCSS},set:function(t){var e=this._validateFilter(r.FILTER_PCSS);(t||this.filter===r.FILTER_PCSS)&&(this.filter=t?e:r.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"contactHardeningLightSizeUVRatio",{get:function(){return this._contactHardeningLightSizeUVRatio},set:function(t){this._contactHardeningLightSizeUVRatio=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"darkness",{get:function(){return this._darkness},set:function(t){this.setDarkness(t)},enumerable:!1,configurable:!0}),r.prototype.getDarkness=function(){return this._darkness},r.prototype.setDarkness=function(t){return this._darkness=t>=1?1:t<=0?0:t,this},Object.defineProperty(r.prototype,"transparencyShadow",{get:function(){return this._transparencyShadow},set:function(t){this.setTransparencyShadow(t)},enumerable:!1,configurable:!0}),r.prototype.setTransparencyShadow=function(t){return this._transparencyShadow=t,this},r.prototype.getShadowMap=function(){return this._shadowMap},r.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},r.prototype.getClassName=function(){return r.CLASSNAME},r.prototype.addShadowCaster=function(t,e){var n;return e===void 0&&(e=!0),this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(t),e&&(n=this._shadowMap.renderList).push.apply(n,t.getChildMeshes()),this):this},r.prototype.removeShadowCaster=function(t,e){if(e===void 0&&(e=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var n=this._shadowMap.renderList.indexOf(t);if(n!==-1&&this._shadowMap.renderList.splice(n,1),e)for(var i=0,o=t.getChildren();i1?(this._shadowMap=new sn(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(h.a.LESS,!0)):this._shadowMap=new sn(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube())},r.prototype._initializeShadowMap=function(){var t=this;if(this._createTargetRenderTexture(),this._shadowMap!==null){this._shadowMap.wrapU=we.a.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=we.a.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(we.a.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=function(a,s){return!0};var e=this._scene.getEngine();this._shadowMap.onBeforeRenderObservable.add(function(a){if(t._currentFaceIndex=a,t._filter===r.FILTER_PCF&&e.setColorWrite(!1),t._scene.getSceneUniformBuffer().useUbo){var s=t._scene.getSceneUniformBuffer();s.updateMatrix("viewProjection",t.getTransformMatrix()),s.updateMatrix("view",t._viewMatrix),s.update()}}),this._shadowMap.onAfterUnbindObservable.add(function(){if(t._scene.getSceneUniformBuffer().useUbo){var a=t._scene.getSceneUniformBuffer();a.updateMatrix("viewProjection",t._scene.getTransformMatrix()),a.updateMatrix("view",t._scene.getViewMatrix()),a.update()}if(t._filter===r.FILTER_PCF&&e.setColorWrite(!0),t.useBlurExponentialShadowMap||t.useBlurCloseExponentialShadowMap){var s=t.getShadowMapForRendering();if(s){var d=s.getInternalTexture();t._scene.postProcessManager.directRender(t._blurPostProcesses,d,!0),e.unBindFramebuffer(d,!0)}}});var n=new M.b(0,0,0,0),i=new M.b(1,1,1,1);this._shadowMap.onClearObservable.add(function(a){t._filter===r.FILTER_PCF?a.clear(i,!1,!0,!1):t.useExponentialShadowMap||t.useBlurExponentialShadowMap?a.clear(n,!0,!0,!1):a.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(function(a){t._storedUniqueId=t._shadowMap.uniqueId,t._mapSize=a.getRenderSize(),t._light._markMeshesAsLightDirty(),t.recreateShadowMap()});for(var o=eo.b.MIN_RENDERINGGROUPS;o=s.length)return void(t&&t(n));setTimeout(O,16)}};O()}else t&&t(this)}else t&&t(this)}else t&&t(this)},r.prototype.forceCompilationAsync=function(t){var e=this;return new Promise(function(n){e.forceCompilation(function(){n()},t)})},r.prototype._isReadyCustomDefines=function(t,e,n){},r.prototype._prepareShadowDefines=function(t,e,n,i){n.push("#define SM_FLOAT "+(this._textureType!==h.a.TEXTURETYPE_UNSIGNED_INT?"1":"0")),n.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),n.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));var o=t.getMesh();return n.push("#define SM_NORMALBIAS "+(this.normalBias&&o.isVerticesDataPresent(Me.b.NormalKind)?"1":"0")),n.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Ci.a.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),n.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),n.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&i?"1":"0")),this._isReadyCustomDefines(n,t,e),n},r.prototype.isReady=function(t,e,n){var i=t.getMaterial(),o=i?.shadowDepthWrapper,a=[];if(this._prepareShadowDefines(t,e,a,n),o){if(!o.isReadyForSubMesh(t,a,this,e))return!1}else{var s=[Me.b.PositionKind],d=t.getMesh();if(this.normalBias&&d.isVerticesDataPresent(Me.b.NormalKind)&&(s.push(Me.b.NormalKind),a.push("#define NORMAL"),d.nonUniformScaling&&a.push("#define NONUNIFORMSCALING")),i&&i.needAlphaTesting()){var p=i.getAlphaTestTexture();if(p){if(!p.isReady())return!1;a.push("#define ALPHATEST"),d.isVerticesDataPresent(Me.b.UVKind)&&(s.push(Me.b.UVKind),a.push("#define UV1")),d.isVerticesDataPresent(Me.b.UV2Kind)&&p.coordinatesIndex===1&&(s.push(Me.b.UV2Kind),a.push("#define UV2"))}}var y=new Er.a;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){s.push(Me.b.MatricesIndicesKind),s.push(Me.b.MatricesWeightsKind),d.numBoneInfluencers>4&&(s.push(Me.b.MatricesIndicesExtraKind),s.push(Me.b.MatricesWeightsExtraKind));var P=d.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&y.addCPUSkinningFallback(0,d),P.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(P.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");var O=d.morphTargetManager,U=0;O&&O.numInfluencers>0&&(a.push("#define MORPHTARGETS"),U=O.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+U),tt.a.PrepareAttributesForMorphTargetsInfluencers(s,d,U));var F=this._scene;if(F.clipPlane&&a.push("#define CLIPPLANE"),F.clipPlane2&&a.push("#define CLIPPLANE2"),F.clipPlane3&&a.push("#define CLIPPLANE3"),F.clipPlane4&&a.push("#define CLIPPLANE4"),F.clipPlane5&&a.push("#define CLIPPLANE5"),F.clipPlane6&&a.push("#define CLIPPLANE6"),e&&(a.push("#define INSTANCES"),tt.a.PushAttributesForInstances(s),t.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(var z=0,J=this.customShaderOptions.defines;z -#endif -void main(void) -{ -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#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 -}`;je.a.ShadersStore.depthPixelShader=um;var hm=` -attribute vec3 position; -#include -#include -#include[0..maxSimultaneousMorphTargets] - -#include -uniform mat4 viewProjection; -uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -varying float vDepthMetric; -void main(void) -{ -vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -#include -#include -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); -#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 -} -`;je.a.ShadersStore.depthVertexShader=hm;var ca=function(){function r(t,e,n,i){var o=this;e===void 0&&(e=h.a.TEXTURETYPE_FLOAT),n===void 0&&(n=null),i===void 0&&(i=!1),this.enabled=!0,this.useOnlyInActiveCamera=!1,this._scene=t,this._storeNonLinearDepth=i,this.isPacked=e===h.a.TEXTURETYPE_UNSIGNED_BYTE,this.isPacked?this._clearColor=new M.b(1,1,1,1):this._clearColor=new M.b(1,0,0,1),r._SceneComponentInitialization(this._scene),this._camera=n;var a=t.getEngine(),s=this.isPacked||a.webGLVersion===1?h.a.TEXTUREFORMAT_RGBA:h.a.TEXTUREFORMAT_R;this._depthMap=new sn("depthMap",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,e,!1,void 0,void 0,void 0,void 0,s),this._depthMap.wrapU=we.a.CLAMP_ADDRESSMODE,this._depthMap.wrapV=we.a.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(function(p){p.clear(o._clearColor,!0,!0,!0)});var d=function(p){var y=p.getRenderingMesh(),P=p.getEffectiveMesh(),O=o._scene,U=O.getEngine(),F=p.getMaterial();if(P._internalAbstractMeshDataInfo._isActiveIntermediate=!1,F&&p.verticesCount!==0&&p._renderId!==O.getRenderId()){U.setState(F.backFaceCulling,0,!1,O.useRightHandedSystem);var z=y._getInstancesRenderList(p._id,!!p.getReplacementMesh());if(!z.mustReturn){var J=U.getCaps().instancedArrays&&(z.visibleInstances[p._id]!==null&&z.visibleInstances[p._id]!==void 0||y.hasThinInstances),ie=o._camera||O.activeCamera;if(o.isReady(p,J)&&ie){if(p._renderId=O.getRenderId(),U.enableEffect(o._effect),y._bind(p,o._effect,F.fillMode),o._effect.setMatrix("viewProjection",O.getTransformMatrix()),o._effect.setFloat2("depthValues",ie.minZ,ie.minZ+ie.maxZ),F&&F.needAlphaTesting()){var se=F.getAlphaTestTexture();se&&(o._effect.setTexture("diffuseSampler",se),o._effect.setMatrix("diffuseMatrix",se.getTextureMatrix()))}y.useBones&&y.computeBonesUsingShaders&&y.skeleton&&o._effect.setMatrices("mBones",y.skeleton.getTransformMatrices(y)),tt.a.BindMorphTargetParameters(y,o._effect),y._processRendering(P,p,o._effect,F.fillMode,z,J,function(ce,ue){return o._effect.setMatrix("world",ue)})}}}};this._depthMap.customRenderFunction=function(p,y,P,O){var U;if(O.length){for(a.setColorWrite(!1),U=0;U4&&(o.push(Me.b.MatricesIndicesExtraKind),o.push(Me.b.MatricesWeightsExtraKind)),i.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),i.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):i.push("#define NUM_BONE_INFLUENCERS 0");var s=a.morphTargetManager,d=0;s&&s.numInfluencers>0&&(d=s.numInfluencers,i.push("#define MORPHTARGETS"),i.push("#define NUM_MORPH_INFLUENCERS "+d),tt.a.PrepareAttributesForMorphTargetsInfluencers(o,a,d)),e&&(i.push("#define INSTANCES"),tt.a.PushAttributesForInstances(o),t.getRenderingMesh().hasThinInstances&&i.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&i.push("#define NONLINEARDEPTH"),this.isPacked&&i.push("#define PACKED");var p=i.join(` -`);return this._cachedDefines!==p&&(this._cachedDefines=p,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","depthValues","morphTargetInfluences"],["diffuseSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d})),this._effect.isReady()},r.prototype.getDepthMap=function(){return this._depthMap},r.prototype.dispose=function(){this._depthMap.dispose()},r._SceneComponentInitialization=function(t){throw En.a.WarnImport("DepthRendererSceneComponent")},r}(),dm=`attribute 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) -{ -discard; -glFragColor=vec4(0.); -} -#endif -`;je.a.ShadersStore.minmaxReduxPixelShader=dm;var Xu=function(){function r(t){this.onAfterReductionPerformed=new x.c,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=t,this._postProcessManager=new ms.a(t.getScene())}return Object.defineProperty(r.prototype,"sourceTexture",{get:function(){return this._sourceTexture},enumerable:!1,configurable:!0}),r.prototype.setSourceTexture=function(t,e,n,i){var o=this;if(n===void 0&&(n=h.a.TEXTURETYPE_HALF_FLOAT),i===void 0&&(i=!0),t!==this._sourceTexture){this.dispose(!1),this._sourceTexture=t,this._reductionSteps=[],this._forceFullscreenViewport=i;var a=this._camera.getScene(),s=new _t("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,h.a.TEXTURE_NEAREST_NEAREST,a.getEngine(),!1,"#define INITIAL"+(e?` -#define DEPTH_REDUX`:""),n,void 0,void 0,void 0,h.a.TEXTUREFORMAT_RG);s.autoClear=!1,s.forceFullscreenViewport=i;var d=this._sourceTexture.getRenderWidth(),p=this._sourceTexture.getRenderHeight();s.onApply=function(O,U){return function(F){F.setTexture("sourceTexture",o._sourceTexture),F.setFloatArray2("texSize",new Float32Array([O,U]))}}(d,p),this._reductionSteps.push(s);for(var y=1;d>1||p>1;){d=Math.max(Math.round(d/2),1),p=Math.max(Math.round(p/2),1);var P=new _t("Reduction phase "+y,"minmaxRedux",["texSize"],null,{width:d,height:p},null,h.a.TEXTURE_NEAREST_NEAREST,a.getEngine(),!1,"#define "+(d==1&&p==1?"LAST":d==1||p==1?"ONEBEFORELAST":"MAIN"),n,void 0,void 0,void 0,h.a.TEXTUREFORMAT_RG);P.autoClear=!1,P.forceFullscreenViewport=i,P.onApply=function(O,U){return function(F){O==1||U==1?F.setIntArray2("texSize",new Int32Array([O,U])):F.setFloatArray2("texSize",new Float32Array([O,U]))}}(d,p),this._reductionSteps.push(P),y++,d==1&&p==1&&P.onAfterRenderObservable.add(function(O,U,F){var z=new Float32Array(4*O*U),J={min:0,max:0};return function(){a.getEngine()._readTexturePixels(F.inputTexture,O,U,-1,0,z),J.min=z[0],J.max=z[1],o.onAfterReductionPerformed.notifyObservers(J)}}(d,p,P))}}},Object.defineProperty(r.prototype,"refreshRate",{get:function(){return this._sourceTexture?this._sourceTexture.refreshRate:-1},set:function(t){this._sourceTexture&&(this._sourceTexture.refreshRate=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"activated",{get:function(){return this._activated},enumerable:!1,configurable:!0}),r.prototype.activate=function(){var t=this;!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(function(){t._reductionSteps[0].activate(t._camera),t._postProcessManager.directRender(t._reductionSteps,t._reductionSteps[0].inputTexture,t._forceFullscreenViewport),t._camera.getScene().getEngine().unBindFramebuffer(t._reductionSteps[0].inputTexture,!1)}),this._activated=!0)},r.prototype.deactivate=function(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)},r.prototype.dispose=function(t){if(t===void 0&&(t=!0),t&&this.onAfterReductionPerformed.clear(),this.deactivate(),this._reductionSteps){for(var e=0;en&&(e=0,n=1),e<0&&(e=0),n>1&&(n=1),this._minDistance=e,this._maxDistance=n,this._breaksAreDirty=!0)},Object.defineProperty(t.prototype,"minDistance",{get:function(){return this._minDistance},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"maxDistance",{get:function(){return this._maxDistance},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return t.CLASSNAME},t.prototype.getCascadeMinExtents=function(e){return e>=0&&e=0&&ethis._scene.activeCamera.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"debug",{get:function(){return this._debug},set:function(e){this._debug=e,this._light._markMeshesAsLightDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthClamp",{get:function(){return this._depthClamp},set:function(e){this._depthClamp=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cascadeBlendPercentage",{get:function(){return this._cascadeBlendPercentage},set:function(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lambda",{get:function(){return this._lambda},set:function(e){var n=Math.min(Math.max(e,0),1);this._lambda!=n&&(this._lambda=n,this._breaksAreDirty=!0)},enumerable:!1,configurable:!0}),t.prototype.getCascadeViewMatrix=function(e){return e>=0&&e=0&&e=0&&e=s&&(a=0,s=1),a==n._minDistance&&s==n._maxDistance||n.setMinMaxDistance(a,s)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"autoCalcDepthBoundsRefreshRate",{get:function(){var e,n,i;return(i=(n=(e=this._depthReducer)===null||e===void 0?void 0:e.depthRenderer)===null||n===void 0?void 0:n.getDepthMap().refreshRate)!==null&&i!==void 0?i:-1},set:function(e){var n;!((n=this._depthReducer)===null||n===void 0)&&n.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)},enumerable:!1,configurable:!0}),t.prototype.splitFrustum=function(){this._breaksAreDirty=!0},t.prototype._splitFrustum=function(){var e=this._scene.activeCamera;if(e){for(var n=e.minZ,i=e.maxZ,o=i-n,a=this._minDistance,s=n+a*o,d=n+(this._shadowMaxZ=n?Math.min((this._shadowMaxZ-n)/(i-n),this._maxDistance):this._maxDistance)*o,p=d-s,y=d/s,P=0;PMath.PI;)o-=2*Math.PI;var s=o/Math.PI,d=a/Math.PI;s=.5*s+.5;var p=Math.round(s*n);p<0?p=0:p>=n&&(p=n-1);var y=Math.round(d*i);y<0?y=0:y>=i&&(y=i-1);var P=i-y-1;return{r:e[P*n*3+3*p+0],g:e[P*n*3+3*p+1],b:e[P*n*3+3*p+2]}},r.FACE_LEFT=[new u.e(-1,-1,-1),new u.e(1,-1,-1),new u.e(-1,1,-1),new u.e(1,1,-1)],r.FACE_RIGHT=[new u.e(1,-1,1),new u.e(-1,-1,1),new u.e(1,1,1),new u.e(-1,1,1)],r.FACE_FRONT=[new u.e(1,-1,-1),new u.e(1,-1,1),new u.e(1,1,-1),new u.e(1,1,1)],r.FACE_BACK=[new u.e(-1,-1,1),new u.e(-1,-1,-1),new u.e(-1,1,1),new u.e(-1,1,-1)],r.FACE_DOWN=[new u.e(1,1,-1),new u.e(1,1,1),new u.e(-1,1,-1),new u.e(-1,1,1)],r.FACE_UP=[new u.e(-1,-1,-1),new u.e(-1,-1,1),new u.e(1,-1,-1),new u.e(1,-1,1)],r}(),Ju=function(){function r(){}return r.Ldexp=function(t,e){return e>1023?t*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?t*Math.pow(2,-1074)*Math.pow(2,e+1074):t*Math.pow(2,e)},r.Rgbe2float=function(t,e,n,i,o,a){o>0?(o=this.Ldexp(1,o-136),t[a+0]=e*o,t[a+1]=n*o,t[a+2]=i*o):(t[a+0]=0,t[a+1]=0,t[a+2]=0)},r.readStringLine=function(t,e){for(var n="",i="",o=e;o32767)throw"HDR Bad header format, unsupported size";return{height:e,width:n,dataPosition:s+=i.length+1}},r.GetCubeMapTextureData=function(t,e){var n=new Uint8Array(t),i=this.RGBE_ReadHeader(n),o=this.RGBE_ReadPixels(n,i);return Zs.ConvertPanoramaToCubemap(o,i.width,i.height,e)},r.RGBE_ReadPixels=function(t,e){return this.RGBE_ReadPixels_RLE(t,e)},r.RGBE_ReadPixels_RLE=function(t,e){for(var n,i,o,a,s,d=e.height,p=e.width,y=e.dataPosition,P=0,O=0,U=0,F=new ArrayBuffer(4*p),z=new Uint8Array(F),J=new ArrayBuffer(e.width*e.height*4*3),ie=new Float32Array(J);d>0;){if(n=t[y++],i=t[y++],o=t[y++],a=t[y++],n!=2||i!=2||128&o||e.width<8||e.width>32767)return this.RGBE_ReadPixels_NOT_RLE(t,e);if((o<<8|a)!=p)throw"HDR Bad header format, wrong scan line width";for(P=0,U=0;U<4;U++)for(O=(U+1)*p;P128){if((s=n-128)==0||s>O-P)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)z[P++]=i}else{if((s=n)==0||s>O-P)throw"HDR Bad Format, bad scanline data (non-run)";if(z[P++]=i,--s>0)for(var se=0;se0;){for(s=0;s -#include -#include -#include -uniform float alphaG; -uniform samplerCube inputTexture; -uniform vec2 vFilteringInfo; -uniform float hdrScale; -varying vec3 direction; -void main() { -vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo); -gl_FragColor=vec4(color*hdrScale,1.0); -}`;je.a.ShadersStore.hdrFilteringPixelShader=_m;var th=function(){function r(t,e){e===void 0&&(e={}),this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=h.a.TEXTURE_FILTERING_QUALITY_OFFLINE,this.hdrScale=1,this._engine=t,this.hdrScale=e.hdrScale||this.hdrScale,this.quality=e.hdrScale||this.quality}return r.prototype._createRenderTarget=function(t){var e=h.a.TEXTURETYPE_UNSIGNED_BYTE;this._engine.getCaps().textureHalfFloatRender?e=h.a.TEXTURETYPE_HALF_FLOAT:this._engine.getCaps().textureFloatRender&&(e=h.a.TEXTURETYPE_FLOAT);var n=this._engine.createRenderTargetCubeTexture(t,{format:h.a.TEXTUREFORMAT_RGBA,type:e,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:h.a.TEXTURE_NEAREST_SAMPLINGMODE});return this._engine.updateTextureWrappingMode(n,h.a.TEXTURE_CLAMP_ADDRESSMODE,h.a.TEXTURE_CLAMP_ADDRESSMODE,h.a.TEXTURE_CLAMP_ADDRESSMODE),this._engine.updateTextureSamplingMode(h.a.TEXTURE_TRILINEAR_SAMPLINGMODE,n,!0),n},r.prototype._prefilterInternal=function(t){var e=t.getSize().width,n=Math.round($.a.Log2(e))+1,i=this._effectWrapper.effect,o=this._createRenderTarget(e);this._effectRenderer.setViewport();var a=t.getInternalTexture();a&&this._engine.updateTextureSamplingMode(h.a.TEXTURE_TRILINEAR_SAMPLINGMODE,a,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);var s=[[new u.e(0,0,-1),new u.e(0,-1,0),new u.e(1,0,0)],[new u.e(0,0,1),new u.e(0,-1,0),new u.e(-1,0,0)],[new u.e(1,0,0),new u.e(0,0,1),new u.e(0,1,0)],[new u.e(1,0,0),new u.e(0,0,-1),new u.e(0,-1,0)],[new u.e(1,0,0),new u.e(0,-1,0),new u.e(0,0,1)],[new u.e(-1,0,0),new u.e(0,-1,0),new u.e(0,0,-1)]];i.setFloat("hdrScale",this.hdrScale),i.setFloat2("vFilteringInfo",t.getSize().width,n),i.setTexture("inputTexture",t);for(var d=0;d<6;d++){i.setVector3("up",s[d][0]),i.setVector3("right",s[d][1]),i.setVector3("front",s[d][2]);for(var p=0;p=2&&this._prefilterOnLoad){var i=this._onLoad,o=new th(n);this._onLoad=function(){o.prefilter(e,i)}}this._texture=n.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,h.a.TEXTUREFORMAT_RGB,n.getCaps().textureFloat?h.a.TEXTURETYPE_FLOAT:h.a.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,function(a){e.lodGenerationOffset=0,e.lodGenerationScale=.8;var s=Ju.GetCubeMapTextureData(a,e._size);if(e._generateHarmonics){var d=Xo.ConvertCubeMapToSphericalPolynomial(s);e.sphericalPolynomial=d}for(var p=[],y=null,P=0;P<6;P++){if(!n.getCaps().textureFloat){var O=new ArrayBuffer(e._size*e._size*3);y=new Uint8Array(O)}var U=s[t._facesMapping[P]];if(e.gammaSpace||y){for(var F=0;F255){var ce=255/se;z*=ce,J*=ce,ie*=ce}y[3*F+0]=z,y[3*F+1]=J,y[3*F+2]=ie}}y?p.push(y):p.push(U)}return p},null,this._onLoad,this._onError)},t.prototype.clone=function(){var e=new t(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},t.prototype.delayLoad=function(){this.delayLoadState===h.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=h.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},t.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},t.prototype.setReflectionTextureMatrix=function(e){var n,i=this;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&((n=this.getScene())===null||n===void 0||n.markAllMaterialsAsDirty(h.a.MATERIAL_TextureDirtyFlag,function(o){return o.getActiveTextures().indexOf(i)!==-1}))},t.Parse=function(e,n,i){var o=null;return e.name&&!e.isRenderTarget&&((o=new t(i+e.name,n,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,o.hasAlpha=e.hasAlpha,o.level=e.level,o.coordinatesMode=e.coordinatesMode,o.isBlocking=e.isBlocking),o&&(e.boundingBoxPosition&&(o.boundingBoxPosition=u.e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(o.boundingBoxSize=u.e.FromArray(e.boundingBoxSize)),e.rotationY&&(o.rotationY=e.rotationY)),o},t.prototype.serialize=function(){if(!this.name)return null;var 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},t._facesMapping=["right","left","up","down","front","back"],t}(zn.a);R.a.RegisteredTypes["BABYLON.HDRCubeTexture"]=la;var nh=function(){function r(t,e,n){e===void 0&&(e=0),n===void 0&&(n=null),this.name=t,this.animations=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new x.c,this._onDataLayoutChanged=new x.c,this._animationPropertiesOverride=null,this._scene=n||te.a.LastCreatedScene,this.influence=e,this._scene&&(this._uniqueId=this._scene.getUniqueId())}return Object.defineProperty(r.prototype,"influence",{get:function(){return this._influence},set:function(t){if(this._influence!==t){var e=this._influence;this._influence=t,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(e===0||t===0)}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(t){this._animationPropertiesOverride=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"hasUVs",{get:function(){return!!this._uvs},enumerable:!1,configurable:!0}),r.prototype.setPositions=function(t){var e=this.hasPositions;this._positions=t,e!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)},r.prototype.getPositions=function(){return this._positions},r.prototype.setNormals=function(t){var e=this.hasNormals;this._normals=t,e!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)},r.prototype.getNormals=function(){return this._normals},r.prototype.setTangents=function(t){var e=this.hasTangents;this._tangents=t,e!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)},r.prototype.getTangents=function(){return this._tangents},r.prototype.setUVs=function(t){var e=this.hasUVs;this._uvs=t,e!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)},r.prototype.getUVs=function(){return this._uvs},r.prototype.clone=function(){var t=this,e=L.a.Clone(function(){return new r(t.name,t.influence,t._scene)},this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e},r.prototype.serialize=function(){var t={};return t.name=this.name,t.influence=this.influence,t.positions=Array.prototype.slice.call(this.getPositions()),this.id!=null&&(t.id=this.id),this.hasNormals&&(t.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(t.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(t.uvs=Array.prototype.slice.call(this.getUVs())),L.a.AppendSerializedAnimations(this,t),t},r.prototype.getClassName=function(){return"MorphTarget"},r.Parse=function(t){var e=new r(t.name,t.influence);if(e.setPositions(t.positions),t.id!=null&&(e.id=t.id),t.normals&&e.setNormals(t.normals),t.tangents&&e.setTangents(t.tangents),t.uvs&&e.setUVs(t.uvs),t.animations)for(var n=0;n=0&&(this._targets.splice(e,1),t.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(e,1)[0]),t._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(e,1)[0]),this._syncActiveTargets(!0))},r.prototype.clone=function(){for(var t=new r(this._scene),e=0,n=this._targets;e-1&&this._impostors.splice(e,1).length&&this.getPhysicsPlugin().removePhysicsBody(t)},r.prototype.addJoint=function(t,e,n){var i={mainImpostor:t,connectedImpostor:e,joint:n};n.physicsPlugin=this._physicsPlugin,this._joints.push(i),this._physicsPlugin.generateJoint(i)},r.prototype.removeJoint=function(t,e,n){var i=this._joints.filter(function(o){return o.connectedImpostor===e&&o.joint===n&&o.mainImpostor===t});i.length&&this._physicsPlugin.removeJoint(i[0])},r.prototype._step=function(t){var e=this;this._impostors.forEach(function(n){n.isBodyInitRequired()&&e._physicsPlugin.generatePhysicsBody(n)}),t>.1?t=.1:t<=0&&(t=1/60),this._physicsPlugin.executeStep(t,this._impostors)},r.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},r.prototype.getImpostors=function(){return this._impostors},r.prototype.getImpostorForPhysicsObject=function(t){for(var e=0;e0&&(this._physicsBodysToRemoveAfterStep.forEach(function(e){t.world.remove(e)}),this._physicsBodysToRemoveAfterStep=[])},r.prototype.applyImpulse=function(t,e,n){var i=new this.BJSCANNON.Vec3(n.x,n.y,n.z),o=new this.BJSCANNON.Vec3(e.x,e.y,e.z);t.physicsBody.applyImpulse(o,i)},r.prototype.applyForce=function(t,e,n){var i=new this.BJSCANNON.Vec3(n.x,n.y,n.z),o=new this.BJSCANNON.Vec3(e.x,e.y,e.z);t.physicsBody.applyForce(o,i)},r.prototype.generatePhysicsBody=function(t){if(this._removeMarkedPhysicsBodiesFromWorld(),t.parent)t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate());else{if(t.isBodyInitRequired()){var e=this._createShape(t),n=t.physicsBody;n&&this.removePhysicsBody(t);var i=this._addMaterial("mat-"+t.uniqueId,t.getParam("friction"),t.getParam("restitution")),o={mass:t.getParam("mass"),material:i},a=t.getParam("nativeOptions");for(var s in a)a.hasOwnProperty(s)&&(o[s]=a[s]);t.physicsBody=new this.BJSCANNON.Body(o),t.physicsBody.addEventListener("collide",t.onCollide),this.world.addEventListener("preStep",t.beforeStep),this.world.addEventListener("postStep",t.afterStep),t.physicsBody.addShape(e),this.world.add(t.physicsBody),n&&["force","torque","velocity","angularVelocity"].forEach(function(d){var p=n[d];t.physicsBody[d].set(p.x,p.y,p.z)}),this._processChildMeshes(t)}this._updatePhysicsBodyTransformation(t)}},r.prototype._processChildMeshes=function(t){var e=this,n=t.object.getChildMeshes?t.object.getChildMeshes(!0):[],i=t.object.rotationQuaternion;if(n.length){var o=function(a){if(i&&a.rotationQuaternion){var s=a.getPhysicsImpostor();if(s&&s.parent!==t){var d=a.getAbsolutePosition().subtract(a.parent.getAbsolutePosition()),p=a.rotationQuaternion;s.physicsBody&&(e.removePhysicsBody(s),s.physicsBody=null),s.parent=t,s.resetUpdateFlags(),t.physicsBody.addShape(e._createShape(s),new e.BJSCANNON.Vec3(d.x,d.y,d.z),new e.BJSCANNON.Quaternion(p.x,p.y,p.z,p.w)),t.physicsBody.mass+=s.getParam("mass")}i.multiplyInPlace(a.rotationQuaternion),a.getChildMeshes(!0).filter(function(y){return!!y.physicsImpostor}).forEach(o)}};n.filter(function(a){return!!a.physicsImpostor}).forEach(o)}},r.prototype.removePhysicsBody=function(t){t.physicsBody.removeEventListener("collide",t.onCollide),this.world.removeEventListener("preStep",t.beforeStep),this.world.removeEventListener("postStep",t.afterStep),this._physicsBodysToRemoveAfterStep.indexOf(t.physicsBody)===-1&&this._physicsBodysToRemoveAfterStep.push(t.physicsBody)},r.prototype.generateJoint=function(t){var e=t.mainImpostor.physicsBody,n=t.connectedImpostor.physicsBody;if(e&&n){var i,o=t.joint.jointData,a={pivotA:o.mainPivot?new this.BJSCANNON.Vec3().set(o.mainPivot.x,o.mainPivot.y,o.mainPivot.z):null,pivotB:o.connectedPivot?new this.BJSCANNON.Vec3().set(o.connectedPivot.x,o.connectedPivot.y,o.connectedPivot.z):null,axisA:o.mainAxis?new this.BJSCANNON.Vec3().set(o.mainAxis.x,o.mainAxis.y,o.mainAxis.z):null,axisB:o.connectedAxis?new this.BJSCANNON.Vec3().set(o.connectedAxis.x,o.connectedAxis.y,o.connectedAxis.z):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(t.joint.type){case en.e.HingeJoint:case en.e.Hinge2Joint:i=new this.BJSCANNON.HingeConstraint(e,n,a);break;case en.e.DistanceJoint:i=new this.BJSCANNON.DistanceConstraint(e,n,o.maxDistance||2);break;case en.e.SpringJoint:var s=o;i=new this.BJSCANNON.Spring(e,n,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:a.pivotA,localAnchorB:a.pivotB});break;case en.e.LockJoint:i=new this.BJSCANNON.LockConstraint(e,n,a);break;case en.e.PointToPointJoint:case en.e.BallAndSocketJoint:default:i=new this.BJSCANNON.PointToPointConstraint(e,a.pivotA,n,a.pivotB,a.maxForce)}i.collideConnected=!!o.collision,t.joint.physicsJoint=i,t.joint.type!==en.e.SpringJoint?this.world.addConstraint(i):(t.joint.jointData.forceApplicationCallback=t.joint.jointData.forceApplicationCallback||function(){i.applyForce()},t.mainImpostor.registerAfterPhysicsStep(t.joint.jointData.forceApplicationCallback))}},r.prototype.removeJoint=function(t){t.joint.type!==en.e.SpringJoint?this.world.removeConstraint(t.joint.physicsJoint):t.mainImpostor.unregisterAfterPhysicsStep(t.joint.jointData.forceApplicationCallback)},r.prototype._addMaterial=function(t,e,n){var i,o;for(i=0;i1e3*n));d++);this.time+=i;for(var p=this.time%n/n,y=t,P=this.bodies,O=0;O!==P.length;O++){var U=P[O];U.type!==e.Body.STATIC&&U.sleepState!==e.Body.SLEEPING?(U.position.vsub(U.previousPosition,y),y.scale(p,y),U.position.vadd(y,U.interpolatedPosition)):(U.interpolatedPosition.set(U.position.x,U.position.y,U.position.z),U.interpolatedQuaternion.set(U.quaternion.x,U.quaternion.y,U.quaternion.z,U.quaternion.w))}}}},r.prototype.raycast=function(t,e){return this._cannonRaycastResult.reset(),this.world.raycastClosest(t,e,{},this._cannonRaycastResult),this._raycastResult.reset(t,e),this._cannonRaycastResult.hasHit&&(this._raycastResult.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}),this._raycastResult.setHitDistance(this._cannonRaycastResult.distance)),this._raycastResult},r}();Mr.DefaultPluginFactory=function(){return new $s};var ih=function(){function r(t,e,n){t===void 0&&(t=!0),n===void 0&&(n=OIMO),this._useDeltaForWorldStep=t,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=u.e.Zero(),this.BJSOIMO=n,this.world=new this.BJSOIMO.World({iterations:e}),this.world.clear(),this._raycastResult=new Js}return r.prototype.setGravity=function(t){this.world.gravity.set(t.x,t.y,t.z)},r.prototype.setTimeStep=function(t){this.world.timeStep=t},r.prototype.getTimeStep=function(){return this.world.timeStep},r.prototype.executeStep=function(t,e){var n=this;e.forEach(function(s){s.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?t:this._fixedTimeStep,this.world.step(),e.forEach(function(s){s.afterStep(),n._tmpImpostorsArray[s.uniqueId]=s});for(var i=this.world.contacts;i!==null;)if(!i.touching||i.body1.sleeping||i.body2.sleeping){var o=this._tmpImpostorsArray[+i.body1.name],a=this._tmpImpostorsArray[+i.body2.name];o&&a&&(o.onCollide({body:a.physicsBody,point:null}),a.onCollide({body:o.physicsBody,point:null})),i=i.next}else i=i.next},r.prototype.applyImpulse=function(t,e,n){var i=t.physicsBody.mass;t.physicsBody.applyImpulse(n.scale(this.world.invScale),e.scale(this.world.invScale*i))},r.prototype.applyForce=function(t,e,n){l.a.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,e,n)},r.prototype.generatePhysicsBody=function(t){var e=this;if(t.parent)t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate());else{if(t.isBodyInitRequired()){var n={name:t.uniqueId,config:[t.getParam("mass")||.001,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:t.getParam("mass")!==0,density:t.getParam("mass"),friction:t.getParam("friction"),restitution:t.getParam("restitution"),world:this.world},i=[t];(s=t.object).getChildMeshes&&s.getChildMeshes().forEach(function(d){d.physicsImpostor&&i.push(d.physicsImpostor)});var o=function(d){return Math.max(d,Mr.Epsilon)},a=new u.b;i.forEach(function(d){if(d.object.rotationQuaternion){var p=d.object.rotationQuaternion;a.copyFrom(p),d.object.rotationQuaternion.set(0,0,0,1),d.object.computeWorldMatrix(!0);var y=a.toEulerAngles(),P=d.getObjectExtendSize();if(d===t){var O=t.getObjectCenter();t.object.getAbsolutePivotPoint().subtractToRef(O,e._tmpPositionVector),e._tmpPositionVector.divideInPlace(t.object.scaling),n.pos.push(O.x),n.pos.push(O.y),n.pos.push(O.z),n.posShape.push(0,0,0),n.rotShape.push(0,0,0)}else{var U=d.object.position.clone();n.posShape.push(U.x),n.posShape.push(U.y),n.posShape.push(U.z),n.rotShape.push(57.29577951308232*y.x,57.29577951308232*y.y,57.29577951308232*y.z)}switch(d.object.rotationQuaternion.copyFrom(a),d.type){case Ct.a.ParticleImpostor:l.a.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Ct.a.SphereImpostor:var F=P.x,z=P.y,J=P.z,ie=Math.max(o(F),o(z),o(J))/2;n.type.push("sphere"),n.size.push(ie),n.size.push(ie),n.size.push(ie);break;case Ct.a.CylinderImpostor:var se=o(P.x)/2,ce=o(P.y);n.type.push("cylinder"),n.size.push(se),n.size.push(ce),n.size.push(ce);break;case Ct.a.PlaneImpostor:case Ct.a.BoxImpostor:default:se=o(P.x),ce=o(P.y);var ue=o(P.z);n.type.push("box"),n.size.push(se),n.size.push(ce),n.size.push(ue)}d.object.rotationQuaternion=p}}),t.physicsBody=this.world.add(n),t.physicsBody.resetQuaternion(a),t.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);var s;t.setDeltaPosition(this._tmpPositionVector)}},r.prototype.removePhysicsBody=function(t){this.world.removeRigidBody(t.physicsBody)},r.prototype.generateJoint=function(t){var e=t.mainImpostor.physicsBody,n=t.connectedImpostor.physicsBody;if(e&&n){var i,o=t.joint.jointData,a=o.nativeParams||{},s={body1:e,body2:n,axe1:a.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:a.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:a.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:a.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:a.min,max:a.max,collision:a.collision||o.collision,spring:a.spring,world:this.world};switch(t.joint.type){case en.e.BallAndSocketJoint:i="jointBall";break;case en.e.SpringJoint:l.a.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var d=o;s.min=d.length||s.min,s.max=Math.max(s.min,s.max);case en.e.DistanceJoint:i="jointDistance",s.max=o.maxDistance;break;case en.e.PrismaticJoint:i="jointPrisme";break;case en.e.SliderJoint:i="jointSlide";break;case en.e.WheelJoint:i="jointWheel";break;case en.e.HingeJoint:default:i="jointHinge"}s.type=i,t.joint.physicsJoint=this.world.add(s)}},r.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(e){l.a.Warn(e)}},r.prototype.isSupported=function(){return this.BJSOIMO!==void 0},r.prototype.setTransformationFromPhysicsBody=function(t){if(!t.physicsBody.sleeping){if(t.physicsBody.shapes.next){for(var e=t.physicsBody.shapes;e.next;)e=e.next;t.object.position.set(e.position.x,e.position.y,e.position.z)}else{var n=t.physicsBody.getPosition();t.object.position.set(n.x,n.y,n.z)}if(t.object.rotationQuaternion){var i=t.physicsBody.getQuaternion();t.object.rotationQuaternion.set(i.x,i.y,i.z,i.w)}}},r.prototype.setPhysicsBodyTransformation=function(t,e,n){var i=t.physicsBody;t.physicsBody.shapes.next||(i.position.set(e.x,e.y,e.z),i.orientation.set(n.x,n.y,n.z,n.w),i.syncShapes(),i.awake())},r.prototype.setLinearVelocity=function(t,e){t.physicsBody.linearVelocity.set(e.x,e.y,e.z)},r.prototype.setAngularVelocity=function(t,e){t.physicsBody.angularVelocity.set(e.x,e.y,e.z)},r.prototype.getLinearVelocity=function(t){var e=t.physicsBody.linearVelocity;return e?new u.e(e.x,e.y,e.z):null},r.prototype.getAngularVelocity=function(t){var e=t.physicsBody.angularVelocity;return e?new u.e(e.x,e.y,e.z):null},r.prototype.setBodyMass=function(t,e){var n=e===0;t.physicsBody.shapes.density=n?1:e,t.physicsBody.setupMass(n?2:1)},r.prototype.getBodyMass=function(t){return t.physicsBody.shapes.density},r.prototype.getBodyFriction=function(t){return t.physicsBody.shapes.friction},r.prototype.setBodyFriction=function(t,e){t.physicsBody.shapes.friction=e},r.prototype.getBodyRestitution=function(t){return t.physicsBody.shapes.restitution},r.prototype.setBodyRestitution=function(t,e){t.physicsBody.shapes.restitution=e},r.prototype.sleepBody=function(t){t.physicsBody.sleep()},r.prototype.wakeUpBody=function(t){t.physicsBody.awake()},r.prototype.updateDistanceJoint=function(t,e,n){t.physicsJoint.limitMotor.upperLimit=e,n!==void 0&&(t.physicsJoint.limitMotor.lowerLimit=n)},r.prototype.setMotor=function(t,e,n,i){n!==void 0?l.a.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):n=1e6,e*=-1;var o=i?t.physicsJoint.rotationalLimitMotor2:t.physicsJoint.rotationalLimitMotor1||t.physicsJoint.rotationalLimitMotor||t.physicsJoint.limitMotor;o&&o.setMotor(e,n)},r.prototype.setLimit=function(t,e,n,i){var o=i?t.physicsJoint.rotationalLimitMotor2:t.physicsJoint.rotationalLimitMotor1||t.physicsJoint.rotationalLimitMotor||t.physicsJoint.limitMotor;o&&o.setLimit(e,n===void 0?-e:n)},r.prototype.syncMeshWithImpostor=function(t,e){var n=e.physicsBody;t.position.x=n.position.x,t.position.y=n.position.y,t.position.z=n.position.z,t.rotationQuaternion&&(t.rotationQuaternion.x=n.orientation.x,t.rotationQuaternion.y=n.orientation.y,t.rotationQuaternion.z=n.orientation.z,t.rotationQuaternion.w=n.orientation.s)},r.prototype.getRadius=function(t){return t.physicsBody.shapes.radius},r.prototype.getBoxSizeToRef=function(t,e){var n=t.physicsBody.shapes;e.x=2*n.halfWidth,e.y=2*n.halfHeight,e.z=2*n.halfDepth},r.prototype.dispose=function(){this.world.clear()},r.prototype.raycast=function(t,e){return l.a.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(t,e),this._raycastResult},r}(),ha=f(97),rh=function(){function r(t,e,n){var i=this;t===void 0&&(t=!0),e===void 0&&(e=Ammo),n===void 0&&(n=null),this._useDeltaForWorldStep=t,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new u.b,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new u.e,this._tmpMatrix=new u.a,typeof e=="function"?e(this.bjsAMMO):this.bjsAMMO=e,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=n||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=function(o,a,s,d){var p=(o=i.bjsAMMO.wrapPointer(o,Ammo.btManifoldPoint)).getPositionWorldOnA();i._tmpContactPoint.x=p.x(),i._tmpContactPoint.y=p.y(),i._tmpContactPoint.z=p.z(),i._tmpContactCallbackResult=!0},this._raycastResult=new Js,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)):l.a.Error("AmmoJS is not available. Please make sure you included the js file.")}return r.prototype.setGravity=function(t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)},r.prototype.setTimeStep=function(t){this._timeStep=t},r.prototype.setFixedTimeStep=function(t){this._fixedTimeStep=t},r.prototype.setMaxSteps=function(t){this._maxSteps=t},r.prototype.getTimeStep=function(){return this._timeStep},r.prototype._isImpostorInContact=function(t){return this._tmpContactCallbackResult=!1,this.world.contactTest(t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},r.prototype._isImpostorPairInContact=function(t,e){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(t.physicsBody,e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},r.prototype._stepSimulation=function(t,e,n){if(t===void 0&&(t=1/60),e===void 0&&(e=10),n===void 0&&(n=1/60),e==0)this.world.stepSimulation(t,0);else for(;e>0&&t>0;)t-n0&&this._isImpostorInContact(d))for(var p=0,y=d._onPhysicsCollideCallbacks;p3?3:d;var p=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,n-1,d);return p.get_m_cfg().set_collisions(17),p},r.prototype._createCustom=function(t){var e=null;return this.onCreateCustomShape&&(e=this.onCreateCustomShape(t)),e==null&&(e=new this.bjsAMMO.btCompoundShape),e},r.prototype._addHullVerts=function(t,e,n){var i=this,o=0;if(n&&n.getIndices&&n.getWorldMatrix&&n.getChildMeshes){var a=n.getIndices();a||(a=[]);var s=n.getVerticesData(Me.b.PositionKind);s||(s=[]),n.computeWorldMatrix(!1);for(var d=a.length/3,p=0;p0){if(t.type!=Ct.a.NoImpostor){var p=this._createShape(t,!0);p&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,p))}return i}this.bjsAMMO.destroy(i),i=null}switch(t.type){case Ct.a.SphereImpostor:if($.a.WithinEpsilon(a.x,a.y,1e-4)&&$.a.WithinEpsilon(a.x,a.z,1e-4))i=new this.bjsAMMO.btSphereShape(a.x/2);else{var y=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(y,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(a.x/2,a.y/2,a.z/2))}break;case Ct.a.CapsuleImpostor:i=new this.bjsAMMO.btCapsuleShape(a.x/2,a.y/2);break;case Ct.a.CylinderImpostor:this._tmpAmmoVectorA.setValue(a.x/2,a.y/2,a.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Ct.a.PlaneImpostor:case Ct.a.BoxImpostor:this._tmpAmmoVectorA.setValue(a.x/2,a.y/2,a.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Ct.a.MeshImpostor:if(t.getParam("mass")==0){var P=new this.bjsAMMO.btTriangleMesh;t._pluginData.toDispose.push(P);var O=this._addMeshVerts(P,o,o);i=O==0?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(P);break}case Ct.a.ConvexHullImpostor:var U=new this.bjsAMMO.btConvexHullShape;(O=this._addHullVerts(U,o,o))==0?(t._pluginData.toDispose.push(U),i=new this.bjsAMMO.btCompoundShape):i=U;break;case Ct.a.NoImpostor:i=new this.bjsAMMO.btSphereShape(a.x/2);break;case Ct.a.CustomImpostor:i=this._createCustom(t);break;case Ct.a.SoftbodyImpostor:i=this._createSoftbody(t);break;case Ct.a.ClothImpostor:i=this._createCloth(t);break;case Ct.a.RopeImpostor:i=this._createRope(t);break;default:l.a.Warn("The impostor type is not currently supported by the ammo plugin.")}return i},r.prototype.setTransformationFromPhysicsBody=function(t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),t.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),t.object.rotationQuaternion?t.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):t.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(t.object.rotation))},r.prototype.setPhysicsBodyTransformation=function(t,e,n){var i=t.physicsBody.getWorldTransform();if(Math.abs(i.getOrigin().x()-e.x)>Gt.a||Math.abs(i.getOrigin().y()-e.y)>Gt.a||Math.abs(i.getOrigin().z()-e.z)>Gt.a||Math.abs(i.getRotation().x()-n.x)>Gt.a||Math.abs(i.getRotation().y()-n.y)>Gt.a||Math.abs(i.getRotation().z()-n.z)>Gt.a||Math.abs(i.getRotation().w()-n.w)>Gt.a)if(this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),i.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(n.x,n.y,n.z,n.w),i.setRotation(this._tmpAmmoQuaternion),t.physicsBody.setWorldTransform(i),t.mass==0){var o=t.physicsBody.getMotionState();o&&o.setWorldTransform(i)}else t.physicsBody.activate()},r.prototype.isSupported=function(){return this.bjsAMMO!==void 0},r.prototype.setLinearVelocity=function(t,e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),t.soft?t.physicsBody.linearVelocity(this._tmpAmmoVectorA):t.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)},r.prototype.setAngularVelocity=function(t,e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),t.soft?t.physicsBody.angularVelocity(this._tmpAmmoVectorA):t.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)},r.prototype.getLinearVelocity=function(t){if(t.soft)var e=t.physicsBody.linearVelocity();else e=t.physicsBody.getLinearVelocity();if(!e)return null;var n=new u.e(e.x(),e.y(),e.z());return this.bjsAMMO.destroy(e),n},r.prototype.getAngularVelocity=function(t){if(t.soft)var e=t.physicsBody.angularVelocity();else e=t.physicsBody.getAngularVelocity();if(!e)return null;var n=new u.e(e.x(),e.y(),e.z());return this.bjsAMMO.destroy(e),n},r.prototype.setBodyMass=function(t,e){t.soft?t.physicsBody.setTotalMass(e,!1):t.physicsBody.setMassProps(e),t._pluginData.mass=e},r.prototype.getBodyMass=function(t){return t._pluginData.mass||0},r.prototype.getBodyFriction=function(t){return t._pluginData.friction||0},r.prototype.setBodyFriction=function(t,e){t.soft?t.physicsBody.get_m_cfg().set_kDF(e):t.physicsBody.setFriction(e),t._pluginData.friction=e},r.prototype.getBodyRestitution=function(t){return t._pluginData.restitution||0},r.prototype.setBodyRestitution=function(t,e){t.physicsBody.setRestitution(e),t._pluginData.restitution=e},r.prototype.getBodyPressure=function(t){return t.soft?t._pluginData.pressure||0:(l.a.Warn("Pressure is not a property of a rigid body"),0)},r.prototype.setBodyPressure=function(t,e){t.soft?t.type===Ct.a.SoftbodyImpostor?(t.physicsBody.get_m_cfg().set_kPR(e),t._pluginData.pressure=e):(t.physicsBody.get_m_cfg().set_kPR(0),t._pluginData.pressure=0):l.a.Warn("Pressure can only be applied to a softbody")},r.prototype.getBodyStiffness=function(t){return t.soft?t._pluginData.stiffness||0:(l.a.Warn("Stiffness is not a property of a rigid body"),0)},r.prototype.setBodyStiffness=function(t,e){t.soft?(e=(e=e<0?0:e)>1?1:e,t.physicsBody.get_m_materials().at(0).set_m_kLST(e),t._pluginData.stiffness=e):l.a.Warn("Stiffness cannot be applied to a rigid body")},r.prototype.getBodyVelocityIterations=function(t){return t.soft?t._pluginData.velocityIterations||0:(l.a.Warn("Velocity iterations is not a property of a rigid body"),0)},r.prototype.setBodyVelocityIterations=function(t,e){t.soft?(e=e<0?0:e,t.physicsBody.get_m_cfg().set_viterations(e),t._pluginData.velocityIterations=e):l.a.Warn("Velocity iterations cannot be applied to a rigid body")},r.prototype.getBodyPositionIterations=function(t){return t.soft?t._pluginData.positionIterations||0:(l.a.Warn("Position iterations is not a property of a rigid body"),0)},r.prototype.setBodyPositionIterations=function(t,e){t.soft?(e=e<0?0:e,t.physicsBody.get_m_cfg().set_piterations(e),t._pluginData.positionIterations=e):l.a.Warn("Position iterations cannot be applied to a rigid body")},r.prototype.appendAnchor=function(t,e,n,i,o,a){o===void 0&&(o=1),a===void 0&&(a=!1);var s=t.segments,d=Math.round((s-1)*n)+s*(s-1-Math.round((s-1)*i));t.physicsBody.appendAnchor(d,e.physicsBody,a,o)},r.prototype.appendHook=function(t,e,n,i,o){i===void 0&&(i=1),o===void 0&&(o=!1);var a=Math.round(t.segments*n);t.physicsBody.appendAnchor(a,e.physicsBody,o,i)},r.prototype.sleepBody=function(t){l.a.Warn("sleepBody is not currently supported by the Ammo physics plugin")},r.prototype.wakeUpBody=function(t){t.physicsBody.activate()},r.prototype.updateDistanceJoint=function(t,e,n){l.a.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")},r.prototype.setMotor=function(t,e,n,i){t.physicsJoint.enableAngularMotor(!0,e,n)},r.prototype.setLimit=function(t,e,n){l.a.Warn("setLimit is not currently supported by the Ammo physics plugin")},r.prototype.syncMeshWithImpostor=function(t,e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),t.position.x=this._tmpAmmoTransform.getOrigin().x(),t.position.y=this._tmpAmmoTransform.getOrigin().y(),t.position.z=this._tmpAmmoTransform.getOrigin().z(),t.rotationQuaternion&&(t.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),t.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),t.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),t.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())},r.prototype.getRadius=function(t){return t.getObjectExtendSize().x/2},r.prototype.getBoxSizeToRef=function(t,e){var n=t.getObjectExtendSize();e.x=n.x,e.y=n.y,e.z=n.z},r.prototype.dispose=function(){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},r.prototype.raycast=function(t,e){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(t.x,t.y,t.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(e.x,e.y,e.z);var n=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);return this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,n),this._raycastResult.reset(t,e),n.hasHit()&&(this._raycastResult.setHitData({x:n.get_m_hitNormalWorld().x(),y:n.get_m_hitNormalWorld().y(),z:n.get_m_hitNormalWorld().z()},{x:n.get_m_hitPointWorld().x(),y:n.get_m_hitPointWorld().y(),z:n.get_m_hitPointWorld().z()}),this._raycastResult.calculateHitDistance()),this.bjsAMMO.destroy(n),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB),this._raycastResult},r.DISABLE_COLLISION_FLAG=4,r.KINEMATIC_FLAG=2,r.DISABLE_DEACTIVATION_FLAG=4,r}();B.a.prototype.removeReflectionProbe=function(r){if(!this.reflectionProbes)return-1;var t=this.reflectionProbes.indexOf(r);return t!==-1&&this.reflectionProbes.splice(t,1),t},B.a.prototype.addReflectionProbe=function(r){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(r)};var oh=function(){function r(t,e,n,i,o){var a=this;i===void 0&&(i=!0),o===void 0&&(o=!1),this.name=t,this._viewMatrix=u.a.Identity(),this._target=u.e.Zero(),this._add=u.e.Zero(),this._invertYAxis=!1,this.position=u.e.Zero(),this._scene=n,this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this);var s=h.a.TEXTURETYPE_UNSIGNED_BYTE;if(o){var d=this._scene.getEngine().getCaps();d.textureHalfFloatRender?s=h.a.TEXTURETYPE_HALF_FLOAT:d.textureFloatRender&&(s=h.a.TEXTURETYPE_FLOAT)}this._renderTargetTexture=new sn(t,e,n,i,!0,s,!0),this._renderTargetTexture.onBeforeRenderObservable.add(function(p){switch(p){case 0:a._add.copyFromFloats(1,0,0);break;case 1:a._add.copyFromFloats(-1,0,0);break;case 2:a._add.copyFromFloats(0,a._invertYAxis?1:-1,0);break;case 3:a._add.copyFromFloats(0,a._invertYAxis?-1:1,0);break;case 4:a._add.copyFromFloats(0,0,1);break;case 5:a._add.copyFromFloats(0,0,-1)}a._attachedMesh&&a.position.copyFrom(a._attachedMesh.getAbsolutePosition()),a.position.addToRef(a._add,a._target),u.a.LookAtLHToRef(a.position,a._target,u.e.Up(),a._viewMatrix),n.activeCamera&&(a._projectionMatrix=u.a.PerspectiveFovLH(Math.PI/2,1,n.activeCamera.minZ,n.activeCamera.maxZ),n.setTransformMatrix(a._viewMatrix,a._projectionMatrix)),n._forcedViewPosition=a.position}),this._renderTargetTexture.onAfterUnbindObservable.add(function(){n._forcedViewPosition=null,n.updateTransformMatrix(!0)})}return Object.defineProperty(r.prototype,"samples",{get:function(){return this._renderTargetTexture.samples},set:function(t){this._renderTargetTexture.samples=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(t){this._renderTargetTexture.refreshRate=t},enumerable:!1,configurable:!0}),r.prototype.getScene=function(){return this._scene},Object.defineProperty(r.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},enumerable:!1,configurable:!0}),r.prototype.attachToMesh=function(t){this._attachedMesh=t},r.prototype.setRenderingAutoClearDepthStencil=function(t,e){this._renderTargetTexture.setRenderingAutoClearDepthStencil(t,e)},r.prototype.dispose=function(){var t=this._scene.reflectionProbes.indexOf(this);t!==-1&&this._scene.reflectionProbes.splice(t,1),this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null)},r.prototype.toString=function(t){var e="Name: "+this.name;return t&&(e+=", position: "+this.position.toString(),this._attachedMesh&&(e+=", attached mesh: "+this._attachedMesh.name)),e},r.prototype.getClassName=function(){return"ReflectionProbe"},r.prototype.serialize=function(){var t=L.a.Serialize(this,this._renderTargetTexture.serialize());return t.isReflectionProbe=!0,t},r.Parse=function(t,e,n){var i=null;if(e.reflectionProbes)for(var o=0;o0){var n=t._waitingData.lods.ids,i=e.isEnabled(!1);if(t._waitingData.lods.distances){var o=t._waitingData.lods.distances;if(o.length>=n.length){var a=o.length>n.length?o[o.length-1]:0;e.setEnabled(!1);for(var s=0;s0&&e.addLODLevel(a,null),i===!0&&e.setEnabled(!0)}else Ye.b.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},ch=function(r,t,e,n,i){i===void 0&&(i=!1);var o=new An(r),a="importScene has failed JSON parse";try{var s=JSON.parse(t);a="";var d,p,y=Ut.loggingLevel===Ut.DETAILED_LOGGING;if(s.environmentTexture!==void 0&&s.environmentTexture!==null){var P=s.isPBR===void 0||s.isPBR;if(s.environmentTextureType&&s.environmentTextureType==="BABYLON.HDRCubeTexture"){var O=s.environmentTextureSize?s.environmentTextureSize:128,U=new la((s.environmentTexture.match(/https?:\/\//g)?"":e)+s.environmentTexture,r,O,!0,!P);s.environmentTextureRotationY&&(U.rotationY=s.environmentTextureRotationY),r.environmentTexture=U}else if(Xn.a.EndsWith(s.environmentTexture,".env")){var F=new ni((s.environmentTexture.match(/https?:\/\//g)?"":e)+s.environmentTexture,r);s.environmentTextureRotationY&&(F.rotationY=s.environmentTextureRotationY),r.environmentTexture=F}else{var z=ni.CreateFromPrefilteredData((s.environmentTexture.match(/https?:\/\//g)?"":e)+s.environmentTexture,r);s.environmentTextureRotationY&&(z.rotationY=s.environmentTextureRotationY),r.environmentTexture=z}if(s.createDefaultSkybox===!0){var J=r.activeCamera!==void 0&&r.activeCamera!==null?(r.activeCamera.maxZ-r.activeCamera.minZ)/2:1e3,ie=s.skyboxBlurLevel||0;r.createDefaultSkybox(r.environmentTexture,P,J,ie)}o.environmentTexture=r.environmentTexture}if(s.environmentIntensity!==void 0&&s.environmentIntensity!==null&&(r.environmentIntensity=s.environmentIntensity),s.lights!==void 0&&s.lights!==null)for(d=0,p=s.lights.length;d0){for(var $t=0;$t0){for(var Bn=0;Bn-1&&p.skeletons!==void 0&&p.skeletons!==null&&!(z.indexOf(ie.skeletonId)>-1))for(var Le=0,xe=p.skeletons.length;Le1,this.wrapU=h.a.TEXTURE_CLAMP_ADDRESSMODE,this.wrapV=h.a.TEXTURE_CLAMP_ADDRESSMODE,this.wrapR=h.a.TEXTURE_CLAMP_ADDRESSMODE,this.anisotropicFilteringLevel=1;var o=function(s){if(typeof s=="string"){for(var d,p=null,y=null,P=s.split(` -`),O=0,U=0,F=0,z=0,J=0,ie=0;ie0&&(ie+1)%4==0)p[ie]=255;else{var Te=y[ie];p[ie]=Te/J*255}e.is3D?(e.updateSize(O,O,O),i.updateRawTexture3D(e,p,h.a.TEXTUREFORMAT_RGBA,!1)):(e.updateSize(O*O,O),i.updateRawTexture(e,p,h.a.TEXTUREFORMAT_RGBA,!1)),e.isReady=!0,n._triggerOnLoad()}},a=this.getScene();return a?a._loadFile(this.url,o):i._loadFile(this.url,o),this._texture},t.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},t.prototype.clone=function(){var e=new t(this.url,this.getScene()||this._getEngine());return e.level=this.level,e},t.prototype.delayLoad=function(){this.delayLoadState===h.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=h.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},t.Parse=function(e,n){var i=null;return e.name&&!e.isRenderTarget&&((i=new t(e.name,n)).name=e.name,i.level=e.level),i},t.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},t._noneEmptyLineRegex=/\S+/,t}(zn.a);R.a.RegisteredTypes["BABYLON.ColorGradingTexture"]=fh;var ph=function(r){function t(e,n,i,o,a,s,d){o===void 0&&(o=!1),a===void 0&&(a=!0),s===void 0&&(s=null),d===void 0&&(d=null);var p=r.call(this,n)||this;if(p._onLoad=null,p._onError=null,!e)throw new Error("Image url is not set");return p._coordinatesMode=we.a.CUBIC_MODE,p.name=e,p.url=e,p._size=i,p._noMipmap=o,p.gammaSpace=a,p._onLoad=s,p._onError=d,p.hasAlpha=!1,p.isCube=!0,p._texture=p._getFromCache(e,p._noMipmap),p._texture?s&&(p._texture.isReady?Ye.b.SetImmediate(function(){return s()}):p._texture.onLoadedObservable.add(s)):n.useDelayedTextureLoading?p.delayLoadState=h.a.DELAYLOADSTATE_NOTLOADED:p.loadImage(p.loadTexture.bind(p),p._onError),p}return Object(c.d)(t,r),t.prototype.loadImage=function(e,n){var i=this,o=document.createElement("canvas"),a=new Image;a.addEventListener("load",function(){i._width=a.width,i._height=a.height,o.width=i._width,o.height=i._height;var s=o.getContext("2d");s.drawImage(a,0,0);var d=s.getImageData(0,0,a.width,a.height);i._buffer=d.data.buffer,o.remove(),e()}),a.addEventListener("error",function(s){n&&n(i.getClassName()+" could not be loaded",s)}),a.src=this.url},t.prototype.loadTexture=function(){var e=this,n=this.getScene();n&&(this._texture=n.getEngine().createRawCubeTextureFromUrl(this.url,n,this._size,h.a.TEXTUREFORMAT_RGB,n.getEngine().getCaps().textureFloat?h.a.TEXTURETYPE_FLOAT:h.a.TEXTURETYPE_UNSIGNED_INTEGER,this._noMipmap,function(){for(var i=e.getFloat32ArrayFromArrayBuffer(e._buffer),o=Zs.ConvertPanoramaToCubemap(i,e._width,e._height,e._size),a=[],s=0;s<6;s++){var d=o[t._FacesMapping[s]];a.push(d)}return a},null,this._onLoad,this._onError))},t.prototype.getFloat32ArrayFromArrayBuffer=function(e){for(var n=new DataView(e),i=new Float32Array(3*e.byteLength/4),o=0,a=0;ae.length)l.a.Error("Unable to load TGA file - Not enough data");else{n+=i.id_length;var o,a=!1,s=!1,d=!1;switch(i.image_type){case r._TYPE_RLE_INDEXED:a=!0;case r._TYPE_INDEXED:s=!0;break;case r._TYPE_RLE_RGB:a=!0;case r._TYPE_RGB:break;case r._TYPE_RLE_GREY:a=!0;case r._TYPE_GREY:d=!0}var p,y,P,O,U,F,z,J=i.pixel_size>>3,ie=i.width*i.height*J;if(s&&(p=e.subarray(n,n+=i.colormap_length*(i.colormap_size>>3))),a){var se,ce,ue;o=new Uint8Array(ie);for(var fe=0,ve=new Uint8Array(J);n>r._ORIGIN_SHIFT){default:case r._ORIGIN_UL:y=0,O=1,z=i.width,P=0,U=1,F=i.height;break;case r._ORIGIN_BL:y=0,O=1,z=i.width,P=i.height-1,U=-1,F=-1;break;case r._ORIGIN_UR:y=i.width-1,O=-1,z=-1,P=0,U=1,F=i.height;break;case r._ORIGIN_BR:y=i.width-1,O=-1,z=-1,P=i.height-1,U=-1,F=-1}var Te=r["_getImageData"+(d?"Grey":"")+i.pixel_size+"bits"](i,p,o,P,U,F,y,O,z);t.getEngine()._uploadDataToTextureDirectly(t,Te)}}},r._getImageData8bits=function(t,e,n,i,o,a,s,d,p){var y,P,O,U=n,F=e,z=t.width,J=t.height,ie=0,se=new Uint8Array(z*J*4);for(O=i;O!==a;O+=o)for(P=s;P!==p;P+=d,ie++)y=U[ie],se[4*(P+z*O)+3]=255,se[4*(P+z*O)+2]=F[3*y+0],se[4*(P+z*O)+1]=F[3*y+1],se[4*(P+z*O)+0]=F[3*y+2];return se},r._getImageData16bits=function(t,e,n,i,o,a,s,d,p){var y,P,O,U=n,F=t.width,z=t.height,J=0,ie=new Uint8Array(F*z*4);for(O=i;O!==a;O+=o)for(P=s;P!==p;P+=d,J+=2){var se=255*((31744&(y=U[J+0]+(U[J+1]<<8)))>>10)/31|0,ce=255*((992&y)>>5)/31|0,ue=255*(31&y)/31|0;ie[4*(P+F*O)+0]=se,ie[4*(P+F*O)+1]=ce,ie[4*(P+F*O)+2]=ue,ie[4*(P+F*O)+3]=32768&y?0:255}return ie},r._getImageData24bits=function(t,e,n,i,o,a,s,d,p){var y,P,O=n,U=t.width,F=t.height,z=0,J=new Uint8Array(U*F*4);for(P=i;P!==a;P+=o)for(y=s;y!==p;y+=d,z+=3)J[4*(y+U*P)+3]=255,J[4*(y+U*P)+2]=O[z+0],J[4*(y+U*P)+1]=O[z+1],J[4*(y+U*P)+0]=O[z+2];return J},r._getImageData32bits=function(t,e,n,i,o,a,s,d,p){var y,P,O=n,U=t.width,F=t.height,z=0,J=new Uint8Array(U*F*4);for(P=i;P!==a;P+=o)for(y=s;y!==p;y+=d,z+=4)J[4*(y+U*P)+2]=O[z+0],J[4*(y+U*P)+1]=O[z+1],J[4*(y+U*P)+0]=O[z+2],J[4*(y+U*P)+3]=O[z+3];return J},r._getImageDataGrey8bits=function(t,e,n,i,o,a,s,d,p){var y,P,O,U=n,F=t.width,z=t.height,J=0,ie=new Uint8Array(F*z*4);for(O=i;O!==a;O+=o)for(P=s;P!==p;P+=d,J++)y=U[J],ie[4*(P+F*O)+0]=y,ie[4*(P+F*O)+1]=y,ie[4*(P+F*O)+2]=y,ie[4*(P+F*O)+3]=255;return ie},r._getImageDataGrey16bits=function(t,e,n,i,o,a,s,d,p){var y,P,O=n,U=t.width,F=t.height,z=0,J=new Uint8Array(U*F*4);for(P=i;P!==a;P+=o)for(y=s;y!==p;y+=d,z+=2)J[4*(y+U*P)+0]=O[z+0],J[4*(y+U*P)+1]=O[z+0],J[4*(y+U*P)+2]=O[z+0],J[4*(y+U*P)+3]=O[z+1];return J},r._TYPE_INDEXED=1,r._TYPE_RGB=2,r._TYPE_GREY=3,r._TYPE_RLE_INDEXED=9,r._TYPE_RLE_RGB=10,r._TYPE_RLE_GREY=11,r._ORIGIN_MASK=48,r._ORIGIN_SHIFT=4,r._ORIGIN_BL=0,r._ORIGIN_BR=1,r._ORIGIN_UL=2,r._ORIGIN_UR=3,r}(),_h=function(){function r(){this.supportCascades=!1}return r.prototype.canLoad=function(t){return Xn.a.EndsWith(t,".tga")},r.prototype.loadCubeData=function(t,e,n,i,o){throw".env not supported in Cube."},r.prototype.loadData=function(t,e,n){var i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=pa.GetTGAHeader(i);n(o.width,o.height,e.generateMipMaps,!1,function(){pa.UploadContent(e,i)})},r}();Ue.a._TextureLoaders.push(new _h);var po,ym=function(){};(function(r){r[r.cTFETC1=0]="cTFETC1",r[r.cTFBC1=1]="cTFBC1",r[r.cTFBC4=2]="cTFBC4",r[r.cTFPVRTC1_4_OPAQUE_ONLY=3]="cTFPVRTC1_4_OPAQUE_ONLY",r[r.cTFBC7_M6_OPAQUE_ONLY=4]="cTFBC7_M6_OPAQUE_ONLY",r[r.cTFETC2=5]="cTFETC2",r[r.cTFBC3=6]="cTFBC3",r[r.cTFBC5=7]="cTFBC5"})(po||(po={}));var _o=function(){function r(){}return r.GetInternalFormatFromBasisFormat=function(t){if(t===po.cTFETC1)return 36196;if(t===po.cTFBC1)return 33776;if(t===po.cTFBC3)return 33779;throw"The chosen Basis transcoder format is not currently supported"},r._CreateWorkerAsync=function(){var t=this;return this._WorkerPromise||(this._WorkerPromise=new Promise(function(e){t._Worker?e(t._Worker):Ye.b.LoadFileAsync(r.WasmModuleURL).then(function(n){var i=URL.createObjectURL(new Blob(["("+Tm+")()"],{type:"application/javascript"}));t._Worker=new Worker(i);var o=function(a){a.data.action==="init"&&(t._Worker.removeEventListener("message",o),e(t._Worker))};t._Worker.addEventListener("message",o),t._Worker.postMessage({action:"init",url:r.JSModuleURL,wasmBinary:n})})})),this._WorkerPromise},r.TranscodeAsync=function(t,e){var n=this,i=t instanceof ArrayBuffer?new Uint8Array(t):t;return new Promise(function(o,a){n._CreateWorkerAsync().then(function(){var s=n._actionId++,d=function(y){y.data.action==="transcode"&&y.data.id===s&&(n._Worker.removeEventListener("message",d),y.data.success?o(y.data):a("Transcode is not supported on this device"))};n._Worker.addEventListener("message",d);var p=new Uint8Array(i.byteLength);p.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),n._Worker.postMessage({action:"transcode",id:s,imageData:p,config:e,ignoreSupportedFormats:n._IgnoreSupportedFormats},[p.buffer])})})},r.LoadTextureFromTranscodeResult=function(t,e){for(var n,i=t.getEngine(),o=function(){if(n=e.fileInfo.images[a].levels[0],t._invertVScale=t.invertY,e.format===-1)if(t.type=h.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,t.format=h.a.TEXTUREFORMAT_RGB,i.webGLVersion<2&&($.a.Log2(n.width)%1!=0||$.a.Log2(n.height)%1!=0)){var s=new xt.a(i,xt.b.Temp);t._invertVScale=t.invertY,s.type=h.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,s.format=h.a.TEXTUREFORMAT_RGB,s.width=n.width+3&-4,s.height=n.height+3&-4,i._bindTextureDirectly(i._gl.TEXTURE_2D,s,!0),i._uploadDataToTextureDirectly(s,n.transcodedPixels,a,0,h.a.TEXTUREFORMAT_RGB,!0),i._rescaleTexture(s,t,i.scenes[0],i._getInternalFormat(h.a.TEXTUREFORMAT_RGB),function(){i._releaseTexture(s),i._bindTextureDirectly(i._gl.TEXTURE_2D,t,!0)})}else t._invertVScale=!t.invertY,t.width=n.width+3&-4,t.height=n.height+3&-4,i._uploadDataToTextureDirectly(t,n.transcodedPixels,a,0,h.a.TEXTUREFORMAT_RGB,!0);else t.width=n.width,t.height=n.height,e.fileInfo.images[a].levels.forEach(function(d,p){i._uploadCompressedDataToTextureDirectly(t,r.GetInternalFormatFromBasisFormat(e.format),d.width,d.height,d.transcodedPixels,a,p)}),i.webGLVersion<2&&($.a.Log2(t.width)%1!=0||$.a.Log2(t.height)%1!=0)&&(Ye.b.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."),t._cachedWrapU=we.a.CLAMP_ADDRESSMODE,t._cachedWrapV=we.a.CLAMP_ADDRESSMODE)},a=0;a>2&3],se[Ee++]=ie[Pe>>4&3],se[Ee++]=ie[Pe>>6&3]}}return se}(O,0,a.getImageWidth(s,d)+3&-4,a.getImageHeight(s,d)+3&-4)),O):null}onmessage=function(a){if(a.data.action==="init")i||(Module={wasmBinary:a.data.wasmBinary},importScripts(a.data.url),i=new Promise(function(fe){Module.onRuntimeInitialized=function(){Module.initializeBasis(),fe()}})),i.then(function(){postMessage({action:"init"})});else if(a.data.action==="transcode"){var s=a.data.config,d=a.data.imageData,p=new Module.BasisFile(d),y=function(fe){for(var ve=fe.getHasAlpha(),Te=fe.getNumImages(),Oe=[],Pe=0;Pe1&&e.generateMipMaps;_o.LoadTextureFromTranscodeResult(e,d),e.getEngine()._setCubeMapTextureParams(e,p),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),i&&i()}).catch(function(d){Ye.b.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),e.isReady=!0})}},r.prototype.loadData=function(t,e,n){var i=e.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!i.etc1,s3tc:!!i.s3tc,pvrtc:!!i.pvrtc,etc2:!!i.etc2}};_o.TranscodeAsync(t,o).then(function(a){var s=a.fileInfo.images[0].levels[0],d=a.fileInfo.images[0].levels.length>1&&e.generateMipMaps;n(s.width,s.height,d,a.format!==-1,function(){_o.LoadTextureFromTranscodeResult(e,a)})}).catch(function(a){Ye.b.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),n(0,0,!1,!1,function(){})})},r}();Ue.a._TextureLoaders.push(new mh);var tc=function(r){function t(e,n,i,o,a){var s=this,d=!(!a||!a.generateMipMaps)&&a.generateMipMaps,p=!(!a||!a.generateDepthTexture)&&a.generateDepthTexture,y=!a||a.doNotChangeAspectRatio===void 0||a.doNotChangeAspectRatio;if((s=r.call(this,e,n,o,d,y)||this).isSupported){var P=[],O=[];s._initTypes(i,P,O,a);var U=!a||a.generateDepthBuffer===void 0||a.generateDepthBuffer,F=!(!a||a.generateStencilBuffer===void 0)&&a.generateStencilBuffer;return s._size=n,s._multiRenderTargetOptions={samplingModes:O,generateMipMaps:d,generateDepthBuffer:U,generateStencilBuffer:F,generateDepthTexture:p,types:P,textureCount:i},s._count=i,s._createInternalTextures(),s._createTextures(),s}s.dispose()}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"isSupported",{get:function(){return this._getEngine().webGLVersion>1||this._getEngine().getCaps().drawBuffersExtension},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textures",{get:function(){return this._textures},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wrapU",{set:function(e){if(this._textures)for(var n=0;n=0;e--)this._internalTextures[e]!==void 0&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},t}(sn),nc=function(r,t,e){this.id=r,this.scale=t,this.offset=e},Em=function(){function r(t,e,n,i){var o,a,s,d,p,y,P,O,U,F,z,J,ie;return this.name=t,this.meshes=e,this.scene=i,this.options=n,this.options.map=(o=this.options.map)!==null&&o!==void 0?o:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=(a=this.options.uvsIn)!==null&&a!==void 0?a:Me.b.UVKind,this.options.uvsOut=(s=this.options.uvsOut)!==null&&s!==void 0?s:Me.b.UVKind,this.options.layout=(d=this.options.layout)!==null&&d!==void 0?d:r.LAYOUT_STRIP,this.options.layout===r.LAYOUT_COLNUM&&(this.options.colnum=(p=this.options.colnum)!==null&&p!==void 0?p:8),this.options.updateInputMeshes=(y=this.options.updateInputMeshes)===null||y===void 0||y,this.options.disposeSources=(P=this.options.disposeSources)===null||P===void 0||P,this._expecting=0,this.options.fillBlanks=(O=this.options.fillBlanks)===null||O===void 0||O,this.options.fillBlanks===!0&&(this.options.customFillColor=(U=this.options.customFillColor)!==null&&U!==void 0?U:"black"),this.options.frameSize=(F=this.options.frameSize)!==null&&F!==void 0?F:256,this.options.paddingRatio=(z=this.options.paddingRatio)!==null&&z!==void 0?z:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=(J=this.options.paddingMode)!==null&&J!==void 0?J:r.SUBUV_WRAP,this.options.paddingMode===r.SUBUV_COLOR&&(this.options.paddingColor=(ie=this.options.paddingColor)!==null&&ie!==void 0?ie:new M.b(0,0,0,1)),this.sets={},this.frames=[],this}return r.prototype._createFrames=function(t){for(var e=this,n=this._calculateSize(),i=new u.d(1,1).divide(n),o=0,a=this._expecting,s=this.meshes.length,d=Object.keys(this.sets),p=0;p0);for(var t=0;t0)}},r}(),Sm=` -attribute vec2 position; - -varying vec2 vPosition; -varying vec2 vUV; -const vec2 madd=vec2(0.5,0.5); -void main(void) { -vPosition=position; -vUV=position*madd+madd; -gl_Position=vec4(position,0.0,1.0); -}`;je.a.ShadersStore.proceduralVertexShader=Sm;var mo=function(r){function t(e,n,i,o,a,s,d,p){a===void 0&&(a=null),s===void 0&&(s=!0),d===void 0&&(d=!1),p===void 0&&(p=h.a.TEXTURETYPE_UNSIGNED_INT);var y=r.call(this,null,o,!s)||this;y.isEnabled=!0,y.autoClear=!0,y.onGeneratedObservable=new x.c,y.onBeforeGenerationObservable=new x.c,y.nodeMaterialSource=null,y._textures={},y._currentRefreshId=-1,y._frameId=-1,y._refreshRate=1,y._vertexBuffers={},y._uniforms=new Array,y._samplers=new Array,y._floats={},y._ints={},y._floatsArrays={},y._colors3={},y._colors4={},y._vectors2={},y._vectors3={},y._matrices={},y._fallbackTextureUsed=!1,y._cachedDefines="",y._contentUpdateId=-1;var P=(o=y.getScene()||te.a.LastCreatedScene)._getComponent(st.a.NAME_PROCEDURALTEXTURE);P||(P=new gh(o),o._addComponent(P)),o.proceduralTextures.push(y),y._fullEngine=o.getEngine(),y.name=e,y.isRenderTarget=!0,y._size=n,y._generateMipMaps=s,y.setFragment(i),y._fallbackTexture=a,d?(y._texture=y._fullEngine.createRenderTargetCubeTexture(n,{generateMipMaps:s,generateDepthBuffer:!1,generateStencilBuffer:!1,type:p}),y.setFloat("face",0)):y._texture=y._fullEngine.createRenderTargetTexture(n,{generateMipMaps:s,generateDepthBuffer:!1,generateStencilBuffer:!1,type:p});var O=[];return O.push(1,1),O.push(-1,1),O.push(-1,-1),O.push(1,-1),y._vertexBuffers[Me.b.PositionKind]=new Me.b(y._fullEngine,O,Me.b.PositionKind,!1,!1,2),y._createIndexBuffer(),y}return Object(c.d)(t,r),t.prototype.getEffect=function(){return this._effect},t.prototype.getContent=function(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData=this.readPixels(0,0,this._contentData),this._contentUpdateId=this._frameId),this._contentData},t.prototype._createIndexBuffer=function(){var e=this._fullEngine,n=[];n.push(0),n.push(1),n.push(2),n.push(0),n.push(2),n.push(3),this._indexBuffer=e.createIndexBuffer(n)},t.prototype._rebuild=function(){var e=this._vertexBuffers[Me.b.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===sn.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=sn.REFRESHRATE_RENDER_ONCE)},t.prototype.reset=function(){this._effect!==void 0&&this._effect.dispose()},t.prototype._getDefines=function(){return""},t.prototype.isReady=function(){var e,n=this,i=this._fullEngine;if(this.nodeMaterialSource)return this._effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;var o=this._getDefines();return!(!this._effect||o!==this._cachedDefines||!this._effect.isReady())||(e=this._fragment.fragmentElement!==void 0?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines=o,this._effect=i.createEffect(e,[Me.b.PositionKind],this._uniforms,this._samplers,o,void 0,void 0,function(){n.releaseInternalTexture(),n._fallbackTexture&&(n._texture=n._fallbackTexture._texture,n._texture&&n._texture.incrementReferences()),n._fallbackTextureUsed=!0}),this._effect.isReady())},t.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},t.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!1,configurable:!0}),t.prototype._shouldRender=function(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(this._currentRefreshId===-1||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)},t.prototype.getRenderSize=function(){return this._size},t.prototype.resize=function(e,n){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._fullEngine.createRenderTargetTexture(e,n),this._size=e,this._generateMipMaps=n)},t.prototype._checkUniform=function(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)},t.prototype.setTexture=function(e,n){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=n,this},t.prototype.setFloat=function(e,n){return this._checkUniform(e),this._floats[e]=n,this},t.prototype.setInt=function(e,n){return this._checkUniform(e),this._ints[e]=n,this},t.prototype.setFloats=function(e,n){return this._checkUniform(e),this._floatsArrays[e]=n,this},t.prototype.setColor3=function(e,n){return this._checkUniform(e),this._colors3[e]=n,this},t.prototype.setColor4=function(e,n){return this._checkUniform(e),this._colors4[e]=n,this},t.prototype.setVector2=function(e,n){return this._checkUniform(e),this._vectors2[e]=n,this},t.prototype.setVector3=function(e,n){return this._checkUniform(e),this._vectors3[e]=n,this},t.prototype.setMatrix=function(e,n){return this._checkUniform(e),this._matrices[e]=n,this},t.prototype.render=function(e){var n=this.getScene();if(n){var i=this._fullEngine;if(i.enableEffect(this._effect),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(var o in this._textures)this._effect.setTexture(o,this._textures[o]);for(o in this._ints)this._effect.setInt(o,this._ints[o]);for(o in this._floats)this._effect.setFloat(o,this._floats[o]);for(o in this._floatsArrays)this._effect.setArray(o,this._floatsArrays[o]);for(o in this._colors3)this._effect.setColor3(o,this._colors3[o]);for(o in this._colors4){var a=this._colors4[o];this._effect.setFloat4(o,a.r,a.g,a.b,a.a)}for(o in this._vectors2)this._effect.setVector2(o,this._vectors2[o]);for(o in this._vectors3)this._effect.setVector3(o,this._vectors3[o]);for(o in this._matrices)this._effect.setMatrix(o,this._matrices[o])}if(this._texture){if(this.isCube)for(var s=0;s<6;s++)i.bindFramebuffer(this._texture,s,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",s),this.autoClear&&i.clear(n.clearColor,!0,!1,!1),i.drawElementsType(Ht.a.TriangleFillMode,0,6),s===5&&i.generateMipMapsForCubemap(this._texture);else i.bindFramebuffer(this._texture,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this.autoClear&&i.clear(n.clearColor,!0,!1,!1),i.drawElementsType(Ht.a.TriangleFillMode,0,6);i.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}}},t.prototype.clone=function(){var e=this.getSize(),n=new t(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return n.hasAlpha=this.hasAlpha,n.level=this.level,n.coordinatesMode=this.coordinatesMode,n},t.prototype.dispose=function(){var e=this.getScene();if(e){var n=e.proceduralTextures.indexOf(this);n>=0&&e.proceduralTextures.splice(n,1);var i=this._vertexBuffers[Me.b.PositionKind];i&&(i.dispose(),this._vertexBuffers[Me.b.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),r.prototype.dispose.call(this)}},Object(c.c)([Object(L.c)()],t.prototype,"isEnabled",void 0),Object(c.c)([Object(L.c)()],t.prototype,"autoClear",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_generateMipMaps",void 0),Object(c.c)([Object(L.c)()],t.prototype,"_size",void 0),Object(c.c)([Object(L.c)()],t.prototype,"refreshRate",null),t}(we.a);R.a.RegisteredTypes["BABYLON.ProceduralTexture"]=mo;var Am=function(r){function t(e,n,i,o,a,s){var d=r.call(this,e,i,null,o,a,s)||this;return d._animate=!0,d._time=0,d._texturePath=n,d._loadJson(n),d.refreshRate=1,d}return Object(c.d)(t,r),t.prototype._loadJson=function(e){var n=this,i=function(){try{n.setFragment(n._texturePath)}catch{l.a.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},o=e+"/config.json",a=new re.a;a.open("GET",o),a.addEventListener("load",function(){if(a.status===200||a.responseText&&a.responseText.length>0)try{n._config=JSON.parse(a.response),n.updateShaderUniforms(),n.updateTextures(),n.setFragment(n._texturePath+"/custom"),n._animate=n._config.animate,n.refreshRate=n._config.refreshrate}catch{i()}else i()},!1),a.addEventListener("error",function(){i()},!1);try{a.send()}catch{l.a.Error("CustomProceduralTexture: Error on XHR send request.")}},t.prototype.isReady=function(){if(!r.prototype.isReady.call(this))return!1;for(var e in this._textures)if(!this._textures[e].isReady())return!1;return!0},t.prototype.render=function(e){var n=this.getScene();this._animate&&n&&(this._time+=.03*n.getAnimationRatio(),this.updateShaderUniforms()),r.prototype.render.call(this,e)},t.prototype.updateTextures=function(){for(var e=0;e0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isConnectedInVertexShader",{get:function(){if(this.target===Re.Vertex)return!0;if(!this.hasEndpoints)return!1;for(var t=0,e=this._endpoints;t=0)&&(e.isExposedOnFrame=!0,e.exposedPortPosition=this.exposedPortPosition),e},r.prototype.dispose=function(){this.onConnectionObservable.clear()},r}(),Mm=f(152),pt=function(){function r(t,e,n,i){e===void 0&&(e=Re.Vertex),n===void 0&&(n=!1),i===void 0&&(i=!1),this._isFinalMerger=!1,this._isInput=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this._target=e,this._isFinalMerger=n,this._isInput=i,this._name=t,this.uniqueId=Mm.a.UniqueId}return Object.defineProperty(r.prototype,"name",{get:function(){return this._name},set:function(t){this.validateBlockName(t)&&(this._name=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isUnique",{get:function(){return this._isUnique},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isFinalMerger",{get:function(){return this._isFinalMerger},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isInput",{get:function(){return this._isInput},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"buildId",{get:function(){return this._buildId},set:function(t){this._buildId=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"target",{get:function(){return this._target},set:function(t){!(this._target&t)&&(this._target=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"inputs",{get:function(){return this._inputs},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"outputs",{get:function(){return this._outputs},enumerable:!1,configurable:!0}),r.prototype.getInputByName=function(t){var e=this._inputs.filter(function(n){return n.name===t});return e.length?e[0]:null},r.prototype.getOutputByName=function(t){var e=this._outputs.filter(function(n){return n.name===t});return e.length?e[0]:null},r.prototype.initialize=function(t){},r.prototype.bind=function(t,e,n,i){},r.prototype._declareOutput=function(t,e){return e._getGLType(t.type)+" "+t.associatedVariableName},r.prototype._writeVariable=function(t){return t.connectedPoint?""+t.associatedVariableName:"0."},r.prototype._writeFloat=function(t){var e=t.toString();return e.indexOf(".")===-1&&(e+=".0"),""+e},r.prototype.getClassName=function(){return"NodeMaterialBlock"},r.prototype.registerInput=function(t,e,n,i,o){return n===void 0&&(n=!1),(o=o??new _a(t,this,bn.Input)).type=e,o.isOptional=n,i&&(o.target=i),this._inputs.push(o),this},r.prototype.registerOutput=function(t,e,n,i){return(i=i??new _a(t,this,bn.Output)).type=e,n&&(i.target=n),this._outputs.push(i),this},r.prototype.getFirstAvailableInput=function(t){t===void 0&&(t=null);for(var e=0,n=this._inputs;e=this._outputs.length?null:this._outputs[e+1]},r.prototype.connectTo=function(t,e){if(this._outputs.length!==0){for(var n=e&&e.output?this.getOutputByName(e.output):this.getFirstAvailableOutput(t),i=!0;i;){var o=e&&e.input?t.getInputByName(e.input):t.getFirstAvailableInput(n);if(n&&o&&n.canConnectTo(o))n.connectTo(o),i=!1;else{if(!n)throw"Unable to find a compatible match";n=this.getSiblingOutput(n)}}return this}},r.prototype._buildBlock=function(t){},r.prototype.updateUniformsAndSamples=function(t,e,n,i){},r.prototype.provideFallbacks=function(t,e){},r.prototype.initializeDefines=function(t,e,n,i){},r.prototype.prepareDefines=function(t,e,n,i,o){},r.prototype.autoConfigure=function(t){},r.prototype.replaceRepeatableContent=function(t,e,n,i){},r.prototype.isReady=function(t,e,n,i){return!0},r.prototype._linkConnectionTypes=function(t,e,n){n===void 0&&(n=!1),n?this._inputs[e]._acceptedConnectionPointType=this._inputs[t]:this._inputs[t]._linkedConnectionSource=this._inputs[e],this._inputs[e]._linkedConnectionSource=this._inputs[t]},r.prototype._processBuild=function(t,e,n,i){t.build(e,i);var o=e._vertexState!=null,a=t._buildTarget===Re.Vertex&&t.target!==Re.VertexAndFragment;if(o&&(!(t.target&t._buildTarget)||!(t.target&n.target)||this.target!==Re.VertexAndFragment&&a)&&(!t.isInput&&e.target!==t._buildTarget||t.isInput&&t.isAttribute&&!t._noContextSwitch)){var s=n.connectedPoint;e._vertexState._emitVaryingFromString("v_"+s.associatedVariableName,e._getGLType(s.type))&&(e._vertexState.compilationString+="v_"+s.associatedVariableName+" = "+s.associatedVariableName+`;\r -`),n.associatedVariableName="v_"+s.associatedVariableName,n._enforceAssociatedVariableName=!0}},r.prototype.validateBlockName=function(t){for(var e=0,n=["position","normal","tangent","particle_positionw","uv","uv2","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];e[0.."+n.repeatKey+`]\r -`;var i=je.a.IncludesShadersStore[t]+`\r -`;if(this.sharedData.emitComments&&(i=e+`\r -`+i),!n)return i;if(n.replaceStrings)for(var o=0;o[0.."+n.repeatKey+`]\r -`:this.functions[o]="#include<"+t+`>\r -`,void(this.sharedData.emitComments&&(this.functions[o]=e+`\r -`+this.functions[o]));if(this.functions[o]=je.a.IncludesShadersStore[t],this.sharedData.emitComments&&(this.functions[o]=e+`\r -`+this.functions[o]),n.removeIfDef&&(this.functions[o]=this.functions[o].replace(/^\s*?#ifdef.+$/gm,""),this.functions[o]=this.functions[o].replace(/^\s*?#endif.*$/gm,""),this.functions[o]=this.functions[o].replace(/^\s*?#else.*$/gm,""),this.functions[o]=this.functions[o].replace(/^\s*?#elif.*$/gm,"")),n.removeAttributes&&(this.functions[o]=this.functions[o].replace(/^\s*?attribute.+$/gm,"")),n.removeUniforms&&(this.functions[o]=this.functions[o].replace(/^\s*?uniform.+$/gm,"")),n.removeVaryings&&(this.functions[o]=this.functions[o].replace(/^\s*?varying.+$/gm,"")),n.replaceStrings)for(var a=0;a0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0},r.prototype.getDragGradients=function(){return this._dragGradients},r.prototype.getLimitVelocityGradients=function(){return this._limitVelocityGradients},r.prototype.getColorGradients=function(){return this._colorGradients},r.prototype.getSizeGradients=function(){return this._sizeGradients},r.prototype.getColorRemapGradients=function(){return this._colorRemapGradients},r.prototype.getAlphaRemapGradients=function(){return this._alphaRemapGradients},r.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},r.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},r.prototype.getVelocityGradients=function(){return this._velocityGradients},r.prototype.getStartSizeGradients=function(){return this._startSizeGradients},r.prototype.getEmitRateGradients=function(){return this._emitRateGradients},Object.defineProperty(r.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:u.e.Zero()},set:function(t){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:u.e.Zero()},set:function(t){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:u.e.Zero()},set:function(t){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:u.e.Zero()},set:function(t){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(t){this._isBillboardBased!==t&&(this._isBillboardBased=t,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(t){this._attachImageProcessingConfiguration(t)},enumerable:!1,configurable:!0}),r.prototype._attachImageProcessingConfiguration=function(t){t!==this._imageProcessingConfiguration&&(!t&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=t)},r.prototype._reset=function(){},r.prototype._removeGradientAndTexture=function(t,e,n){if(!e)return this;for(var i=0,o=0,a=e;o-1))return this._optimizers.push(e),this},t.prototype.unregisterOptimizer=function(e){var n=this._optimizers.indexOf(e);if(n!==-1)return this._optimizers.splice(n,1),this},t.prototype.addOutputNode=function(e){if(e.target===null)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&Re.Vertex&&this._addVertexOutputNode(e),e.target&Re.Fragment&&this._addFragmentOutputNode(e),this},t.prototype.removeOutputNode=function(e){return e.target===null||(e.target&Re.Vertex&&this._removeVertexOutputNode(e),e.target&Re.Fragment&&this._removeFragmentOutputNode(e)),this},t.prototype._addVertexOutputNode=function(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=Re.Vertex,this._vertexOutputNodes.push(e),this},t.prototype._removeVertexOutputNode=function(e){var n=this._vertexOutputNodes.indexOf(e);if(n!==-1)return this._vertexOutputNodes.splice(n,1),this},t.prototype._addFragmentOutputNode=function(e){if(this._fragmentOutputNodes.indexOf(e)===-1)return e.target=Re.Fragment,this._fragmentOutputNodes.push(e),this},t.prototype._removeFragmentOutputNode=function(e){var n=this._fragmentOutputNodes.indexOf(e);if(n!==-1)return this._fragmentOutputNodes.splice(n,1),this},t.prototype.needAlphaBlending=function(){return!this.ignoreAlpha&&(this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)},t.prototype.needAlphaTesting=function(){return this._sharedData&&this._sharedData.hints.needAlphaTesting},t.prototype._initializeBlock=function(e,n,i){if(e.initialize(n),e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){for(var o=e.getClassName(),a=0,s=this.attachedBlocks;a-1&&this.attachedBlocks.splice(n,1),e.isFinalMerger&&this.removeOutputNode(e)},t.prototype.build=function(e){e===void 0&&(e=!1),this._buildWasSuccessful=!1;var n=this.getScene().getEngine(),i=this._mode===Rn.Particle;if(this._vertexOutputNodes.length===0&&!i)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new bh,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=Re.Vertex,this._fragmentCompilationState=new bh,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=Re.Fragment,this._sharedData=new Im,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=i;for(var o=[],a=[],s=0,d=this._vertexOutputNodes;s0\r -`,e.compilationString+=this._declareOutput(o,e)+" = "+a.associatedVariableName+" * "+i+`;\r -`,e.compilationString+=`#else\r -`,e.compilationString+=this._declareOutput(o,e)+" = "+a.associatedVariableName+`;\r -`,e.compilationString+=`#endif\r -`,this},t}(pt);R.a.RegisteredTypes["BABYLON.BonesBlock"]=Sh;var Ah=function(r){function t(e){var n=r.call(this,e,Re.Vertex)||this;return n.registerInput("world0",le.Vector4),n.registerInput("world1",le.Vector4),n.registerInput("world2",le.Vector4),n.registerInput("world3",le.Vector4),n.registerInput("world",le.Matrix,!0),n.registerOutput("output",le.Matrix),n.registerOutput("instanceID",le.Float),n}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"InstancesBlock"},Object.defineProperty(t.prototype,"world0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"instanceID",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.world0.connectedPoint){var n=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="world0"});n||(n=new At("world0")).setAsAttribute("world0"),n.output.connectTo(this.world0)}if(!this.world1.connectedPoint){var i=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="world1"});i||(i=new At("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){var o=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="world2"});o||(o=new At("world2")).setAsAttribute("world2"),o.output.connectTo(this.world2)}if(!this.world3.connectedPoint){var a=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="world3"});a||(a=new At("world3")).setAsAttribute("world3"),a.output.connectTo(this.world3)}if(!this.world.connectedPoint){var s=e.getInputBlockByPredicate(function(d){return d.isAttribute&&d.name==="world"});s||(s=new At("world")).setAsSystemValue(bt.World),s.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"},t.prototype.prepareDefines=function(e,n,i,o,a){o===void 0&&(o=!1);var s=!1;i.INSTANCES!==o&&(i.setValue("INSTANCES",o),s=!0),a&&i.THIN_INSTANCES!==!!a?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!a?.getRenderingMesh().hasThinInstances),s=!0),s&&i.markAsUnprocessed()},t.prototype._buildBlock=function(e){r.prototype._buildBlock.call(this,e),e.sharedData.blocksWithDefines.push(this);var n=this._outputs[0],i=this._outputs[1],o=this.world0,a=this.world1,s=this.world2,d=this.world3;return e.compilationString+=`#ifdef INSTANCES\r -`,e.compilationString+=this._declareOutput(n,e)+" = mat4("+o.associatedVariableName+", "+a.associatedVariableName+", "+s.associatedVariableName+", "+d.associatedVariableName+`);\r -`,e.compilationString+=`#ifdef THIN_INSTANCES\r -`,e.compilationString+=n.associatedVariableName+" = "+this.world.associatedVariableName+" * "+n.associatedVariableName+`;\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=this._declareOutput(i,e)+` = float(gl_InstanceID);\r -`,e.compilationString+=`#else\r -`,e.compilationString+=this._declareOutput(n,e)+" = "+this.world.associatedVariableName+`;\r -`,e.compilationString+=this._declareOutput(i,e)+` = 0.0;\r -`,e.compilationString+=`#endif\r -`,this},t}(pt);R.a.RegisteredTypes["BABYLON.InstancesBlock"]=Ah;var Ph=function(r){function t(e){var n=r.call(this,e,Re.Vertex)||this;return n.registerInput("position",le.Vector3),n.registerInput("normal",le.Vector3),n.registerInput("tangent",le.Vector3),n.registerInput("uv",le.Vector2),n.registerOutput("positionOutput",le.Vector3),n.registerOutput("normalOutput",le.Vector3),n.registerOutput("tangentOutput",le.Vector3),n.registerOutput("uvOutput",le.Vector2),n}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"MorphTargetsBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tangent",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positionOutput",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalOutput",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tangentOutput",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uvOutput",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("morphTargetInfluences")},t.prototype.autoConfigure=function(e){if(!this.position.isConnected){var n=e.getInputBlockByPredicate(function(s){return s.isAttribute&&s.name==="position"});n||(n=new At("position")).setAsAttribute(),n.output.connectTo(this.position)}if(!this.normal.isConnected){var i=e.getInputBlockByPredicate(function(s){return s.isAttribute&&s.name==="normal"});i||(i=new At("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){var o=e.getInputBlockByPredicate(function(s){return s.isAttribute&&s.name==="tangent"});o||(o=new At("tangent")).setAsAttribute("tangent"),o.output.connectTo(this.tangent)}if(!this.uv.isConnected){var a=e.getInputBlockByPredicate(function(s){return s.isAttribute&&s.name==="uv"});a||(a=new At("uv")).setAsAttribute("uv"),a.output.connectTo(this.uv)}},t.prototype.prepareDefines=function(e,n,i){i._areAttributesDirty&&tt.a.PrepareDefinesForMorphTargets(e,i)},t.prototype.bind=function(e,n,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&tt.a.BindMorphTargetParameters(i,e)},t.prototype.replaceRepeatableContent=function(e,n,i,o){for(var a=this.position,s=this.normal,d=this.tangent,p=this.uv,y=this.positionOutput,P=this.normalOutput,O=this.tangentOutput,U=this.uvOutput,F=e,z=o.NUM_MORPH_INFLUENCERS,J=i.morphTargetManager,ie=J&&J.supportsNormals&&o.NORMAL,se=J&&J.supportsTangents&&o.TANGENT,ce=J&&J.supportsUVs&&o.UV1,ue="",fe=0;fe0)for(fe=0;fe=0;tt.a.PrepareUniformsAndSamplersForLight(a,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+a],o,s)}},t.prototype.bind=function(e,n,i){if(i){var o=i.getScene();this.light?tt.a.BindLight(this.light,this._lightId,o,e,!0):tt.a.BindLights(o,i,e,!0,n.maxSimultaneousLights)}},t.prototype._injectVertexCode=function(e){var n=this.worldPosition,i="//"+this.name;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var o="v_"+n.associatedVariableName;e._emitVaryingFromString(o,"vec4")&&(e.compilationString+=o+" = "+n.associatedVariableName+`;\r -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:n.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = "+n.associatedVariableName+`;\r -`,this.view.isConnected&&(e.compilationString+="mat4 view = "+this.view.associatedVariableName+`;\r -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))},t.prototype._buildBlock=function(e){if(r.prototype._buildBlock.call(this,e),e.target===Re.Fragment){e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);var n="//"+this.name,i=this.worldPosition;e._emitFunctionFromInclude("helperFunctions",n),e._emitFunctionFromInclude("lightsFragmentFunctions",n,{replaceStrings:[{search:/vPositionW/g,replace:"v_"+i.associatedVariableName+".xyz"}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",n,{replaceStrings:[{search:/vPositionW/g,replace:"v_"+i.associatedVariableName+".xyz"}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",n,{repeatKey:"maxSimultaneousLights"}),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+="vec3 viewDirectionW = normalize("+this.cameraPosition.associatedVariableName+" - v_"+i.associatedVariableName+`.xyz);\r -`),e.compilationString+=`lightingInfo info;\r -`,e.compilationString+=`float shadow = 1.;\r -`,e.compilationString+="float glossiness = "+(this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0")+" * "+(this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0")+`;\r -`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.);\r -`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.);\r -`,e.compilationString+="vec3 normalW = "+this.worldNormal.associatedVariableName+`.xyz;\r -`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",n,{repeatKey:"maxSimultaneousLights"});var o=this.diffuseOutput,a=this.specularOutput;return e.compilationString+=this._declareOutput(o,e)+" = diffuseBase"+(this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:"")+`;\r -`,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+" = specularBase"+(this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:"")+`;\r -`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = shadow;\r -`),this}this._injectVertexCode(e)},t.prototype.serialize=function(){var e=r.prototype.serialize.call(this);return this.light&&(e.lightId=this.light.id),e},t.prototype._deserialize=function(e,n,i){r.prototype._deserialize.call(this,e,n,i),e.lightId&&(this.light=n.getLightByID(e.lightId))},t}(pt);R.a.RegisteredTypes["BABYLON.LightBlock"]=wh;var Fh=function(r){function t(e,n){n===void 0&&(n=!1);var i=r.call(this,e,n?Re.Fragment:Re.VertexAndFragment)||this;return i.convertToGammaSpace=!1,i.convertToLinearSpace=!1,i._fragmentOnly=n,i.registerInput("uv",le.Vector2,!1,Re.VertexAndFragment),i.registerOutput("rgba",le.Color4,Re.Neutral),i.registerOutput("rgb",le.Color3,Re.Neutral),i.registerOutput("r",le.Float,Re.Neutral),i.registerOutput("g",le.Float,Re.Neutral),i.registerOutput("b",le.Float,Re.Neutral),i.registerOutput("a",le.Float,Re.Neutral),i._inputs[0].acceptedConnectionPointTypes.push(le.Vector3),i._inputs[0].acceptedConnectionPointTypes.push(le.Vector4),i._inputs[0]._prioritizeVertex=!n,i}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"TextureBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){if(this._fragmentOnly)return Re.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return Re.VertexAndFragment;for(var e=this.uv.connectedPoint;e;){if(e.target===Re.Fragment)return Re.Fragment;if(e.target===Re.Vertex)return Re.VertexAndFragment;if(e.target===Re.Neutral||e.target===Re.VertexAndFragment){var n=e.ownerBlock;e=null;for(var i=0,o=n.inputs;i1?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&&ht.a.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areLightsDirty){var a=e.getScene();if(this.light){var s={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};tt.a.PrepareDefinesForLight(a,e,this.light,this._lightId,i,!0,s),s.needRebuild&&i.rebuild()}else tt.a.PrepareDefinesForLights(a,e,i,!0,n.maxSimultaneousLights),i._needNormals=!0,tt.a.PrepareDefinesForMultiview(a,i)}},t.prototype.updateUniformsAndSamples=function(e,n,i,o){for(var a=0;a=0;tt.a.PrepareUniformsAndSamplersForLight(a,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+a],o,s)}},t.prototype.bind=function(e,n,i){var o,a;if(i){var s=i.getScene();this.light?tt.a.BindLight(this.light,this._lightId,s,e,!0):tt.a.BindLights(s,i,e,!0,n.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);var d=this._scene.ambientColor;d&&e.setColor3("ambientFromScene",d);var p=s.useRightHandedSystem===(s._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,p?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);var y=(a=(o=this.indexOfRefraction.connectInputBlock)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:1.5,P=Math.pow((y-1)/(y+1),2);this._metallicReflectanceColor.scaleToRef(P*this._metallicF0Factor,M.c.Color3[0]);var O=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,M.c.Color3[0],O)}},t.prototype._injectVertexCode=function(e){var n,i,o=this.worldPosition,a="//"+this.name;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",a,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",a,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var s="v_"+o.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=s+" = "+o.associatedVariableName+`;\r -`);var d=this.reflection.isConnected?(n=this.reflection.connectedPoint)===null||n===void 0?void 0:n.ownerBlock:null;d&&(d.viewConnectionPoint=this.view),e.compilationString+=(i=d?.handleVertexSide(e))!==null&&i!==void 0?i:"",e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0\r -`,e._injectAtEnd+=`vClipSpacePosition = gl_Position;\r -`,e._injectAtEnd+=`#endif\r -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",a,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:o.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = "+o.associatedVariableName+`;\r -`,this.view.isConnected&&(e.compilationString+="mat4 view = "+this.view.associatedVariableName+`;\r -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",a,{repeatKey:"maxSimultaneousLights"}))},t.prototype._getAlbedoOpacityCode=function(){var e=`albedoOpacityOutParams albedoOpacityOut;\r -`;return e+=`albedoOpacityBlock( - vec4(`+(this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)")+`, 1.), - #ifdef ALBEDO - vec4(1.), - vec2(1., 1.), - #endif - #ifdef OPACITY - vec4(`+(this.opacity.isConnected?this.opacity.associatedVariableName:"1.")+`), - vec2(1., 1.), - #endif - albedoOpacityOut - ); - - vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; - float alpha = albedoOpacityOut.alpha;\r -`},t.prototype._getAmbientOcclusionCode=function(){var e=`ambientOcclusionOutParams aoOut;\r -`;return e+=`ambientOcclusionBlock( - #ifdef AMBIENT - vec3(`+(this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.")+`), - vec4(0., 1.0, 1.0, 0.), - #endif - aoOut - );\r -`},t.prototype._getReflectivityCode=function(e){var n=`reflectivityOutParams reflectivityOut;\r -`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),n+=`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\r -`},t.prototype._buildBlock=function(e){var n,i,o,a,s,d,p,y,P,O,U,F,z,J,ie,se,ce,ue,fe,ve,Te,Oe,Pe,Ee,Se,Le,xe,Ne,Ie,Fe,Ke,nt,rt,ut,qe,at,ot,Je,dt;r.prototype._buildBlock.call(this,e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=ia.GetEnvironmentBRDFTexture(this._scene));var Ve=this.reflection.isConnected?(n=this.reflection.connectedPoint)===null||n===void 0?void 0:n.ownerBlock:null;if(Ve&&(Ve.worldPositionConnectionPoint=this.worldPosition,Ve.cameraPositionConnectionPoint=this.cameraPosition,Ve.worldNormalConnectionPoint=this.worldNormal),e.target!==Re.Fragment)return this._injectVertexCode(e),this;e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);var $e="//"+this.name,yt="v_"+this.worldPosition.associatedVariableName,Wt=this.perturbedNormal;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"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",$e,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",$e,{repeatKey:"maxSimultaneousLights"}),e._emitFunctionFromInclude("helperFunctions",$e),e._emitFunctionFromInclude("importanceSampling",$e),e._emitFunctionFromInclude("pbrHelperFunctions",$e),e._emitFunctionFromInclude("imageProcessingFunctions",$e),e._emitFunctionFromInclude("shadowsFragmentFunctions",$e,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",$e,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",$e),e._emitFunctionFromInclude("pbrBRDFFunctions",$e,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i=Ve?._defineSkyboxName)!==null&&i!==void 0?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",$e),e._emitFunctionFromInclude("pbrDirectLightingFunctions",$e,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",$e),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",$e),e._emitFunctionFromInclude("pbrBlockReflectivity",$e),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",$e),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",$e),e._emitFunctionFromInclude("pbrBlockAnisotropic",$e),e._emitUniformFromString("vLightingIntensity","vec4"),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+="vec4 "+this._vNormalWName+" = normalize("+this.worldNormal.associatedVariableName+`);\r -`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+="vec3 viewDirectionW = normalize("+this.cameraPosition.associatedVariableName+" - "+yt+`.xyz);\r -`),e.compilationString+="vec3 geometricNormalW = "+this._vNormalWName+`.xyz;\r -`,e.compilationString+="vec3 normalW = "+(Wt.isConnected?"normalize("+Wt.associatedVariableName+".xyz)":"geometricNormalW")+`;\r -`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",$e,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",$e),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",$e),e.compilationString+=`#ifdef UNLIT - vec3 diffuseBase = vec3(1., 1., 1.); - #else\r -`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",$e,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(o=Ve?._defineSkyboxName)!==null&&o!==void 0?o:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(a=Ve?._define3DName)!==null&&a!==void 0?a:"REFLECTIONMAP_3D"}]});var Nt=this.anisotropy.isConnected?(s=this.anisotropy.connectedPoint)===null||s===void 0?void 0:s.ownerBlock:null;Nt&&(Nt.worldPositionConnectionPoint=this.worldPosition,Nt.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Nt.getCode(e,!this.perturbedNormal.isConnected)),Ve&&Ve.hasTexture&&(e.compilationString+=Ve.getCode(e,Nt?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",$e,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(d=Ve?._define3DName)!==null&&d!==void 0?d:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(p=Ve?._defineOppositeZ)!==null&&p!==void 0?p:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(y=Ve?._defineProjectionName)!==null&&y!==void 0?y:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(P=Ve?._defineSkyboxName)!==null&&P!==void 0?P:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(O=Ve?._defineLODReflectionAlpha)!==null&&O!==void 0?O:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(U=Ve?._defineLinearSpecularReflection)!==null&&U!==void 0?U:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(F=Ve?._vReflectionFilteringInfoName)!==null&&F!==void 0?F:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",$e,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});var Qt=this.sheen.isConnected?(z=this.sheen.connectedPoint)===null||z===void 0?void 0:z.ownerBlock:null;Qt&&(e.compilationString+=Qt.getCode(Ve)),e._emitFunctionFromInclude("pbrBlockSheen",$e,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(J=Ve?._define3DName)!==null&&J!==void 0?J:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(ie=Ve?._defineSkyboxName)!==null&&ie!==void 0?ie:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(se=Ve?._defineLODReflectionAlpha)!==null&&se!==void 0?se:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(ce=Ve?._defineLinearSpecularReflection)!==null&&ce!==void 0?ce:"LINEARSPECULARREFLECTION"}]});var vt=this.clearcoat.isConnected?(ue=this.clearcoat.connectedPoint)===null||ue===void 0?void 0:ue.ownerBlock:null,Jt=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Xt=this.perturbedNormal.isConnected&&((fe=this.perturbedNormal.connectedPoint)===null||fe===void 0?void 0:fe.ownerBlock).worldTangent.isConnected,zt=this.anisotropy.isConnected&&((ve=this.anisotropy.connectedPoint)===null||ve===void 0?void 0:ve.ownerBlock).worldTangent.isConnected,Yt=Xt||!this.perturbedNormal.isConnected&&zt;e.compilationString+=Ea.GetCode(e,vt,Ve,yt,Jt,Yt,this.worldNormal.associatedVariableName),Jt&&(Yt=(Te=vt?.worldTangent.isConnected)!==null&&Te!==void 0&&Te),e._emitFunctionFromInclude("pbrBlockClearcoat",$e,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(Oe=Ve?._define3DName)!==null&&Oe!==void 0?Oe:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(Pe=Ve?._defineOppositeZ)!==null&&Pe!==void 0?Pe:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(Ee=Ve?._defineProjectionName)!==null&&Ee!==void 0?Ee:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(Se=Ve?._defineSkyboxName)!==null&&Se!==void 0?Se:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(Le=Ve?._defineLODReflectionAlpha)!==null&&Le!==void 0?Le:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(xe=Ve?._defineLinearSpecularReflection)!==null&&xe!==void 0?xe:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:Yt?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",$e,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(Ne=Ve?._defineSkyboxName)!==null&&Ne!==void 0?Ne:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(Ie=Ve?._define3DName)!==null&&Ie!==void 0?Ie:"REFLECTIONMAP_3D"}]});var Et=this.subsurface.isConnected?(Fe=this.subsurface.connectedPoint)===null||Fe===void 0?void 0:Fe.ownerBlock:null,Mt=this.subsurface.isConnected?(nt=((Ke=this.subsurface.connectedPoint)===null||Ke===void 0?void 0:Ke.ownerBlock).refraction.connectedPoint)===null||nt===void 0?void 0:nt.ownerBlock:null;Mt&&(Mt.viewConnectionPoint=this.view,Mt.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Sa.GetCode(e,Et,Ve,yt),e._emitFunctionFromInclude("pbrBlockSubSurface",$e,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(rt=Ve?._define3DName)!==null&&rt!==void 0?rt:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(ut=Ve?._defineOppositeZ)!==null&&ut!==void 0?ut:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(qe=Ve?._defineProjectionName)!==null&&qe!==void 0?qe:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(at=Mt?._define3DName)!==null&&at!==void 0?at:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(ot=Mt?._defineLODRefractionAlpha)!==null&&ot!==void 0?ot:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(Je=Mt?._defineLinearSpecularRefraction)!==null&&Je!==void 0?Je:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(dt=Mt?._defineOppositeZ)!==null&&dt!==void 0?dt:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",$e),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",$e,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",$e,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",$e),e.compilationString+=`#endif\r -`;var $t=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",Mn=pn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();Mn.indexOf(".")===-1&&(Mn+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",$e,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:$t+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:Mn}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",$e,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",$e,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",$e,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:yt},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.);\r -gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r -`}]});for(var Bn=0,qn=this._outputs;Bn("+this._options.remappedVariables.join(",")+")":je.a.IncludesShadersStore.shadowMapVertexNormalBias,P=this._options&&this._options.remappedVariables?"#include("+this._options.remappedVariables.join(",")+")":je.a.IncludesShadersStore.shadowMapVertexMetric,O=this._options&&this._options.remappedVariables?"#include("+this._options.remappedVariables.join(",")+")":je.a.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow,U=je.a.IncludesShadersStore.shadowMapFragment;d=(d=(d=(d=d.replace(/void\s+?main/g,je.a.IncludesShadersStore.shadowMapVertexDeclaration+`\r -void main`)).replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,y)).indexOf("#define SHADOWDEPTH_METRIC")!==-1?d.replace(/#define SHADOWDEPTH_METRIC/g,P):d.replace(/}\s*$/g,P+`\r -}`)).replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");var F=p.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||p.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,z=p.indexOf("#define SHADOWDEPTH_FRAGMENT")!==-1,J="";F?p=p.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,O):J=O+`\r -`,p=p.replace(/void\s+?main/g,je.a.IncludesShadersStore.shadowMapFragmentDeclaration+`\r -void main`),z?p=p.replace(/#define SHADOWDEPTH_FRAGMENT/g,U):J+=U+`\r -`,J&&(p=p.replace(/}\s*$/g,J+"}")),p=p.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");var ie=o.getUniformNames().slice();return ie.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM"),a.depthEffect=this._scene.getEngine().createEffect({vertexSource:d,fragmentSource:p,vertexToken:a.token,fragmentToken:a.token},{attributes:o.getAttributesNames(),uniformsNames:ie,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:s+` -`+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters()},this._scene.getEngine()),a.depthEffect},r}(),Td=f(101);function Ac(r,t,e,n,i){var o=new r.DecoderBuffer;o.Init(t,t.byteLength);var a,s,d=new r.Decoder;try{var p=d.GetEncodedGeometryType(o);switch(p){case r.TRIANGULAR_MESH:a=new r.Mesh,s=d.DecodeBufferToMesh(o,a);break;case r.POINT_CLOUD:a=new r.PointCloud,s=d.DecodeBufferToPointCloud(o,a);break;default:throw new Error("Invalid geometry type "+p)}if(!s.ok()||!a.ptr)throw new Error(s.error_msg());if(p===r.TRIANGULAR_MESH){var y=3*a.num_faces(),P=4*y,O=r._malloc(P);try{d.GetTrianglesUInt32Array(a,P,O);var U=new Uint32Array(y);U.set(new Uint32Array(r.HEAPF32.buffer,O,y)),n(U)}finally{r._free(O)}}var F=function(se,ce){var ue=ce.num_components(),fe=a.num_points(),ve=fe*ue,Te=ve*Float32Array.BYTES_PER_ELEMENT,Oe=r._malloc(Te);try{d.GetAttributeDataArrayForAllPoints(a,ce,r.DT_FLOAT32,Te,Oe);var Pe=new Float32Array(r.HEAPF32.buffer,Oe,ve);if(se==="color"&&ue===3){for(var Ee=new Float32Array(4*fe),Se=0,Le=0;Ser.EPSILON?1:0;d|=y,p.push(y)}switch(d){case 0:(u.e.Dot(this.normal,t.plane.normal)>0?e:n).push(t);break;case 1:i.push(t);break;case 2:o.push(t);break;case 3:var P,O=[],U=[];for(a=0;a=3&&(P=new Pc(O,t.shared)).plane&&i.push(P),U.length>=3&&(P=new Pc(U,t.shared)).plane&&o.push(P)}},r.EPSILON=1e-5,r}(),Pc=function(){function r(t,e){this.vertices=t,this.shared=e,this.plane=Gm.FromPoints(t[0].pos,t[1].pos,t[2].pos)}return r.prototype.clone=function(){return new r(this.vertices.map(function(t){return t.clone()}),this.shared)},r.prototype.flip=function(){this.vertices.reverse().map(function(t){t.flip()}),this.plane.flip()},r}(),Qn=function(){function r(t){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,t&&this.build(t)}return r.prototype.clone=function(){var t=new r;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map(function(e){return e.clone()}),t},r.prototype.invert=function(){for(var t=0;t1)?1:r.arc||1,d=r.sideOrientation===0?0:r.sideOrientation||ft.a.DEFAULTSIDE;t.push(0,0,0),i.push(.5,.5);for(var p=2*Math.PI*s,y=s===1?p/a:p/(a-1),P=0,O=0;Oe.x&&(e.x=n.x),n.ye.y&&(e.y=n.y)}),{min:t,max:e,width:e.x-t.x,height:e.y-t.y}},r}(),Xm=function(){function r(){}return r.Rectangle=function(t,e,n,i){return[new u.d(t,e),new u.d(n,e),new u.d(n,i),new u.d(t,i)]},r.Circle=function(t,e,n,i){e===void 0&&(e=0),n===void 0&&(n=0),i===void 0&&(i=32);for(var o=new Array,a=0,s=2*Math.PI/i,d=0;d0){var P=o.length/3;this._points.elements.forEach(function(J){i.push(0,-1,0),o.push(J.x,-t,J.y),a.push(1-(J.x-s.min.x)/s.width,1-(J.y-s.min.y)/s.height)});var O=d.length;for(y=0;ya.elements.length-1?a.elements[0]:a.elements[P+1],t.push(U.x,0,U.y),t.push(U.x,-s,U.y),t.push(O.x,0,O.y),t.push(O.x,-s,O.y);var F=new u.e(U.x,0,U.y),z=new u.e(O.x,0,O.y).subtract(F),J=new u.e(0,1,0),ie=u.e.Cross(z,J);ie=ie.normalize(),n.push(y/o.width,0),n.push(y/o.width,1),y+=z.length(),n.push(y/o.width,0),n.push(y/o.width,1),d?(e.push(ie.x,ie.y,ie.z),e.push(ie.x,ie.y,ie.z),e.push(ie.x,ie.y,ie.z),e.push(ie.x,ie.y,ie.z),i.push(p),i.push(p+2),i.push(p+1),i.push(p+1),i.push(p+2),i.push(p+3)):(e.push(-ie.x,-ie.y,-ie.z),e.push(-ie.x,-ie.y,-ie.z),e.push(-ie.x,-ie.y,-ie.z),e.push(-ie.x,-ie.y,-ie.z),i.push(p),i.push(p+1),i.push(p+2),i.push(p+1),i.push(p+3),i.push(p+2)),p+=4}},r}();ft.a.CreatePolygon=function(r,t,e,n,i,o,a){for(var s=e||new Array(3),d=n,p=[],y=a||!1,P=0;P<3;P++)s[P]===void 0&&(s[P]=new u.f(0,0,1,1)),d&&d[P]===void 0&&(d[P]=new M.b(1,1,1,1));var O=r.getVerticesData(Me.b.PositionKind),U=r.getVerticesData(Me.b.NormalKind),F=r.getVerticesData(Me.b.UVKind),z=r.getIndices(),J=O.length/9,ie=0,se=0,ce=0,ue=0,fe=[0];if(y)for(var ve=J;ve1?1:e.arc:1,a=e.closed===void 0||e.closed,s=e.shape,d=e.radius||1,p=e.tessellation||64,y=e.clip||0,P=e.updatable,O=De.a._GetDefaultSideOrientation(e.sideOrientation),U=e.cap||De.a.NO_CAP,F=2*Math.PI,z=new Array,J=e.invertUV||!1,ie=0,se=0,ce=F/p*o,ue=new Array;for(ie=0;ie<=p-y;ie++){for(ue=[],U!=De.a.CAP_START&&U!=De.a.CAP_ALL||(ue.push(new u.e(0,s[0].y,0)),ue.push(new u.e(Math.cos(ie*ce)*s[0].x*d,s[0].y,Math.sin(ie*ce)*s[0].x*d))),se=0;se0||P>0){switch(J=-O,ie=-U,se=O,ce=U,i){case De.a.CENTER:J-=d/=2,se+=d;break;case De.a.LEFT:se+=d,F=-d/2;break;case De.a.RIGHT:J-=d,F=d/2}switch(o){case De.a.CENTER:ie-=P/=2,ce+=P;break;case De.a.BOTTOM:ce+=P,z=-P/2;break;case De.a.TOP:ie-=P,z=P/2}}var ue=[],fe=[],ve=[];ve[0]=[0,0,1,0,1,1,0,1],ve[1]=[0,0,1,0,1,1,0,1],t!==De.a.ROTATE_TILE&&t!==De.a.ROTATE_ROW||(ve[1]=[1,1,0,1,0,0,1,0]),t!==De.a.FLIP_TILE&&t!==De.a.FLIP_ROW||(ve[1]=[1,0,0,0,0,1,1,1]),t!==De.a.FLIP_N_ROTATE_TILE&&t!==De.a.FLIP_N_ROTATE_ROW||(ve[1]=[0,1,1,1,1,0,0,0]);for(var Te=[],Oe=[],Pe=[],Ee=0,Se=0;Se0||P>0){var xe,Ne,Ie,Fe,Ke=P>0&&(o===De.a.CENTER||o===De.a.TOP),nt=P>0&&(o===De.a.CENTER||o===De.a.BOTTOM),rt=d>0&&(i===De.a.CENTER||i===De.a.RIGHT),ut=d>0&&(i===De.a.CENTER||i===De.a.LEFT),qe=[];if(Ke&&rt&&(ue.push(J+F,ie+z,0),ue.push(-O+F,ie+z,0),ue.push(-O+F,ie+P+z,0),ue.push(J+F,ie+P+z,0),Pe.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,qe=[xe=1-d/e,Ne=1-P/n,Ie=1,Ne,Ie,Fe=1,xe,Fe],t===De.a.ROTATE_ROW&&(qe=[1-xe,1-Ne,1-Ie,1-Ne,1-Ie,1-Fe,1-xe,1-Fe]),t===De.a.FLIP_ROW&&(qe=[1-xe,Ne,1-Ie,Ne,1-Ie,Fe,1-xe,Fe]),t===De.a.FLIP_N_ROTATE_ROW&&(qe=[xe,1-Ne,Ie,1-Ne,Ie,1-Fe,xe,1-Fe]),Te=Te.concat(qe),Oe.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),fe.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),Ke&&ut&&(ue.push(O+F,ie+z,0),ue.push(se+F,ie+z,0),ue.push(se+F,ie+P+z,0),ue.push(O+F,ie+P+z,0),Pe.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,qe=[xe=0,Ne=1-P/n,Ie=d/e,Ne,Ie,Fe=1,xe,Fe],(t===De.a.ROTATE_ROW||t===De.a.ROTATE_TILE&&s%2==0)&&(qe=[1-xe,1-Ne,1-Ie,1-Ne,1-Ie,1-Fe,1-xe,1-Fe]),(t===De.a.FLIP_ROW||t===De.a.FLIP_TILE&&s%2==0)&&(qe=[1-xe,Ne,1-Ie,Ne,1-Ie,Fe,1-xe,Fe]),(t===De.a.FLIP_N_ROTATE_ROW||t===De.a.FLIP_N_ROTATE_TILE&&s%2==0)&&(qe=[xe,1-Ne,Ie,1-Ne,Ie,1-Fe,xe,1-Fe]),Te=Te.concat(qe),Oe.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),fe.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),nt&&rt&&(ue.push(J+F,U+z,0),ue.push(-O+F,U+z,0),ue.push(-O+F,ce+z,0),ue.push(J+F,ce+z,0),Pe.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,qe=[xe=1-d/e,Ne=0,Ie=1,Ne,Ie,Fe=P/n,xe,Fe],(t===De.a.ROTATE_ROW&&y%2==1||t===De.a.ROTATE_TILE&&y%1==0)&&(qe=[1-xe,1-Ne,1-Ie,1-Ne,1-Ie,1-Fe,1-xe,1-Fe]),(t===De.a.FLIP_ROW&&y%2==1||t===De.a.FLIP_TILE&&y%2==0)&&(qe=[1-xe,Ne,1-Ie,Ne,1-Ie,Fe,1-xe,Fe]),(t===De.a.FLIP_N_ROTATE_ROW&&y%2==1||t===De.a.FLIP_N_ROTATE_TILE&&y%2==0)&&(qe=[xe,1-Ne,Ie,1-Ne,Ie,1-Fe,xe,1-Fe]),Te=Te.concat(qe),Oe.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),fe.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),nt&&ut&&(ue.push(O+F,U+z,0),ue.push(se+F,U+z,0),ue.push(se+F,ce+z,0),ue.push(O+F,ce+z,0),Pe.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,qe=[xe=0,Ne=0,Ie=d/e,Ne,Ie,Fe=P/n,xe,Fe],(t===De.a.ROTATE_ROW&&y%2==1||t===De.a.ROTATE_TILE&&(y+s)%2==1)&&(qe=[1-xe,1-Ne,1-Ie,1-Ne,1-Ie,1-Fe,1-xe,1-Fe]),(t===De.a.FLIP_ROW&&y%2==1||t===De.a.FLIP_TILE&&(y+s)%2==1)&&(qe=[1-xe,Ne,1-Ie,Ne,1-Ie,Fe,1-xe,Fe]),(t===De.a.FLIP_N_ROTATE_ROW&&y%2==1||t===De.a.FLIP_N_ROTATE_TILE&&(y+s)%2==1)&&(qe=[xe,1-Ne,Ie,1-Ne,Ie,1-Fe,xe,1-Fe]),Te=Te.concat(qe),Oe.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),fe.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),Ke){var at=[];for(xe=0,Ne=1-P/n,Ie=1,Fe=1,at[0]=[xe,Ne,Ie,Ne,Ie,Fe,xe,Fe],at[1]=[xe,Ne,Ie,Ne,Ie,Fe,xe,Fe],t!==De.a.ROTATE_TILE&&t!==De.a.ROTATE_ROW||(at[1]=[1-xe,1-Ne,1-Ie,1-Ne,1-Ie,1-Fe,1-xe,1-Fe]),t!==De.a.FLIP_TILE&&t!==De.a.FLIP_ROW||(at[1]=[1-xe,Ne,1-Ie,Ne,1-Ie,Fe,1-xe,Fe]),t!==De.a.FLIP_N_ROTATE_TILE&&t!==De.a.FLIP_N_ROTATE_ROW||(at[1]=[xe,1-Ne,Ie,1-Ne,Ie,1-Fe,xe,1-Fe]),Le=0;Le1)?1:e.arc||1;var U,F,z=function(ce,ue,fe,ve,Te,Oe,Pe,Ee){for(var Se,Le,xe,Ne,Ie=ue.getTangents(),Fe=ue.getNormals(),Ke=ue.getDistances(),nt=2*Math.PI/Te*Ee,rt=Oe||function(){return ve},ut=u.c.Matrix[0],qe=Pe===De.a.NO_CAP||Pe===De.a.CAP_END?0:2,at=0;at3?0:p,e.arc);var se=So.a.CreateRibbon(t,{pathArray:F,closePath:!0,closeArray:!1,updatable:P,sideOrientation:O,invertUV:y,frontUVs:e.frontUVs,backUVs:e.backUVs},n);return se._creationDataStorage.pathArray=F,se._creationDataStorage.path3D=U,se._creationDataStorage.tessellation=s,se._creationDataStorage.cap=p,se._creationDataStorage.arc=e.arc,se._creationDataStorage.radius=a,se},r}();ft.a.CreateIcoSphere=function(r){var t,e=r.sideOrientation||ft.a.DEFAULTSIDE,n=r.radius||1,i=r.flat===void 0||r.flat,o=r.subdivisions||4,a=r.radiusX||n,s=r.radiusY||n,d=r.radiusZ||n,p=(1+Math.sqrt(5))/2,y=[-1,p,-0,1,p,0,-1,-p,0,1,-p,0,0,-1,-p,0,1,-p,0,-1,p,0,1,p,p,0,1,p,0,-1,-p,0,1,-p,0,-1],P=[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],O=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],U=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],F=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],z=new Array,J=new Array,ie=new Array,se=new Array,ce=0,ue=new Array(3),fe=new Array(3);for(t=0;t<3;t++)ue[t]=u.e.Zero(),fe[t]=u.d.Zero();for(var ve=0;ve<20;ve++){for(t=0;t<3;t++){var Te=P[3*ve+t];ue[t].copyFromFloats(y[3*O[Te]],y[3*O[Te]+1],y[3*O[Te]+2]),ue[t].normalize().scaleInPlace(n),fe[t].copyFromFloats(U[2*Te]*(138/1024)+60/1024+F[ve]*(-40/1024),U[2*Te+1]*(239/1024)+26/1024+F[ve]*(20/1024))}for(var Oe=function(Le,xe,Ne,Ie){var Fe,Ke=u.e.Lerp(ue[0],ue[2],xe/o),nt=u.e.Lerp(ue[1],ue[2],xe/o),rt=o===xe?ue[2]:u.e.Lerp(Ke,nt,Le/(o-xe));if(rt.normalize(),i){var ut=u.e.Lerp(ue[0],ue[2],Ie/o),qe=u.e.Lerp(ue[1],ue[2],Ie/o);Fe=u.e.Lerp(ut,qe,Ne/(o-Ie))}else Fe=new u.e(rt.x,rt.y,rt.z);Fe.x/=a,Fe.y/=s,Fe.z/=d,Fe.normalize();var at=u.d.Lerp(fe[0],fe[2],xe/o),ot=u.d.Lerp(fe[1],fe[2],xe/o),Je=o===xe?fe[2]:u.d.Lerp(at,ot,Le/(o-xe));J.push(rt.x*a,rt.y*s,rt.z*d),ie.push(Fe.x,Fe.y,Fe.z),se.push(Je.x,Je.y),z.push(ce),ce++},Pe=0;Pe0)?1:0)+((ut=u.e.Dot(xe[nt+1].position,Ne)-Ie>0)?1:0)+((qe=u.e.Dot(xe[nt+2].position,Ne)-Ie>0)?1:0)){case 0:Ke.push(xe[nt]),Ke.push(xe[nt+1]),Ke.push(xe[nt+2]);break;case 1:if(rt&&(at=xe[nt+1],ot=xe[nt+2],Je=Fe(xe[nt],at),dt=Fe(xe[nt],ot)),ut){at=xe[nt],ot=xe[nt+2],Je=Fe(xe[nt+1],at),dt=Fe(xe[nt+1],ot),Ke.push(Je),Ke.push(ot.clone()),Ke.push(at.clone()),Ke.push(ot.clone()),Ke.push(Je.clone()),Ke.push(dt);break}qe&&(at=xe[nt],ot=xe[nt+1],Je=Fe(xe[nt+2],at),dt=Fe(xe[nt+2],ot)),at&&ot&&Je&&dt&&(Ke.push(at.clone()),Ke.push(ot.clone()),Ke.push(Je),Ke.push(dt),Ke.push(Je.clone()),Ke.push(ot.clone()));break;case 2:rt||(ot=Fe(at=xe[nt].clone(),xe[nt+1]),Je=Fe(at,xe[nt+2]),Ke.push(at),Ke.push(ot),Ke.push(Je)),ut||(ot=Fe(at=xe[nt+1].clone(),xe[nt+2]),Je=Fe(at,xe[nt]),Ke.push(at),Ke.push(ot),Ke.push(Je)),qe||(ot=Fe(at=xe[nt+2].clone(),xe[nt]),Je=Fe(at,xe[nt+1]),Ke.push(at),Ke.push(ot),Ke.push(Je))}}return Ke},Oe=0;OeO||z.deleted||z.isDirty)){for(var J=0;J<3;++J)if(z.error[J]>0,function(y){if(o){var P=y+s.verticesStart,O=u.e.FromArray(o,3*P),U=function(F){if(n){for(var z=0;z0&&this._reconstructedMesh.setVerticesData(Me.b.NormalKind,s),d.length>0&&this._reconstructedMesh.setVerticesData(Me.b.UVKind,d),p.length>0&&this._reconstructedMesh.setVerticesData(Me.b.ColorKind,p);var ue=this._mesh.subMeshes[t];t>0&&(this._reconstructedMesh.subMeshes=[],ie.forEach(function(fe){To.a.AddToMesh(fe.materialIndex,fe.verticesStart,fe.verticesCount,fe.indexStart,fe.indexCount,fe.getMesh())}),To.a.AddToMesh(ue.materialIndex,J,U,z,3*o.length,this._reconstructedMesh))},r.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new De.a(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},r.prototype.isFlipped=function(t,e,n,i,o){for(var a=0;a.999)return!0;var U=u.e.Cross(P,O).normalize();if(i[a]=!1,u.e.Dot(U,s.normal)<.2)return!0}else i[a]=!0,o.push(s)}}return!1},r.prototype.updateTriangles=function(t,e,n,i){for(var o=i,a=0;a=this._thinInstanceDataStorage.instancesCount)return!1;var n=this._thinInstanceDataStorage.matrixData;return t.copyToArray(n,16*r),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[r]=t),e&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},De.a.prototype.thinInstanceSetAttributeAt=function(r,t,e,n){return n===void 0&&(n=!0),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[r]||t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(r,0),this._userThinInstanceBuffersStorage.data[r].set(e,t*this._userThinInstanceBuffersStorage.strides[r]),n&&this.thinInstanceBufferUpdated(r),!0)},Object.defineProperty(De.a.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(r){var t,e;r<=((e=(t=this._thinInstanceDataStorage.matrixData)===null||t===void 0?void 0:t.length)!==null&&e!==void 0?e:0)/16&&(this._thinInstanceDataStorage.instancesCount=r)},enumerable:!0,configurable:!0}),De.a.prototype.thinInstanceSetBuffer=function(r,t,e,n){var i,o;if(e===void 0&&(e=0),n===void 0&&(n=!1),e=e||16,r==="matrix")if((i=this._thinInstanceDataStorage.matrixBuffer)===null||i===void 0||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*e,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,t!==null){this._thinInstanceDataStorage.instancesCount=t.length/e;var a=new Me.a(this.getEngine(),t,!n,e,!1,!0);this._thinInstanceDataStorage.matrixBuffer=a,this.setVerticesBuffer(a.createVertexBuffer("world0",0,4)),this.setVerticesBuffer(a.createVertexBuffer("world1",4,4)),this.setVerticesBuffer(a.createVertexBuffer("world2",8,4)),this.setVerticesBuffer(a.createVertexBuffer("world3",12,4)),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)}else this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo(!0);else t===null?!((o=this._userThinInstanceBuffersStorage)===null||o===void 0)&&o.data[r]&&(this.removeVerticesData(r),delete this._userThinInstanceBuffersStorage.data[r],delete this._userThinInstanceBuffersStorage.strides[r],delete this._userThinInstanceBuffersStorage.sizes[r],delete this._userThinInstanceBuffersStorage.vertexBuffers[r]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[r]=t,this._userThinInstanceBuffersStorage.strides[r]=e,this._userThinInstanceBuffersStorage.sizes[r]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[r]=new Me.b(this.getEngine(),t,r,!n,!1,e,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[r]))},De.a.prototype.thinInstanceBufferUpdated=function(r){var t;r==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):!((t=this._userThinInstanceBuffersStorage)===null||t===void 0)&&t.vertexBuffers[r]&&this._userThinInstanceBuffersStorage.vertexBuffers[r].updateDirectly(this._userThinInstanceBuffersStorage.data[r],0)},De.a.prototype.thinInstancePartialBufferUpdate=function(r,t,e){var n;r==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,e):!((n=this._userThinInstanceBuffersStorage)===null||n===void 0)&&n.vertexBuffers[r]&&this._userThinInstanceBuffersStorage.vertexBuffers[r].updateDirectly(t,e)},De.a.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];var r=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=new Array;for(var t=0;t-1&&(this.agents.splice(e,1),this.transforms.splice(e,1))},r.prototype.getAgents=function(){return this.agents},r.prototype.update=function(t){var e=this.bjsRECASTPlugin.getTimeStep(),n=this.bjsRECASTPlugin.getMaximumSubStepCount();if(e<=Gt.a)this.recastCrowd.update(t);else{var i=t/e;n&&i>n&&(i=n),i<1&&(i=1);for(var o=0;o=400&&o?o(p):e()},!1),p.addEventListener("error",function(){l.a.Error("error on XHR request."),e()},!1),p.send()}else l.a.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),e()},r._ValidateXHRData=function(t,e){e===void 0&&(e=7);try{if(1&e){if(t.responseText&&t.responseText.length>0)return!0;if(e===1)return!1}if(2&e){var n=pa.GetTGAHeader(t.response);if(n.width&&n.height&&n.width>0&&n.height>0)return!0;if(e===2)return!1}if(4&e){var i=new Uint8Array(t.response,0,3);return i[0]===68&&i[1]===68&&i[2]===83}}catch{}return!1},r.IsUASupportingBlobStorage=!0,r.IDBStorageEnabled=!1,r._ParseURL=function(t){document.createElement("a").href=t;var e=t.substring(0,t.lastIndexOf("#")),n=t.substring(e.lastIndexOf("/")+1,t.length);return t.substring(0,t.indexOf(n,0))},r._ReturnFullUrlLocation=function(t){return t.indexOf("http:/")===-1&&t.indexOf("https:/")===-1&&typeof window<"u"?r._ParseURL(window.location.href)+t:t},r}(),Lc=function(){function r(t,e,n){this.gradient=t,this.color1=e,this.color2=n}return r.prototype.getColorToRef=function(t){this.color2?M.b.LerpToRef(this.color1,this.color2,Math.random(),t):t.copyFrom(this.color1)},r}(),Ld=function(r,t){this.gradient=r,this.color=t},Nc=function(){function r(t,e,n){this.gradient=t,this.factor1=e,this.factor2=n}return r.prototype.getFactor=function(){return this.factor2===void 0||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()},r}(),On=function(){function r(){}return r.GetCurrentGradient=function(t,e,n){if(e[0].gradient>t)n(e[0],e[0],1);else{for(var i=0;i=o.gradient&&t<=a.gradient)return void n(o,a,(t-o.gradient)/(a.gradient-o.gradient))}var s=e.length-1;n(e[s],e[s],1)}},r}(),Nd=function(){function r(t){this.particleSystem=t,this.position=u.e.Zero(),this.direction=u.e.Zero(),this.color=new M.b(0,0,0,0),this.colorStep=new M.b(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new u.d(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new M.b(0,0,0,0),this._currentColor2=new M.b(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=r._Count++,this.particleSystem.isAnimationSheetEnabled&&this.updateCellInfoFromSystem()}return r.prototype.updateCellInfoFromSystem=function(){this.cellIndex=this.particleSystem.startSpriteCellID},r.prototype.updateCellIndex=function(){var t=this.age,e=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(this._randomCellOffset===void 0&&(this._randomCellOffset=Math.random()*this.lifeTime),e===0?(e=1,t=this._randomCellOffset):t+=this._randomCellOffset);var n=this._initialEndSpriteCellID-this._initialStartSpriteCellID,i=$.a.Clamp(t*e%this.lifeTime/this.lifeTime);this.cellIndex=this._initialStartSpriteCellID+i*n|0},r.prototype._inheritParticleInfoToSubEmitter=function(t){if(t.particleSystem.emitter.position){var e=t.particleSystem.emitter;if(e.position.copyFrom(this.position),t.inheritDirection){var n=u.c.Vector3[0];this.direction.normalizeToRef(n),e.setDirection(n,0,Math.PI/2)}}else t.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(t.inheritedVelocityAmount/2,u.c.Vector3[0]),t.particleSystem._inheritedVelocityOffset.copyFrom(u.c.Vector3[0])},r.prototype._inheritParticleInfoToSubEmitters=function(){var t=this;this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(function(e){t._inheritParticleInfoToSubEmitter(e)})},r.prototype._reset=function(){this.age=0,this.id=r._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},r.prototype.copyTo=function(t){t.position.copyFrom(this.position),this._initialDirection?t._initialDirection?t._initialDirection.copyFrom(this._initialDirection):t._initialDirection=this._initialDirection.clone():t._initialDirection=null,t.direction.copyFrom(this.direction),this._localPosition&&(t._localPosition?t._localPosition.copyFrom(this._localPosition):t._localPosition=this._localPosition.clone()),t.color.copyFrom(this.color),t.colorStep.copyFrom(this.colorStep),t.lifeTime=this.lifeTime,t.age=this.age,t._randomCellOffset=this._randomCellOffset,t.size=this.size,t.scale.copyFrom(this.scale),t.angle=this.angle,t.angularSpeed=this.angularSpeed,t.particleSystem=this.particleSystem,t.cellIndex=this.cellIndex,t.id=this.id,t._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(t._currentColorGradient=this._currentColorGradient,t._currentColor1.copyFrom(this._currentColor1),t._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(t._currentSizeGradient=this._currentSizeGradient,t._currentSize1=this._currentSize1,t._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(t._currentAngularSpeedGradient=this._currentAngularSpeedGradient,t._currentAngularSpeed1=this._currentAngularSpeed1,t._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(t._currentVelocityGradient=this._currentVelocityGradient,t._currentVelocity1=this._currentVelocity1,t._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(t._currentLimitVelocityGradient=this._currentLimitVelocityGradient,t._currentLimitVelocity1=this._currentLimitVelocity1,t._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(t._currentDragGradient=this._currentDragGradient,t._currentDrag1=this._currentDrag1,t._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this._initialStartSpriteCellID,t._initialEndSpriteCellID=this._initialEndSpriteCellID),this.particleSystem.useRampGradients&&(t.remapData&&this.remapData?t.remapData.copyFrom(this.remapData):t.remapData=new u.f(0,0,0,0)),this._randomNoiseCoordinates1&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),t._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(t._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),t._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))},r._Count=0,r}();(function(r){r[r.ATTACHED=0]="ATTACHED",r[r.END=1]="END"})(wr||(wr={}));var Co=function(){function r(t){if(this.particleSystem=t,this.type=wr.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!t.emitter||!t.emitter.dispose){var e=R.a.GetClass("BABYLON.AbstractMesh");t.emitter=new e("SubemitterSystemEmitter",t.getScene())}t.onDisposeObservable.add(function(){t.emitter&&t.emitter.dispose&&t.emitter.dispose()})}return r.prototype.clone=function(){var t=this.particleSystem.emitter;t?t instanceof u.e?t=t.clone():t.getClassName().indexOf("Mesh")!==-1&&((t=new(R.a.GetClass("BABYLON.Mesh"))("",t.getScene())).isVisible=!1):t=new u.e;var e=new r(this.particleSystem.clone("",t));return e.particleSystem.name+="Clone",e.type=this.type,e.inheritDirection=this.inheritDirection,e.inheritedVelocityAmount=this.inheritedVelocityAmount,e.particleSystem._disposeEmitterOnDispose=!0,e.particleSystem.disposeOnStop=!0,e},r.prototype.serialize=function(){var t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(),t},r._ParseParticleSystem=function(t,e,n){throw En.a.WarnImport("ParseParticle")},r.Parse=function(t,e,n){var i=t.particleSystem,o=new r(r._ParseParticleSystem(i,e,n));return o.type=t.type,o.inheritDirection=t.inheritDirection,o.inheritedVelocityAmount=t.inheritedVelocityAmount,o.particleSystem._isSubEmitter=!0,o},r.prototype.dispose=function(){this.particleSystem.dispose()},r}(),tg=` -varying vec2 vUV; -varying vec4 vColor; -uniform vec4 textureMask; -uniform sampler2D diffuseSampler; -#include -#include -#include -#include -#ifdef RAMPGRADIENT -varying vec4 remapRanges; -uniform sampler2D rampSampler; -#endif -void main(void) { -#include -vec4 textureColor=texture2D(diffuseSampler,vUV); -vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; -#ifdef RAMPGRADIENT -float alpha=baseColor.a; -float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0); -vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.)); -baseColor.rgb*=rampColor.rgb; - -float finalAlpha=baseColor.a; -baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); -#endif -#ifdef BLENDMULTIPLYMODE -float sourceAlpha=vColor.a*textureColor.a; -baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); -#endif - - -#ifdef IMAGEPROCESSINGPOSTPROCESS -baseColor.rgb=toLinearSpace(baseColor.rgb); -#else -#ifdef IMAGEPROCESSING -baseColor.rgb=toLinearSpace(baseColor.rgb); -baseColor=applyImageProcessing(baseColor); -#endif -#endif -gl_FragColor=baseColor; -}`;je.a.ShadersStore.particlesPixelShader=tg;var ng=` -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 -#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 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; -return position+alignedCorner; -} -#endif -void main(void) { -vec2 cornerPos; -cornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot; -#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.; -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.; -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.; -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.; -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 -}`;je.a.ShadersStore.particlesVertexShader=ng;var ln=function(r){function t(e,n,i,o,a,s){o===void 0&&(o=null),a===void 0&&(a=!1),s===void 0&&(s=.01);var d=r.call(this,e)||this;return d._inheritedVelocityOffset=new u.e,d.onDisposeObservable=new x.c,d.onStoppedObservable=new x.c,d._particles=new Array,d._stockParticles=new Array,d._newPartsExcess=0,d._vertexBuffers={},d._scaledColorStep=new M.b(0,0,0,0),d._colorDiff=new M.b(0,0,0,0),d._scaledDirection=u.e.Zero(),d._scaledGravity=u.e.Zero(),d._currentRenderId=-1,d._useInstancing=!1,d._started=!1,d._stopped=!1,d._actualFrame=0,d._currentEmitRate1=0,d._currentEmitRate2=0,d._currentStartSize1=0,d._currentStartSize2=0,d._rawTextureWidth=256,d._useRampGradients=!1,d._disposeEmitterOnDispose=!1,d.isLocal=!1,d._onBeforeDrawParticlesObservable=null,d.recycleParticle=function(p){var y=d._particles.pop();y!==p&&y.copyTo(p),d._stockParticles.push(y)},d._createParticle=function(){var p;if(d._stockParticles.length!==0?(p=d._stockParticles.pop())._reset():p=new Nd(d),d._subEmitters&&d._subEmitters.length>0){var y=d._subEmitters[Math.floor(Math.random()*d._subEmitters.length)];p._attachedSubEmitters=[],y.forEach(function(P){if(P.type===wr.ATTACHED){var O=P.clone();p._attachedSubEmitters.push(O),O.particleSystem.start()}})}return p},d._emitFromParticle=function(p){if(d._subEmitters&&d._subEmitters.length!==0){var y=Math.floor(Math.random()*d._subEmitters.length);d._subEmitters[y].forEach(function(P){if(P.type===wr.END){var O=P.clone();p._inheritParticleInfoToSubEmitter(O),O.particleSystem._rootParticleSystem=d,d.activeSubSystems.push(O.particleSystem),O.particleSystem.start()}})}},d._capacity=n,d._epsilon=s,d._isAnimationSheetEnabled=a,i&&i.getClassName()!=="Scene"?(d._engine=i,d.defaultProjectionMatrix=u.a.PerspectiveFovLH(.8,1,.1,100)):(d._scene=i||te.a.LastCreatedScene,d._engine=d._scene.getEngine(),d.uniqueId=d._scene.getUniqueId(),d._scene.particleSystems.push(d)),d._engine.getCaps().vertexArrayObject&&(d._vertexArrayObject=null),d._attachImageProcessingConfiguration(null),d._customEffect={0:o},d._useInstancing=d._engine.getCaps().instancedArrays,d._createIndexBuffer(),d._createVertexBuffers(),d.particleEmitterType=new Lr,d.updateFunction=function(p){var y=null,P=null;d.noiseTexture&&(y=d.noiseTexture.getSize(),P=d.noiseTexture.getContent());for(var O,U=function(){O=p[F];var z=d._scaledUpdateSpeed,J=O.age;if(O.age+=z,O.age>O.lifeTime){var ie=O.age-J;z=(O.lifeTime-J)*z/ie,O.age=O.lifeTime}var se=O.age/O.lifeTime;d._colorGradients&&d._colorGradients.length>0?On.GetCurrentGradient(se,d._colorGradients,function(Pe,Ee,Se){Pe!==O._currentColorGradient&&(O._currentColor1.copyFrom(O._currentColor2),Ee.getColorToRef(O._currentColor2),O._currentColorGradient=Pe),M.b.LerpToRef(O._currentColor1,O._currentColor2,Se,O.color)}):(O.colorStep.scaleToRef(z,d._scaledColorStep),O.color.addInPlace(d._scaledColorStep),O.color.a<0&&(O.color.a=0)),d._angularSpeedGradients&&d._angularSpeedGradients.length>0&&On.GetCurrentGradient(se,d._angularSpeedGradients,function(Pe,Ee,Se){Pe!==O._currentAngularSpeedGradient&&(O._currentAngularSpeed1=O._currentAngularSpeed2,O._currentAngularSpeed2=Ee.getFactor(),O._currentAngularSpeedGradient=Pe),O.angularSpeed=$.a.Lerp(O._currentAngularSpeed1,O._currentAngularSpeed2,Se)}),O.angle+=O.angularSpeed*z;var ce=z;if(d._velocityGradients&&d._velocityGradients.length>0&&On.GetCurrentGradient(se,d._velocityGradients,function(Pe,Ee,Se){Pe!==O._currentVelocityGradient&&(O._currentVelocity1=O._currentVelocity2,O._currentVelocity2=Ee.getFactor(),O._currentVelocityGradient=Pe),ce*=$.a.Lerp(O._currentVelocity1,O._currentVelocity2,Se)}),O.direction.scaleToRef(ce,d._scaledDirection),d._limitVelocityGradients&&d._limitVelocityGradients.length>0&&On.GetCurrentGradient(se,d._limitVelocityGradients,function(Pe,Ee,Se){Pe!==O._currentLimitVelocityGradient&&(O._currentLimitVelocity1=O._currentLimitVelocity2,O._currentLimitVelocity2=Ee.getFactor(),O._currentLimitVelocityGradient=Pe);var Le=$.a.Lerp(O._currentLimitVelocity1,O._currentLimitVelocity2,Se);O.direction.length()>Le&&O.direction.scaleInPlace(d.limitVelocityDamping)}),d._dragGradients&&d._dragGradients.length>0&&On.GetCurrentGradient(se,d._dragGradients,function(Pe,Ee,Se){Pe!==O._currentDragGradient&&(O._currentDrag1=O._currentDrag2,O._currentDrag2=Ee.getFactor(),O._currentDragGradient=Pe);var Le=$.a.Lerp(O._currentDrag1,O._currentDrag2,Se);d._scaledDirection.scaleInPlace(1-Le)}),d.isLocal&&O._localPosition?(O._localPosition.addInPlace(d._scaledDirection),u.e.TransformCoordinatesToRef(O._localPosition,d._emitterWorldMatrix,O.position)):O.position.addInPlace(d._scaledDirection),P&&y&&O._randomNoiseCoordinates1){var ue=d._fetchR(O._randomNoiseCoordinates1.x,O._randomNoiseCoordinates1.y,y.width,y.height,P),fe=d._fetchR(O._randomNoiseCoordinates1.z,O._randomNoiseCoordinates2.x,y.width,y.height,P),ve=d._fetchR(O._randomNoiseCoordinates2.y,O._randomNoiseCoordinates2.z,y.width,y.height,P),Te=u.c.Vector3[0],Oe=u.c.Vector3[1];Te.copyFromFloats((2*ue-1)*d.noiseStrength.x,(2*fe-1)*d.noiseStrength.y,(2*ve-1)*d.noiseStrength.z),Te.scaleToRef(z,Oe),O.direction.addInPlace(Oe)}if(d.gravity.scaleToRef(z,d._scaledGravity),O.direction.addInPlace(d._scaledGravity),d._sizeGradients&&d._sizeGradients.length>0&&On.GetCurrentGradient(se,d._sizeGradients,function(Pe,Ee,Se){Pe!==O._currentSizeGradient&&(O._currentSize1=O._currentSize2,O._currentSize2=Ee.getFactor(),O._currentSizeGradient=Pe),O.size=$.a.Lerp(O._currentSize1,O._currentSize2,Se)}),d._useRampGradients&&(d._colorRemapGradients&&d._colorRemapGradients.length>0&&On.GetCurrentGradient(se,d._colorRemapGradients,function(Pe,Ee,Se){var Le=$.a.Lerp(Pe.factor1,Ee.factor1,Se),xe=$.a.Lerp(Pe.factor2,Ee.factor2,Se);O.remapData.x=Le,O.remapData.y=xe-Le}),d._alphaRemapGradients&&d._alphaRemapGradients.length>0&&On.GetCurrentGradient(se,d._alphaRemapGradients,function(Pe,Ee,Se){var Le=$.a.Lerp(Pe.factor1,Ee.factor1,Se),xe=$.a.Lerp(Pe.factor2,Ee.factor2,Se);O.remapData.z=Le,O.remapData.w=xe-Le})),d._isAnimationSheetEnabled&&O.updateCellIndex(),O._inheritParticleInfoToSubEmitters(),O.age>=O.lifeTime)return d._emitFromParticle(O),O._attachedSubEmitters&&(O._attachedSubEmitters.forEach(function(Pe){Pe.particleSystem.disposeOnStop=!0,Pe.particleSystem.stop()}),O._attachedSubEmitters=null),d.recycleParticle(O),F--,"continue"},F=0;Fd.gradient?1:0})},t.prototype._removeFactorGradient=function(e,n){if(e)for(var i=0,o=0,a=e;on.gradient?1:0}),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())},t.prototype.addRampGradient=function(e,n){this._rampGradients||(this._rampGradients=[]);var i=new Ld(e,n);return this._rampGradients.push(i),this._syncRampGradientTexture(),this},t.prototype.removeRampGradient=function(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this},t.prototype.addColorGradient=function(e,n,i){this._colorGradients||(this._colorGradients=[]);var o=new Lc(e,n,i);return this._colorGradients.push(o),this._colorGradients.sort(function(a,s){return a.gradients.gradient?1:0}),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var n=0,i=0,o=this._colorGradients;i0&&(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){((n=this.emitter)===null||n===void 0?void 0:n.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);var o=this.noiseTexture;if(o&&o.onGeneratedObservable)o.onGeneratedObservable.addOnce(function(){setTimeout(function(){for(var s=0;s0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}},t.prototype.stop=function(e){e===void 0&&(e=!0),this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())},t.prototype.reset=function(){this._stockParticles=[],this._particles=[]},t.prototype._appendParticleVertex=function(e,n,i,o){var a=e*this._vertexBufferSize;if(this._vertexData[a++]=n.position.x+this.worldOffset.x,this._vertexData[a++]=n.position.y+this.worldOffset.y,this._vertexData[a++]=n.position.z+this.worldOffset.z,this._vertexData[a++]=n.color.r,this._vertexData[a++]=n.color.g,this._vertexData[a++]=n.color.b,this._vertexData[a++]=n.color.a,this._vertexData[a++]=n.angle,this._vertexData[a++]=n.scale.x*n.size,this._vertexData[a++]=n.scale.y*n.size,this._isAnimationSheetEnabled&&(this._vertexData[a++]=n.cellIndex),this._isBillboardBased)this.billboardMode===t.BILLBOARDMODE_STRETCHED&&(this._vertexData[a++]=n.direction.x,this._vertexData[a++]=n.direction.y,this._vertexData[a++]=n.direction.z);else if(n._initialDirection){var s=n._initialDirection;this.isLocal&&(u.e.TransformNormalToRef(s,this._emitterWorldMatrix,u.c.Vector3[0]),s=u.c.Vector3[0]),s.x===0&&s.z===0&&(s.x=.001),this._vertexData[a++]=s.x,this._vertexData[a++]=s.y,this._vertexData[a++]=s.z}else{var d=n.direction;this.isLocal&&(u.e.TransformNormalToRef(d,this._emitterWorldMatrix,u.c.Vector3[0]),d=u.c.Vector3[0]),d.x===0&&d.z===0&&(d.x=.001),this._vertexData[a++]=d.x,this._vertexData[a++]=d.y,this._vertexData[a++]=d.z}this._useRampGradients&&n.remapData&&(this._vertexData[a++]=n.remapData.x,this._vertexData[a++]=n.remapData.y,this._vertexData[a++]=n.remapData.z,this._vertexData[a++]=n.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),o===0?o=this._epsilon:o===1&&(o=1-this._epsilon)),this._vertexData[a++]=i,this._vertexData[a++]=o)},t.prototype._stopSubEmitters=function(){this.activeSubSystems&&(this.activeSubSystems.forEach(function(e){e.stop(!0)}),this.activeSubSystems=new Array)},t.prototype._removeFromRoot=function(){if(this._rootParticleSystem){var e=this._rootParticleSystem.activeSubSystems.indexOf(this);e!==-1&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}},t.prototype._update=function(e){var n,i=this;if(this._alive=this._particles.length>0,this.emitter.position){var o=this.emitter;this._emitterWorldMatrix=o.getWorldMatrix()}else{var a=this.emitter;this._emitterWorldMatrix=u.a.Translation(a.x,a.y,a.z)}this.updateFunction(this._particles);for(var s,d=function(){if(p._particles.length===p._capacity)return"break";if(n=p._createParticle(),p._particles.push(n),p.targetStopDuration&&p._lifeTimeGradients&&p._lifeTimeGradients.length>0){var P=$.a.Clamp(p._actualFrame/p.targetStopDuration);On.GetCurrentGradient(P,p._lifeTimeGradients,function(F,z){var J=F,ie=z,se=J.getFactor(),ce=ie.getFactor(),ue=(P-J.gradient)/(ie.gradient-J.gradient);n.lifeTime=$.a.Lerp(se,ce,ue)})}else n.lifeTime=$.a.RandomRange(p.minLifeTime,p.maxLifeTime);var O=$.a.RandomRange(p.minEmitPower,p.maxEmitPower);if(p.startPositionFunction?p.startPositionFunction(p._emitterWorldMatrix,n.position,n,p.isLocal):p.particleEmitterType.startPositionFunction(p._emitterWorldMatrix,n.position,n,p.isLocal),p.isLocal&&(n._localPosition?n._localPosition.copyFrom(n.position):n._localPosition=n.position.clone(),u.e.TransformCoordinatesToRef(n._localPosition,p._emitterWorldMatrix,n.position)),p.startDirectionFunction?p.startDirectionFunction(p._emitterWorldMatrix,n.direction,n,p.isLocal):p.particleEmitterType.startDirectionFunction(p._emitterWorldMatrix,n.direction,n,p.isLocal),O===0?n._initialDirection?n._initialDirection.copyFrom(n.direction):n._initialDirection=n.direction.clone():n._initialDirection=null,n.direction.scaleInPlace(O),p._sizeGradients&&p._sizeGradients.length!==0?(n._currentSizeGradient=p._sizeGradients[0],n._currentSize1=n._currentSizeGradient.getFactor(),n.size=n._currentSize1,p._sizeGradients.length>1?n._currentSize2=p._sizeGradients[1].getFactor():n._currentSize2=n._currentSize1):n.size=$.a.RandomRange(p.minSize,p.maxSize),n.scale.copyFromFloats($.a.RandomRange(p.minScaleX,p.maxScaleX),$.a.RandomRange(p.minScaleY,p.maxScaleY)),p._startSizeGradients&&p._startSizeGradients[0]&&p.targetStopDuration){var U=p._actualFrame/p.targetStopDuration;On.GetCurrentGradient(U,p._startSizeGradients,function(F,z,J){F!==i._currentStartSizeGradient&&(i._currentStartSize1=i._currentStartSize2,i._currentStartSize2=z.getFactor(),i._currentStartSizeGradient=F);var ie=$.a.Lerp(i._currentStartSize1,i._currentStartSize2,J);n.scale.scaleInPlace(ie)})}p._angularSpeedGradients&&p._angularSpeedGradients.length!==0?(n._currentAngularSpeedGradient=p._angularSpeedGradients[0],n.angularSpeed=n._currentAngularSpeedGradient.getFactor(),n._currentAngularSpeed1=n.angularSpeed,p._angularSpeedGradients.length>1?n._currentAngularSpeed2=p._angularSpeedGradients[1].getFactor():n._currentAngularSpeed2=n._currentAngularSpeed1):n.angularSpeed=$.a.RandomRange(p.minAngularSpeed,p.maxAngularSpeed),n.angle=$.a.RandomRange(p.minInitialRotation,p.maxInitialRotation),p._velocityGradients&&p._velocityGradients.length>0&&(n._currentVelocityGradient=p._velocityGradients[0],n._currentVelocity1=n._currentVelocityGradient.getFactor(),p._velocityGradients.length>1?n._currentVelocity2=p._velocityGradients[1].getFactor():n._currentVelocity2=n._currentVelocity1),p._limitVelocityGradients&&p._limitVelocityGradients.length>0&&(n._currentLimitVelocityGradient=p._limitVelocityGradients[0],n._currentLimitVelocity1=n._currentLimitVelocityGradient.getFactor(),p._limitVelocityGradients.length>1?n._currentLimitVelocity2=p._limitVelocityGradients[1].getFactor():n._currentLimitVelocity2=n._currentLimitVelocity1),p._dragGradients&&p._dragGradients.length>0&&(n._currentDragGradient=p._dragGradients[0],n._currentDrag1=n._currentDragGradient.getFactor(),p._dragGradients.length>1?n._currentDrag2=p._dragGradients[1].getFactor():n._currentDrag2=n._currentDrag1),p._colorGradients&&p._colorGradients.length!==0?(n._currentColorGradient=p._colorGradients[0],n._currentColorGradient.getColorToRef(n.color),n._currentColor1.copyFrom(n.color),p._colorGradients.length>1?p._colorGradients[1].getColorToRef(n._currentColor2):n._currentColor2.copyFrom(n.color)):(s=$.a.RandomRange(0,1),M.b.LerpToRef(p.color1,p.color2,s,n.color),p.colorDead.subtractToRef(n.color,p._colorDiff),p._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)),p._isAnimationSheetEnabled&&(n._initialStartSpriteCellID=p.startSpriteCellID,n._initialEndSpriteCellID=p.endSpriteCellID),n.direction.addInPlace(p._inheritedVelocityOffset),p._useRampGradients&&(n.remapData=new u.f(0,1,0,1)),p.noiseTexture&&(n._randomNoiseCoordinates1?(n._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),n._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(n._randomNoiseCoordinates1=new u.e(Math.random(),Math.random(),Math.random()),n._randomNoiseCoordinates2=new u.e(Math.random(),Math.random(),Math.random()))),n._inheritParticleInfoToSubEmitters()},p=this,y=0;y-1)o=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{var a=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){var s=this._actualFrame/this.targetStopDuration;On.GetCurrentGradient(s,this._emitRateGradients,function(P,O,U){P!==i._currentEmitRateGradient&&(i._currentEmitRate1=i._currentEmitRate2,i._currentEmitRate2=O.getFactor(),i._currentEmitRateGradient=P),a=$.a.Lerp(i._currentEmitRate1,i._currentEmitRate2,U)})}o=a*this._scaledUpdateSpeed>>0,this._newPartsExcess+=a*this._scaledUpdateSpeed-o}if(this._newPartsExcess>1&&(o+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?o=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(o),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){for(var d=0,p=0;p=0&&(s.invertToRef(u.c.Matrix[0]),o.setMatrix("invView",u.c.Matrix[0])),this._vertexArrayObject!==void 0?(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,o)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):a.bindBuffers(this._vertexBuffers,this._indexBuffer,o),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(o),e){case t.BLENDMODE_ADD:a.setAlphaMode(h.a.ALPHA_ADD);break;case t.BLENDMODE_ONEONE:a.setAlphaMode(h.a.ALPHA_ONEONE);break;case t.BLENDMODE_STANDARD:a.setAlphaMode(h.a.ALPHA_COMBINE);break;case t.BLENDMODE_MULTIPLY:a.setAlphaMode(h.a.ALPHA_MULTIPLY)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(o),this._useInstancing?a.drawArraysType(h.a.MATERIAL_TriangleFanDrawMode,0,4,this._particles.length):a.drawElementsType(h.a.MATERIAL_TriangleFillMode,0,6*this._particles.length),this._particles.length},t.prototype.render=function(){if(!this.isReady()||!this._particles.length)return 0;var e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));var n=0;return n=this.blendMode===t.BLENDMODE_MULTIPLYADD?this._render(t.BLENDMODE_MULTIPLY)+this._render(t.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(h.a.ALPHA_DISABLE),n},t.prototype.dispose=function(e){if(e===void 0&&(e=!0),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this._subEmitters&&this._subEmitters.length){for(var n=0;n-1&&this._scene.particleSystems.splice(n,1),this._scene._activeParticleSystems.dispose()),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()},t.prototype.clone=function(e,n){var i=Object(c.a)({},this._customEffect),o=null,a=this._engine;if(a.createEffectForParticles&&this.customShader!=null){var s=(o=this.customShader).shaderOptions.defines.length>0?o.shaderOptions.defines.join(` -`):"";i[0]=a.createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s)}var d=this.serialize(),p=t.Parse(d,this._scene||this._engine,"");return p.name=e,p.customShader=o,p._customEffect=i,n===void 0&&(n=this.emitter),this.noiseTexture&&(p.noiseTexture=this.noiseTexture.clone()),p.emitter=n,this.preventAutoStart||p.start(),p},t.prototype.serialize=function(e){e===void 0&&(e=!1);var n={};if(t._Serialize(n,this,e),n.textureMask=this.textureMask.asArray(),n.customShader=this.customShader,n.preventAutoStart=this.preventAutoStart,this.subEmitters){n.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(var i=0,o=this._subEmitters;i0?p.shaderOptions.defines.join(` -`):"";d=a.createEffectForParticles(p.shaderPath.fragmentElement,p.shaderOptions.uniforms,p.shaderOptions.samplers,y)}var P=new t(s,e.capacity,n,d,e.isAnimationSheetEnabled);if(P.customShader=p,e.id&&(P.id=e.id),e.subEmitters){P.subEmitters=[];for(var O=0,U=e.subEmitters;O=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=direction1+(direction2-direction1)*randoms3; -#else - -newDirection=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); -newDirection=vec3(cos(angle),randoms3.y-0.5,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=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0); -outCellIndex=float(int(cellInfos.x+ratio*dist)); -#endif -} -}`;je.a.ShadersStore.gpuUpdateParticlesVertexShader=ig;var rg=`#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`;je.a.IncludesShadersStore.clipPlaneFragmentDeclaration2=rg;var og=`#version 300 es -uniform sampler2D diffuseSampler; -in vec2 vUV; -in vec4 vColor; -out vec4 outFragColor; -#include -#include -#include -#include -void main() { -#include -vec4 textureColor=texture(diffuseSampler,vUV); -outFragColor=textureColor*vColor; -#ifdef BLENDMULTIPLYMODE -float alpha=vColor.a*textureColor.a; -outFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); -#endif - - -#ifdef IMAGEPROCESSINGPOSTPROCESS -outFragColor.rgb=toLinearSpace(outFragColor.rgb); -#else -#ifdef IMAGEPROCESSING -outFragColor.rgb=toLinearSpace(outFragColor.rgb); -outFragColor=applyImageProcessing(outFragColor); -#endif -#endif -} -`;je.a.ShadersStore.gpuRenderParticlesPixelShader=og;var ag=`#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`;je.a.IncludesShadersStore.clipPlaneVertexDeclaration2=ag;var sg=`#version 300 es -uniform mat4 view; -uniform mat4 projection; -uniform vec2 translationPivot; -uniform vec3 worldOffset; -#ifdef LOCAL -uniform mat4 emitterWM; -#endif - -in vec3 position; -in float age; -in float life; -in vec3 size; -#ifndef BILLBOARD -in vec3 initialDirection; -#endif -#ifdef BILLBOARDSTRETCHED -in vec3 direction; -#endif -in float angle; -#ifdef ANIMATESHEET -in float cellIndex; -#endif -in vec2 offset; -in vec2 uv; -out vec2 vUV; -out vec4 vColor; -out vec3 vPositionW; -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include -#ifdef COLORGRADIENTS -uniform sampler2D colorGradientSampler; -#else -uniform vec4 colorDead; -in 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=texture(colorGradientSampler,vec2(ratio,0)); -#else -vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); -#endif -vec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot; -#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.; -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.; -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.; - -#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); -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 -}`;je.a.ShadersStore.gpuRenderParticlesVertexShader=sg;var or=function(r){function t(e,n,i,o,a){o===void 0&&(o=!1),a===void 0&&(a=null);var s=r.call(this,e)||this;s.layerMask=268435455,s._accumulatedCount=0,s._targetIndex=0,s._currentRenderId=-1,s._started=!1,s._stopped=!1,s._timeDelta=0,s._actualFrame=0,s._rawTextureWidth=256,s.onDisposeObservable=new x.c,s.onStoppedObservable=new x.c,s.forceDepthWrite=!1,s._preWarmDone=!1,s.isLocal=!1,s._onBeforeDrawParticlesObservable=null,i&&i.getClassName()!=="Scene"?(s._engine=i,s.defaultProjectionMatrix=u.a.PerspectiveFovLH(.8,1,.1,100)):(s._scene=i||te.a.LastCreatedScene,s._engine=s._scene.getEngine(),s.uniqueId=s._scene.getUniqueId(),s._scene.particleSystems.push(s)),s._customEffect={0:a},s._attachImageProcessingConfiguration(null),n.randomTextureSize||delete n.randomTextureSize;var d=Object(c.a)({capacity:5e4,randomTextureSize:s._engine.getCaps().maxTextureSize},n),p=n;isFinite(p)&&(d.capacity=p),s._capacity=d.capacity,s._activeCount=d.capacity,s._currentActiveCount=0,s._isAnimationSheetEnabled=o,s._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:[]},s.particleEmitterType=new Lr;for(var y=Math.min(s._engine.getCaps().maxTextureSize,d.randomTextureSize),P=[],O=0;O1},enumerable:!1,configurable:!0}),t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this._activeCount},set:function(e){this._activeCount=Math.min(e,this._capacity)},enumerable:!1,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&(!this._imageProcessingConfiguration||this._imageProcessingConfiguration.isReady())&&this._getEffect().isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.isStopped=function(){return this._stopped},t.prototype.isStopping=function(){return!1},t.prototype.getActiveCount=function(){return this._currentActiveCount},t.prototype.start=function(e){var n=this;if(e===void 0&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout(function(){n.start(0)},e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))},t.prototype.stop=function(){this._stopped||(this._stopped=!0)},t.prototype.reset=function(){this._releaseBuffers(),this._releaseVAOs(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},t.prototype.getCustomEffect=function(e){var n;return e===void 0&&(e=0),(n=this._customEffect[e])!==null&&n!==void 0?n:this._customEffect[0]},t.prototype.setCustomEffect=function(e,n){n===void 0&&(n=0),this._customEffect[n]=e},Object.defineProperty(t.prototype,"onBeforeDrawParticlesObservable",{get:function(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new x.c),this._onBeforeDrawParticlesObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vertexShaderName",{get:function(){return"gpuRenderParticles"},enumerable:!1,configurable:!0}),t.prototype._removeGradientAndTexture=function(e,n,i){return r.prototype._removeGradientAndTexture.call(this,e,n,i),this._releaseBuffers(),this},t.prototype.addColorGradient=function(e,n,i){this._colorGradients||(this._colorGradients=[]);var o=new Lc(e,n);return this._colorGradients.push(o),this._refreshColorGradient(!0),this._releaseBuffers(),this},t.prototype._refreshColorGradient=function(e){e===void 0&&(e=!1),this._colorGradients&&(e&&this._colorGradients.sort(function(n,i){return n.gradienti.gradient?1:0}),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))},t.prototype.forceRefreshGradients=function(){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()},t.prototype.removeColorGradient=function(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(e,n,i){var o=new Nc(n,i);e.push(o),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,n){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,n),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},t.prototype._refreshFactorGradient=function(e,n,i){i===void 0&&(i=!1),e&&(i&&e.sort(function(o,a){return o.gradienta.gradient?1:0}),this[n]&&(this[n].dispose(),this[n]=null))},t.prototype.addAngularSpeedGradient=function(e,n){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,n),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,n){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,n),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype.addLimitVelocityGradient=function(e,n){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,n),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeLimitVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this},t.prototype.addDragGradient=function(e,n){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,n),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeDragGradient=function(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this},t.prototype.addEmitRateGradient=function(e,n,i){return this},t.prototype.removeEmitRateGradient=function(e){return this},t.prototype.addStartSizeGradient=function(e,n,i){return this},t.prototype.removeStartSizeGradient=function(e){return this},t.prototype.addColorRemapGradient=function(e,n,i){return this},t.prototype.removeColorRemapGradient=function(){return this},t.prototype.addAlphaRemapGradient=function(e,n,i){return this},t.prototype.removeAlphaRemapGradient=function(){return this},t.prototype.addRampGradient=function(e,n){return this},t.prototype.removeRampGradient=function(){return this},t.prototype.getRampGradients=function(){return null},Object.defineProperty(t.prototype,"useRampGradients",{get:function(){return!1},set:function(e){},enumerable:!1,configurable:!0}),t.prototype.addLifeTimeGradient=function(e,n,i){return this},t.prototype.removeLifeTimeGradient=function(e){return this},t.prototype._reset=function(){this._releaseBuffers()},t.prototype._createUpdateVAO=function(e){var n={};n.position=e.createVertexBuffer("position",0,3);var i=3;this.particleEmitterType instanceof Nr&&(n.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),n.age=e.createVertexBuffer("age",i,1),i+=1,n.life=e.createVertexBuffer("life",i,1),i+=1,n.seed=e.createVertexBuffer("seed",i,4),i+=4,n.size=e.createVertexBuffer("size",i,3),i+=3,this._colorGradientsTexture||(n.color=e.createVertexBuffer("color",i,4),i+=4),n.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(n.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(n.angle=e.createVertexBuffer("angle",i,1),i+=1):(n.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(n.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this.spriteRandomStartCell&&(n.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1)),this.noiseTexture&&(n.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,n.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3);var o=this._engine.recordVertexArrayObject(n,null,this._updateEffect);return this._engine.bindArrayBuffer(null),o},t.prototype._createRenderVAO=function(e,n){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);var o=3;this.particleEmitterType instanceof Nr&&(o+=3),i.age=e.createVertexBuffer("age",o,1,this._attributesStrideSize,!0),o+=1,i.life=e.createVertexBuffer("life",o,1,this._attributesStrideSize,!0),o+=5,i.size=e.createVertexBuffer("size",o,3,this._attributesStrideSize,!0),o+=3,this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",o,4,this._attributesStrideSize,!0),o+=4),this.billboardMode===ln.BILLBOARDMODE_STRETCHED&&(i.direction=e.createVertexBuffer("direction",o,3,this._attributesStrideSize,!0)),o+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",o,3,this._attributesStrideSize,!0),o+=3),i.angle=e.createVertexBuffer("angle",o,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?o++:o+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",o,1,this._attributesStrideSize,!0),o+=1,this.spriteRandomStartCell&&(i.cellStartOffset=e.createVertexBuffer("cellStartOffset",o,1,this._attributesStrideSize,!0),o+=1)),this.noiseTexture&&(i.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",o,3,this._attributesStrideSize,!0),o+=3,i.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",o,3,this._attributesStrideSize,!0),o+=3),i.offset=n.createVertexBuffer("offset",0,2),i.uv=n.createVertexBuffer("uv",2,2);var a=this._engine.recordVertexArrayObject(i,null,this._getEffect());return this._engine.bindArrayBuffer(null),a},t.prototype._initialize=function(e){if(e===void 0&&(e=!1),!this._buffer0||e){var n=this._engine,i=new Array;this._attributesStrideSize=21,this._targetIndex=0,this.particleEmitterType instanceof Nr&&(this._attributesStrideSize+=3),this.isBillboardBased||(this._attributesStrideSize+=3),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);for(var o=this.particleEmitterType instanceof Nr,a=u.c.Vector3[0],s=0;s=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(e,n){var i=this[n];if(e&&e.length&&!i){for(var o=new Float32Array(this._rawTextureWidth),a=0;a1){var a=0|this._accumulatedCount;this._accumulatedCount-=a,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+a)}if(!this._currentActiveCount)return 0;this._engine.enableEffect(this._updateEffect);var s,d=this._engine;if(!d.setState)throw new Error("GPU particles cannot work with a full Engine. ThinEngine is not supported");if(this._updateEffect.setFloat("currentCount",this._currentActiveCount),this._updateEffect.setFloat("timeDelta",this._timeDelta),this._updateEffect.setFloat("stopFactor",this._stopped?0:1),this._updateEffect.setTexture("randomSampler",this._randomTexture),this._updateEffect.setTexture("randomSampler2",this._randomTexture2),this._updateEffect.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateEffect.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateEffect.setDirectColor4("color1",this.color1),this._updateEffect.setDirectColor4("color2",this.color2)),this._updateEffect.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateEffect.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateEffect.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateEffect.setVector3("gravity",this.gravity),this._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._sizeGradientsTexture),this._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._angularSpeedGradientsTexture),this._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._velocityGradientsTexture),this._limitVelocityGradientsTexture&&(this._updateEffect.setTexture("limitVelocityGradientSampler",this._limitVelocityGradientsTexture),this._updateEffect.setFloat("limitVelocityDamping",this.limitVelocityDamping)),this._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._dragGradientsTexture),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateEffect),this._isAnimationSheetEnabled&&this._updateEffect.setFloat3("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed),this.noiseTexture&&(this._updateEffect.setTexture("noiseSampler",this.noiseTexture),this._updateEffect.setVector3("noiseStrength",this.noiseStrength)),this.emitter.position)s=this.emitter.getWorldMatrix();else{var p=this.emitter;s=u.a.Translation(p.x,p.y,p.z)}if(this.isLocal||this._updateEffect.setMatrix("emitterWM",s),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),d.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),d.setRasterizerState(!1),d.beginTransformFeedback(!0),d.drawArraysType(h.a.MATERIAL_PointListDrawMode,0,this._currentActiveCount),d.endTransformFeedback(),d.setRasterizerState(!0),d.bindTransformFeedbackBuffer(null),!e){var y=this._getEffect();this._engine.enableEffect(y);var P=((n=this._scene)===null||n===void 0?void 0:n.getViewMatrix())||u.a.IdentityReadOnly;if(y.setMatrix("view",P),y.setMatrix("projection",(i=this.defaultProjectionMatrix)!==null&&i!==void 0?i:this._scene.getProjectionMatrix()),y.setTexture("diffuseSampler",this.particleTexture),y.setVector2("translationPivot",this.translationPivot),y.setVector3("worldOffset",this.worldOffset),this.isLocal&&y.setMatrix("emitterWM",s),this._colorGradientsTexture?y.setTexture("colorGradientSampler",this._colorGradientsTexture):y.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var O=this.particleTexture.getBaseSize();y.setFloat3("sheetInfos",this.spriteCellWidth/O.width,this.spriteCellHeight/O.height,O.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){var U=this._scene.activeCamera;y.setVector3("eyePosition",U.globalPosition)}var F=y.defines;if(this._scene&&(this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4||this._scene.clipPlane5||this._scene.clipPlane6)&&tt.a.BindClipPlane(y,this._scene),F.indexOf("#define BILLBOARDMODE_ALL")>=0){var z=P.clone();z.invert(),y.setMatrix("invView",z)}switch(this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(y),this.blendMode){case ln.BLENDMODE_ADD:this._engine.setAlphaMode(h.a.ALPHA_ADD);break;case ln.BLENDMODE_ONEONE:this._engine.setAlphaMode(h.a.ALPHA_ONEONE);break;case ln.BLENDMODE_STANDARD:this._engine.setAlphaMode(h.a.ALPHA_COMBINE);break;case ln.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(h.a.ALPHA_MULTIPLY)}this.forceDepthWrite&&d.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(y),this._engine.drawArraysType(h.a.MATERIAL_TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(h.a.ALPHA_DISABLE)}this._targetIndex++,this._targetIndex===2&&(this._targetIndex=0);var J=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=J,this._currentActiveCount},t.prototype.rebuild=function(){this._initialize(!0)},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null)},t.prototype._releaseVAOs=function(){if(this._updateVAO){for(var e=0;e-1&&this._scene.particleSystems.splice(n,1)}this._releaseBuffers(),this._releaseVAOs(),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()},t.prototype.clone=function(e,n){var i=this.serialize(),o=t.Parse(i,this._scene||this._engine,""),a=Object(c.a)({},this._customEffect);return o.name=e,o._customEffect=a,n===void 0&&(n=this.emitter),o.emitter=n,o.noiseTexture=this.noiseTexture,o},t.prototype.serialize=function(e){e===void 0&&(e=!1);var n={};return ln._Serialize(n,this,e),n.activeParticleCount=this.activeParticleCount,n.randomTextureSize=this._randomTextureSize,n},t.Parse=function(e,n,i,o){o===void 0&&(o=!1);var a=new t(e.name,{capacity:e.capacity,randomTextureSize:e.randomTextureSize},n);return e.activeParticleCount&&(a.activeParticleCount=e.activeParticleCount),ln._Parse(e,a,n,i),e.preventAutoStart&&(a.preventAutoStart=e.preventAutoStart),o||a.preventAutoStart||a.start(),a},t}(bo),Pa=function(){function r(){this.systems=new Array}return Object.defineProperty(r.prototype,"emitterNode",{get:function(){return this._emitterNode},enumerable:!1,configurable:!0}),r.prototype.setEmitterAsSphere=function(t,e,n){this._emitterNode&&this._emitterNode.dispose(),this._emitterCreationOptions={kind:"Sphere",options:t,renderingGroupId:e};var i=Nn.a.CreateSphere("emitterSphere",{diameter:t.diameter,segments:t.segments},n);i.renderingGroupId=e;var o=new Ft.a("emitterSphereMaterial",n);o.emissiveColor=t.color,i.material=o;for(var a=0,s=this.systems;a0&&n.set(this._uvs32,Me.b.UVKind),this._colors32.length>0&&n.set(this._colors32,Me.b.ColorKind),n.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){for(var i=0,o=0;oU?U:i,n=Math.round(U/i),o=0):n=n>U?U:n;for(var F=[],z=[],J=[],ie=[],se=[],ce=u.e.Zero(),ue=n;OU-(n=ue+Math.floor((1+o)*Math.random()))&&(n=U-O),F.length=0,z.length=0,J.length=0,ie.length=0,se.length=0;for(var fe=0,ve=3*O;ve<3*(O+n);ve++){J.push(fe);var Te=s[ve],Oe=3*Te;if(F.push(a[Oe],a[Oe+1],a[Oe+2]),z.push(y[Oe],y[Oe+1],y[Oe+2]),d){var Pe=2*Te;ie.push(d[Pe],d[Pe+1])}if(p){var Ee=4*Te;se.push(p[Ee],p[Ee+1],p[Ee+2],p[Ee+3])}fe++}var Se,Le=this.nbParticles,xe=this._posToShape(F),Ne=this._uvsToShapeUV(ie),Ie=Ye.b.Slice(J),Fe=Ye.b.Slice(se),Ke=Ye.b.Slice(z);for(ce.copyFromFloats(0,0,0),Se=0;Se65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){var at=fe.materialIndex!==null?fe.materialIndex:0;this.depthSortedParticles.push(new wd(U,e,o.length,at))}return fe},r.prototype._posToShape=function(t){for(var e=[],n=0;n=this.nbParticles||!this._updatable)return[];var i=this.particles,o=this.nbParticles;if(e=this.nbParticles?this.nbParticles-1:e,this._computeBoundingBox&&(t!=0||e!=this.nbParticles-1)){var nt=this.mesh._boundingInfo;nt&&(se.copyFrom(nt.minimum),ce.copyFrom(nt.maximum))}var rt=(Le=this.particles[t]._pos)/3|0;Ne=4*rt,Fe=2*rt;for(var ut=t;ut<=e;ut++){var qe=this.particles[ut];this.updateParticle(qe);var at=qe._model._shape,ot=qe._model._shapeUV,Je=qe._rotationMatrix,dt=qe.position,Ve=qe.rotation,$e=qe.scaling,yt=qe._globalPosition;if(this._depthSort&&this._depthSortParticles){var Wt=this.depthSortedParticles[ut];Wt.idx=qe.idx,Wt.ind=qe._ind,Wt.indicesLength=qe._model._indicesLength,Wt.sqDistance=u.e.DistanceSquared(qe.position,ue)}if(!qe.alive||qe._stillInvisible&&!qe.isVisible)Le+=3*(Ke=at.length),Ne+=4*Ke,Fe+=2*Ke;else{if(qe.isVisible){qe._stillInvisible=!1;var Nt=F[12];if(qe.pivot.multiplyToRef($e,Nt),this.billboard&&(Ve.x=0,Ve.y=0),(this._computeParticleRotation||this.billboard)&&qe.getRotationMatrix(i),qe.parentId!==null){var Qt=this.getParticleById(qe.parentId);if(Qt){var vt=Qt._rotationMatrix,Jt=Qt._globalPosition,Xt=dt.x*vt[1]+dt.y*vt[4]+dt.z*vt[7],zt=dt.x*vt[0]+dt.y*vt[3]+dt.z*vt[6],Yt=dt.x*vt[2]+dt.y*vt[5]+dt.z*vt[8];if(yt.x=Jt.x+zt,yt.y=Jt.y+Xt,yt.z=Jt.z+Yt,this._computeParticleRotation||this.billboard){var Et=i.m;Je[0]=Et[0]*vt[0]+Et[1]*vt[3]+Et[2]*vt[6],Je[1]=Et[0]*vt[1]+Et[1]*vt[4]+Et[2]*vt[7],Je[2]=Et[0]*vt[2]+Et[1]*vt[5]+Et[2]*vt[8],Je[3]=Et[4]*vt[0]+Et[5]*vt[3]+Et[6]*vt[6],Je[4]=Et[4]*vt[1]+Et[5]*vt[4]+Et[6]*vt[7],Je[5]=Et[4]*vt[2]+Et[5]*vt[5]+Et[6]*vt[8],Je[6]=Et[8]*vt[0]+Et[9]*vt[3]+Et[10]*vt[6],Je[7]=Et[8]*vt[1]+Et[9]*vt[4]+Et[10]*vt[7],Je[8]=Et[8]*vt[2]+Et[9]*vt[5]+Et[10]*vt[8]}}else qe.parentId=null}else yt.x=dt.x,yt.y=dt.y,yt.z=dt.z,(this._computeParticleRotation||this.billboard)&&(Et=i.m,Je[0]=Et[0],Je[1]=Et[1],Je[2]=Et[2],Je[3]=Et[4],Je[4]=Et[5],Je[5]=Et[6],Je[6]=Et[8],Je[7]=Et[9],Je[8]=Et[10]);var Mt=F[11];for(qe.translateFromPivot?Mt.setAll(0):Mt.copyFrom(Nt),Ke=0;Ke0)for(var e=0;e0&&t.set(this._uvs32,Me.b.UVKind);var e=0;this._colors32.length>0&&(e=1,t.set(this._colors32,Me.b.ColorKind));var n=new De.a(this.name,this._scene);t.applyToMesh(n,this._updatable),this.mesh=n,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);var i=new Ft.a("point cloud material",this._scene);return i.emissiveColor=new M.a(e,e,e),i.disableLighting=!0,i.pointsCloud=!0,i.pointSize=this._size,n.material=i,new Promise(function(o){return o(n)})},r.prototype._addParticle=function(t,e,n,i){var o=new Bd(t,e,n,i,this);return this.particles.push(o),o},r.prototype._randomUnitVector=function(t){t.position=new u.e(Math.random(),Math.random(),Math.random()),t.color=new M.b(1,1,1,1)},r.prototype._getColorIndicesForCoord=function(t,e,n,i){var o=t._groupImageData,a=n*(4*i)+4*e,s=[a,a+1,a+2,a+3],d=s[1],p=s[2],y=s[3],P=o[s[0]],O=o[d],U=o[p],F=o[y];return new M.b(P/255,O/255,U/255,F)},r.prototype._setPointsColorOrUV=function(t,e,n,i,o,a,s){n&&t.updateFacetData();var d=2*t.getBoundingInfo().boundingSphere.radius,p=t.getVerticesData(Me.b.PositionKind),y=t.getIndices(),P=t.getVerticesData(Me.b.UVKind),O=t.getVerticesData(Me.b.ColorKind),U=u.e.Zero();t.computeWorldMatrix();var F=t.getWorldMatrix();if(!F.isIdentity())for(var z=0;z1&&(Xi=1),(Yi=Yr.b+Wr)<0&&(Yi=0),Yi>1&&(Yi=1),M.a.HSVtoRGBToRef(Xr,Xi,Yi,ur),jt.set(ur.r,ur.g,ur.b,1)):jt=qt.set(Math.random(),Math.random(),Math.random(),1),Dn.color=new M.b(jt.x,jt.y,jt.z,jt.w),this._colors.push(jt.x,jt.y,jt.z,jt.w))}},r.prototype._colorFromTexture=function(t,e,n){var i=this;if(t.material===null)return l.a.Warn(t.name+"has no material."),e._groupImageData=null,void this._setPointsColorOrUV(t,e,n,!0,!1);var o=t.material.getActiveTextures();if(o.length===0)return l.a.Warn(t.name+"has no useable texture."),e._groupImageData=null,void this._setPointsColorOrUV(t,e,n,!0,!1);var a=t.clone();a.setEnabled(!1),this._promises.push(new Promise(function(s){zn.a.WhenAllReady(o,function(){var d=e._textureNb;return d<0&&(d=0),d>o.length-1&&(d=o.length-1),e._groupImageData=o[d].readPixels(),e._groupImgWidth=o[d].getSize().width,e._groupImgHeight=o[d].getSize().height,i._setPointsColorOrUV(a,e,n,!0,!0),a.dispose(),s()})}))},r.prototype._calculateDensity=function(t,e,n){for(var i,o,a,s,d,p,y,P,O,U,F,z,J,ie,se,ce,ue,fe=new Array,ve=u.e.Zero(),Te=u.e.Zero(),Oe=u.e.Zero(),Pe=u.e.Zero(),Ee=u.e.Zero(),Se=u.e.Zero(),Le=new Array,xe=0,Ne=n.length/3,Ie=0;Ie0&&(fe=fe.map(function(ut){return ut+nt})),Ie=0;Ie3)&&(a=yn.Random);var s=t.getVerticesData(Me.b.PositionKind),d=t.getIndices();this._groups.push(this._groupCounter);var p=new Ca(this._groupCounter,null);switch(p._groupDensity=this._calculateDensity(e,s,d),a===yn.Color?p._textureNb=i||0:i=i||new M.b(1,1,1,1),a){case yn.Color:this._colorFromTexture(t,p,!1);break;case yn.UV:this._setPointsColorOrUV(t,p,!1,!1,!1);break;case yn.Random:this._setPointsColorOrUV(t,p,!1);break;case yn.Stated:this._setPointsColorOrUV(t,p,!1,void 0,void 0,i,o)}return this.nbParticles+=e,this._groupCounter++,this._groupCounter-1},r.prototype.addVolumePoints=function(t,e,n,i,o){var a=n||yn.Random;(isNaN(a)||a<0||a>3)&&(a=yn.Random);var s=t.getVerticesData(Me.b.PositionKind),d=t.getIndices();this._groups.push(this._groupCounter);var p=new Ca(this._groupCounter,null);switch(p._groupDensity=this._calculateDensity(e,s,d),a===yn.Color?p._textureNb=i||0:i=i||new M.b(1,1,1,1),a){case yn.Color:this._colorFromTexture(t,p,!0);break;case yn.UV:this._setPointsColorOrUV(t,p,!0,!1,!1);break;case yn.Random:this._setPointsColorOrUV(t,p,!0);break;case yn.Stated:this._setPointsColorOrUV(t,p,!0,void 0,void 0,i,o)}return this.nbParticles+=e,this._groupCounter++,this._groupCounter-1},r.prototype.setParticles=function(t,e,n){if(t===void 0&&(t=0),e===void 0&&(e=this.nbParticles-1),n===void 0&&(n=!0),!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(t,e,n);var i=u.c.Matrix[0],o=this.mesh,a=this._colors32,s=this._positions32,d=this._uvs32,p=u.c.Vector3,y=p[5].copyFromFloats(1,0,0),P=p[6].copyFromFloats(0,1,0),O=p[7].copyFromFloats(0,0,1),U=p[8].setAll(Number.MAX_VALUE),F=p[9].setAll(-Number.MAX_VALUE);u.a.IdentityToRef(i);var z=0;if(this.mesh.isFacetDataEnabled&&(this._computeBoundingBox=!0),e=e>=this.nbParticles?this.nbParticles-1:e,this._computeBoundingBox&&(t!=0||e!=this.nbParticles-1)){var J=this.mesh._boundingInfo;J&&(U.copyFrom(J.minimum),F.copyFrom(J.maximum))}z=0;for(var ie=0,se=0,ce=0,ue=t;ue<=e;ue++){var fe=this.particles[ue];ie=3*(z=fe.idx),se=4*z,ce=2*z,this.updateParticle(fe);var ve=fe._rotationMatrix,Te=fe.position,Oe=fe._globalPosition;if(this._computeParticleRotation&&fe.getRotationMatrix(i),fe.parentId!==null){var Pe=this.particles[fe.parentId],Ee=Pe._rotationMatrix,Se=Pe._globalPosition,Le=Te.x*Ee[1]+Te.y*Ee[4]+Te.z*Ee[7],xe=Te.x*Ee[0]+Te.y*Ee[3]+Te.z*Ee[6],Ne=Te.x*Ee[2]+Te.y*Ee[5]+Te.z*Ee[8];if(Oe.x=Se.x+xe,Oe.y=Se.y+Le,Oe.z=Se.z+Ne,this._computeParticleRotation){var Ie=i.m;ve[0]=Ie[0]*Ee[0]+Ie[1]*Ee[3]+Ie[2]*Ee[6],ve[1]=Ie[0]*Ee[1]+Ie[1]*Ee[4]+Ie[2]*Ee[7],ve[2]=Ie[0]*Ee[2]+Ie[1]*Ee[5]+Ie[2]*Ee[8],ve[3]=Ie[4]*Ee[0]+Ie[5]*Ee[3]+Ie[6]*Ee[6],ve[4]=Ie[4]*Ee[1]+Ie[5]*Ee[4]+Ie[6]*Ee[7],ve[5]=Ie[4]*Ee[2]+Ie[5]*Ee[5]+Ie[6]*Ee[8],ve[6]=Ie[8]*Ee[0]+Ie[9]*Ee[3]+Ie[10]*Ee[6],ve[7]=Ie[8]*Ee[1]+Ie[9]*Ee[4]+Ie[10]*Ee[7],ve[8]=Ie[8]*Ee[2]+Ie[9]*Ee[5]+Ie[10]*Ee[8]}}else Oe.x=0,Oe.y=0,Oe.z=0,this._computeParticleRotation&&(Ie=i.m,ve[0]=Ie[0],ve[1]=Ie[1],ve[2]=Ie[2],ve[3]=Ie[4],ve[4]=Ie[5],ve[5]=Ie[6],ve[6]=Ie[8],ve[7]=Ie[9],ve[8]=Ie[10]);var Fe=p[11];fe.translateFromPivot?Fe.setAll(0):Fe.copyFrom(fe.pivot);var Ke=p[0];Ke.copyFrom(fe.position);var nt=Ke.x-fe.pivot.x,rt=Ke.y-fe.pivot.y,ut=Ke.z-fe.pivot.z,qe=nt*ve[0]+rt*ve[3]+ut*ve[6],at=nt*ve[1]+rt*ve[4]+ut*ve[7],ot=nt*ve[2]+rt*ve[5]+ut*ve[8];qe+=Fe.x,at+=Fe.y,ot+=Fe.z;var Je=s[ie]=Oe.x+y.x*qe+P.x*at+O.x*ot,dt=s[ie+1]=Oe.y+y.y*qe+P.y*at+O.y*ot,Ve=s[ie+2]=Oe.z+y.z*qe+P.z*at+O.z*ot;if(this._computeBoundingBox&&(U.minimizeInPlaceFromFloats(Je,dt,Ve),F.maximizeInPlaceFromFloats(Je,dt,Ve)),this._computeParticleColor&&fe.color){var $e=fe.color,yt=this._colors32;yt[se]=$e.r,yt[se+1]=$e.g,yt[se+2]=$e.b,yt[se+3]=$e.a}if(this._computeParticleTexture&&fe.uv){var Wt=fe.uv,Nt=this._uvs32;Nt[ce]=Wt.x,Nt[ce+1]=Wt.y}}return n&&(this._computeParticleColor&&o.updateVerticesData(Me.b.ColorKind,a,!1,!1),this._computeParticleTexture&&o.updateVerticesData(Me.b.UVKind,d,!1,!1),o.updateVerticesData(Me.b.PositionKind,s,!1,!1)),this._computeBoundingBox&&(o._boundingInfo?o._boundingInfo.reConstruct(U,F,o._worldMatrix):o._boundingInfo=new Fi.a(U,F,o._worldMatrix)),this.afterUpdateParticles(t,e,n),this},r.prototype.dispose=function(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null},r.prototype.refreshVisibleSize=function(){return this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo(),this},r.prototype.setVisibilityBox=function(t){var e=t/2;this.mesh._boundingInfo=new Fi.a(new u.e(-e,-e,-e),new u.e(e,e,e))},Object.defineProperty(r.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(t){this._alwaysVisible=t,this.mesh.alwaysSelectAsActiveMesh=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"computeParticleRotation",{set:function(t){this._computeParticleRotation=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(t){this._computeParticleColor=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(t){this._computeParticleTexture=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(t){this._computeBoundingBox=t},enumerable:!1,configurable:!0}),r.prototype.initParticles=function(){},r.prototype.recycleParticle=function(t){return t},r.prototype.updateParticle=function(t){return t},r.prototype.beforeUpdateParticles=function(t,e,n){},r.prototype.afterUpdateParticles=function(t,e,n){},r}();_e.a.prototype.getPhysicsEngine=function(){return this._physicsEngine},_e.a.prototype.enablePhysics=function(r,t){if(r===void 0&&(r=null),this._physicsEngine)return!0;var e=this._getComponent(st.a.NAME_PHYSICSENGINE);e||(e=new Ud(this),this._addComponent(e));try{return this._physicsEngine=new Mr(r,t),this._physicsTimeAccumulator=0,!0}catch(n){return l.a.Error(n.message),!1}},_e.a.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},_e.a.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0},_e.a.prototype.deleteCompoundImpostor=function(r){var t=r.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},_e.a.prototype._advancePhysicsEngineStep=function(r){if(this._physicsEngine){var t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=r;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(r/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}},Object.defineProperty(Dt.a.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(r){var t=this;this._physicsImpostor!==r&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=r,r&&(this._disposePhysicsObserver=this.onDisposeObservable.add(function(){t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),Dt.a.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Dt.a.prototype.applyImpulse=function(r,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(r,t),this):this},Dt.a.prototype.setPhysicsLinkWith=function(r,t,e,n){return this.physicsImpostor&&r.physicsImpostor?(this.physicsImpostor.createJoint(r.physicsImpostor,en.e.HingeJoint,{mainPivot:t,connectedPivot:e,nativeParams:n}),this):this};var xo,Fr,Ud=function(){function r(t){var e=this;this.name=st.a.NAME_PHYSICSENGINE,this.scene=t,this.scene.onBeforePhysicsObservable=new x.c,this.scene.onAfterPhysicsObservable=new x.c,this.scene.getDeterministicFrameTime=function(){return e.scene._physicsEngine?1e3*e.scene._physicsEngine.getTimeStep():1e3/60}}return r.prototype.register=function(){},r.prototype.rebuild=function(){},r.prototype.dispose=function(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()},r}(),hg=function(){function r(t){this._scene=t,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||l.a.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}return r.prototype.applyRadialExplosionImpulse=function(t,e,n,i){if(!this._physicsEngine)return l.a.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;var o=this._physicsEngine.getImpostors();if(o.length===0)return null;typeof e=="number"&&((e=new Br).radius=e,e.strength=n||e.strength,e.falloff=i||e.falloff);var a=new Vd(this._scene,e),s=Array();return o.forEach(function(d){var p=a.getImpostorHitData(d,t);p&&(d.applyImpulse(p.force,p.contactPoint),s.push({impostor:d,hitData:p}))}),a.triggerAffectedImpostorsCallback(s),a.dispose(!1),a},r.prototype.applyRadialExplosionForce=function(t,e,n,i){if(!this._physicsEngine)return l.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;var o=this._physicsEngine.getImpostors();if(o.length===0)return null;typeof e=="number"&&((e=new Br).radius=e,e.strength=n||e.strength,e.falloff=i||e.falloff);var a=new Vd(this._scene,e),s=Array();return o.forEach(function(d){var p=a.getImpostorHitData(d,t);p&&(d.applyForce(p.force,p.contactPoint),s.push({impostor:d,hitData:p}))}),a.triggerAffectedImpostorsCallback(s),a.dispose(!1),a},r.prototype.gravitationalField=function(t,e,n,i){if(!this._physicsEngine)return l.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getImpostors().length===0)return null;typeof e=="number"&&((e=new Br).radius=e,e.strength=n||e.strength,e.falloff=i||e.falloff);var o=new dg(this,this._scene,t,e);return o.dispose(!1),o},r.prototype.updraft=function(t,e,n,i,o){if(!this._physicsEngine)return l.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getImpostors().length===0)return null;typeof e=="number"&&((e=new Bc).radius=e,e.strength=n||e.strength,e.height=i||e.height,e.updraftMode=o||e.updraftMode);var a=new fg(this._scene,t,e);return a.dispose(!1),a},r.prototype.vortex=function(t,e,n,i){if(!this._physicsEngine)return l.a.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(this._physicsEngine.getImpostors().length===0)return null;typeof e=="number"&&((e=new Uc).radius=e,e.strength=n||e.strength,e.height=i||e.height);var o=new pg(this._scene,t,e);return o.dispose(!1),o},r}(),Vd=function(){function r(t,e){this._scene=t,this._options=e,this._dataFetched=!1,this._options=Object(c.a)(Object(c.a)({},new Br),this._options)}return r.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},r.prototype.getImpostorHitData=function(t,e){if(t.mass===0||!this._intersectsWithSphere(t,e,this._options.radius)||t.object.getClassName()!=="Mesh"&&t.object.getClassName()!=="InstancedMesh")return null;var n=t.getObjectCenter().subtract(e),i=new dn.a(e,n,this._options.radius).intersectsMesh(t.object).pickedPoint;if(!i)return null;var o=u.e.Distance(e,i);if(o>this._options.radius)return null;var a=this._options.falloff===xo.Constant?this._options.strength:this._options.strength*(1-o/this._options.radius);return{force:n.multiplyByFloats(a,a,a),contactPoint:i,distanceFromOrigin:o}},r.prototype.triggerAffectedImpostorsCallback=function(t){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(t)},r.prototype.dispose=function(t){var e=this;t===void 0&&(t=!0),t?this._sphere.dispose():setTimeout(function(){e._dataFetched||e._sphere.dispose()},0)},r.prototype._prepareSphere=function(){this._sphere||(this._sphere=Nn.a.CreateSphere("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)},r.prototype._intersectsWithSphere=function(t,e,n){var i=t.object;return this._prepareSphere(),this._sphere.position=e,this._sphere.scaling=new u.e(2*n,2*n,2*n),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(i,!0)},r}(),dg=function(){function r(t,e,n,i){this._physicsHelper=t,this._scene=e,this._origin=n,this._options=i,this._dataFetched=!1,this._options=Object(c.a)(Object(c.a)({},new Br),this._options),this._tickCallback=this._tick.bind(this),this._options.strength=-1*this._options.strength}return r.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},r.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},r.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},r.prototype.dispose=function(t){var e=this;t===void 0&&(t=!0),t?this._sphere.dispose():setTimeout(function(){e._dataFetched||e._sphere.dispose()},0)},r.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{var t=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);t&&(this._sphere=t.getData().sphere.clone("radialExplosionEventSphereClone"))}},r}(),fg=function(){function r(t,e,n){this._scene=t,this._origin=e,this._options=n,this._originTop=u.e.Zero(),this._originDirection=u.e.Zero(),this._cylinderPosition=u.e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object(c.a)(Object(c.a)({},new Bc),this._options),this._origin.addToRef(new u.e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new u.e(0,this._options.height,0),this._originTop),this._options.updraftMode===Fr.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),this._prepareCylinder()}return r.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},r.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},r.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},r.prototype.dispose=function(t){var e=this;t===void 0&&(t=!0),this._cylinder&&(t?this._cylinder.dispose():setTimeout(function(){e._dataFetched||e._cylinder.dispose()},0))},r.prototype.getImpostorHitData=function(t){if(t.mass===0||!this._intersectsWithCylinder(t))return null;var e=t.getObjectCenter();if(this._options.updraftMode===Fr.Perpendicular)var n=this._originDirection;else n=e.subtract(this._originTop);var i=u.e.Distance(this._origin,e),o=-1*this._options.strength;return{force:n.multiplyByFloats(o,o,o),contactPoint:e,distanceFromOrigin:i}},r.prototype._tick=function(){var t=this;this._physicsEngine.getImpostors().forEach(function(e){var n=t.getImpostorHitData(e);n&&e.applyForce(n.force,n.contactPoint)})},r.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=ui.a.CreateCylinder("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)},r.prototype._intersectsWithCylinder=function(t){var e=t.object;return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)},r}(),pg=function(){function r(t,e,n){this._scene=t,this._origin=e,this._options=n,this._originTop=u.e.Zero(),this._cylinderPosition=u.e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object(c.a)(Object(c.a)({},new Uc),this._options),this._origin.addToRef(new u.e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new u.e(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),this._prepareCylinder()}return r.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},r.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},r.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},r.prototype.dispose=function(t){var e=this;t===void 0&&(t=!0),t?this._cylinder.dispose():setTimeout(function(){e._dataFetched||e._cylinder.dispose()},0)},r.prototype.getImpostorHitData=function(t){if(t.mass===0||!this._intersectsWithCylinder(t)||t.object.getClassName()!=="Mesh"&&t.object.getClassName()!=="InstancedMesh")return null;var e=t.getObjectCenter(),n=new u.e(this._origin.x,e.y,this._origin.z),i=e.subtract(n),o=new dn.a(n,i,this._options.radius).intersectsMesh(t.object),a=o.pickedPoint;if(!a)return null;var s=o.distance/this._options.radius,d=a.normalize();if(s>this._options.centripetalForceThreshold&&(d=d.negate()),s>this._options.centripetalForceThreshold)var p=d.x*this._options.centripetalForceMultiplier,y=d.y*this._options.updraftForceMultiplier,P=d.z*this._options.centripetalForceMultiplier;else{var O=u.e.Cross(n,e).normalize();p=(O.x+d.x)*this._options.centrifugalForceMultiplier,y=this._originTop.y*this._options.updraftForceMultiplier,P=(O.z+d.z)*this._options.centrifugalForceMultiplier}var U=new u.e(p,y,P);return{force:U=U.multiplyByFloats(this._options.strength,this._options.strength,this._options.strength),contactPoint:e,distanceFromOrigin:s}},r.prototype._tick=function(){var t=this;this._physicsEngine.getImpostors().forEach(function(e){var n=t.getImpostorHitData(e);n&&e.applyForce(n.force,n.contactPoint)})},r.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=ui.a.CreateCylinder("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)},r.prototype._intersectsWithCylinder=function(t){var e=t.object;return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)},r}(),Br=function(){this.radius=5,this.strength=10,this.falloff=xo.Constant,this.sphere={segments:32,diameter:1}},Bc=function(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=Fr.Center},Uc=function(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02};(function(r){r[r.Constant=0]="Constant",r[r.Linear=1]="Linear"})(xo||(xo={})),function(r){r[r.Center=0]="Center",r[r.Perpendicular=1]="Perpendicular"}(Fr||(Fr={}));var _g=` -varying vec2 vUV; -uniform sampler2D textureSampler; -uniform float degree; -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); -}`;je.a.ShadersStore.blackAndWhitePixelShader=_g;var kd=function(r){function t(e,n,i,o,a,s){var d=r.call(this,e,"blackAndWhite",["degree"],null,n,i,o,a,s)||this;return d.degree=1,d.onApplyObservable.add(function(p){p.setFloat("degree",d.degree)}),d}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"BlackAndWhitePostProcess"},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"degree",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.BlackAndWhitePostProcess"]=kd;var Rt=function(){function r(t,e,n,i){this._name=e,this._singleInstance=i||!0,this._getPostProcesses=n,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(r.prototype,"isSupported",{get:function(){for(var t in this._postProcesses)if(this._postProcesses.hasOwnProperty(t)){for(var e=this._postProcesses[t],n=0;n - -varying vec2 vUV; -uniform sampler2D textureSampler; -uniform float threshold; -uniform float exposure; -void main(void) -{ -gl_FragColor=texture2D(textureSampler,vUV); -float luma=getLuminance(gl_FragColor.rgb*exposure); -gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb; -}`;je.a.ShadersStore.extractHighlightsPixelShader=mg;var Vc=function(r){function t(e,n,i,o,a,s,d,p){d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT),p===void 0&&(p=!1);var y=r.call(this,e,"extractHighlights",["threshold","exposure"],null,n,i,o,a,s,null,d,void 0,null,p)||this;return y.threshold=.9,y._exposure=1,y._inputPostProcess=null,y.onApplyObservable.add(function(P){y._inputPostProcess&&P.setTextureFromPostProcess("textureSampler",y._inputPostProcess),P.setFloat("threshold",Math.pow(y.threshold,Gt.b)),P.setFloat("exposure",y._exposure)}),y}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"ExtractHighlightsPostProcess"},Object(c.c)([Object(L.c)()],t.prototype,"threshold",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.ExtractHighlightsPostProcess"]=Vc;var gg=`uniform sampler2D textureSampler; -uniform sampler2D bloomBlur; -varying vec2 vUV; -uniform float bloomWeight; -void main(void) -{ -gl_FragColor=texture2D(textureSampler,vUV); -vec3 blurred=texture2D(bloomBlur,vUV).rgb; -gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); -} -`;je.a.ShadersStore.bloomMergePixelShader=gg;var kc=function(r){function t(e,n,i,o,a,s,d,p,y,P,O){P===void 0&&(P=h.a.TEXTURETYPE_UNSIGNED_INT),O===void 0&&(O=!1);var U=r.call(this,e,"bloomMerge",["bloomWeight"],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2","bloomBlur"],a,s,d,p,y,null,P,void 0,null,!0)||this;return U.weight=1,U.weight=o,U.onApplyObservable.add(function(F){F.setTextureFromPostProcess("textureSampler",n),F.setTextureFromPostProcessOutput("bloomBlur",i),F.setFloat("bloomWeight",U.weight)}),O||U.updateEffect(),U}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"BloomMergePostProcess"},Object(c.c)([Object(L.c)()],t.prototype,"weight",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.BloomMergePostProcess"]=kc;var Gc=function(r){function t(e,n,i,o,a,s){a===void 0&&(a=0),s===void 0&&(s=!1);var d=r.call(this,e.getEngine(),"bloom",function(){return d._effects},!0)||this;return d.bloomScale=n,d._effects=[],d._downscale=new Vc("highlights",1,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,a,s),d._blurX=new _n("horizontal blur",new u.d(1,0),10,n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,a,void 0,s),d._blurX.alwaysForcePOT=!0,d._blurX.autoClear=!1,d._blurY=new _n("vertical blur",new u.d(0,1),10,n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,a,void 0,s),d._blurY.alwaysForcePOT=!0,d._blurY.autoClear=!1,d.kernel=o,d._effects=[d._downscale,d._blurX,d._blurY],d._merge=new kc("bloomMerge",d._downscale,d._blurY,i,n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,a,s),d._merge.autoClear=!1,d._effects.push(d._merge),d}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"threshold",{get:function(){return this._downscale.threshold},set:function(e){this._downscale.threshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._merge.weight},set:function(e){this._merge.weight=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"kernel",{get:function(){return this._blurX.kernel/this.bloomScale},set:function(e){this._blurX.kernel=e*this.bloomScale,this._blurY.kernel=e*this.bloomScale},enumerable:!1,configurable:!0}),t.prototype.disposeEffects=function(e){for(var n=0;n0 -uniform sampler2D blurStep1; -#endif -#if BLUR_LEVEL>1 -uniform sampler2D blurStep2; -#endif -void main(void) -{ -float coc=texture2D(circleOfConfusionSampler,vUV).r; -#if BLUR_LEVEL == 0 -vec4 original=texture2D(textureSampler,vUV); -vec4 blurred0=texture2D(blurStep0,vUV); -gl_FragColor=mix(original,blurred0,coc); -#endif -#if BLUR_LEVEL == 1 -if(coc<0.5){ -vec4 original=texture2D(textureSampler,vUV); -vec4 blurred1=texture2D(blurStep1,vUV); -gl_FragColor=mix(original,blurred1,coc/0.5); -}else{ -vec4 blurred0=texture2D(blurStep0,vUV); -vec4 blurred1=texture2D(blurStep1,vUV); -gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5); -} -#endif -#if BLUR_LEVEL == 2 -if(coc<0.33){ -vec4 original=texture2D(textureSampler,vUV); -vec4 blurred2=texture2D(blurStep2,vUV); -gl_FragColor=mix(original,blurred2,coc/0.33); -}else if(coc<0.66){ -vec4 blurred1=texture2D(blurStep1,vUV); -vec4 blurred2=texture2D(blurStep2,vUV); -gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33); -}else{ -vec4 blurred0=texture2D(blurStep0,vUV); -vec4 blurred1=texture2D(blurStep1,vUV); -gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34); -} -#endif -} -`;je.a.ShadersStore.depthOfFieldMergePixelShader=Eg;var ar,Sg=function(){},jd=function(r){function t(e,n,i,o,a,s,d,p,y,P,O){P===void 0&&(P=h.a.TEXTURETYPE_UNSIGNED_INT),O===void 0&&(O=!1);var U=r.call(this,e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],a,s,d,p,y,null,P,void 0,null,!0)||this;return U.blurSteps=o,U.onApplyObservable.add(function(F){F.setTextureFromPostProcess("textureSampler",n),F.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),o.forEach(function(z,J){F.setTextureFromPostProcessOutput("blurStep"+(o.length-J-1),z)})}),O||U.updateEffect(),U}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"DepthOfFieldMergePostProcess"},t.prototype.updateEffect=function(e,n,i,o,a,s){e===void 0&&(e=null),n===void 0&&(n=null),i===void 0&&(i=null),e||(e="",e+="#define BLUR_LEVEL "+(this.blurSteps.length-1)+` -`),r.prototype.updateEffect.call(this,e,n,i,o,a,s)},t}(_t);(function(r){r[r.Low=0]="Low",r[r.Medium=1]="Medium",r[r.High=2]="High"})(ar||(ar={}));var Hc=function(r){function t(e,n,i,o,a){i===void 0&&(i=ar.Low),o===void 0&&(o=0),a===void 0&&(a=!1);var s=r.call(this,e.getEngine(),"depth of field",function(){return s._effects},!0)||this;s._effects=[],s._circleOfConfusion=new jc("circleOfConfusion",n,1,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,a),s._depthOfFieldBlurY=[],s._depthOfFieldBlurX=[];var d=1,p=15;switch(i){case ar.High:d=3,p=51;break;case ar.Medium:d=2,p=31;break;default:p=15,d=1}for(var y=p/Math.pow(2,d-1),P=1,O=0;O=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(texture2D(textureSampler,posN,0.0)); -float subpixE=subpixC*subpixC; -float lumaEndP=FxaaLuma(texture2D(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(texture2D(textureSampler,posN.xy,0.0)); -if (!doneP) lumaEndP=FxaaLuma(texture2D(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-1?`#define MALI 1 -`:null},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable)},e,i,o)},t}(_t);R.a.RegisteredTypes["BABYLON.FxaaPostProcess"]=Ro;var Rg=`#include - -uniform sampler2D textureSampler; - -uniform float intensity; -uniform float animatedSeed; - -varying vec2 vUV; -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); -}`;je.a.ShadersStore.grainPixelShader=Rg;var Wc=function(r){function t(e,n,i,o,a,s,d,p){d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT),p===void 0&&(p=!1);var y=r.call(this,e,"grain",["intensity","animatedSeed"],[],n,i,o,a,s,null,d,void 0,null,p)||this;return y.intensity=30,y.animated=!1,y.onApplyObservable.add(function(P){P.setFloat("intensity",y.intensity),P.setFloat("animatedSeed",y.animated?Math.random()+1:1)}),y}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"GrainPostProcess"},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"intensity",void 0),Object(c.c)([Object(L.c)()],t.prototype,"animated",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.GrainPostProcess"]=Wc;var Og=` -varying vec2 vUV; -uniform sampler2D textureSampler; -const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); -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); -}`;je.a.ShadersStore.highlightsPixelShader=Og;var Mg=function(r){function t(e,n,i,o,a,s,d){return d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT),r.call(this,e,"highlights",null,null,n,i,o,a,s,null,d)||this}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"HighlightsPostProcess"},t}(_t);je.a.IncludesShadersStore.mrtFragmentDeclaration=`#if __VERSION__>=200 -layout(location=0) out vec4 glFragData[{X}]; -#endif -`;var Ig=`#extension GL_EXT_draw_buffers : require -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -precision highp float; -precision highp int; -#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 -#ifdef REFLECTIVITY -varying vec2 vReflectivityUV; -uniform sampler2D reflectivitySampler; -#endif -#ifdef ALPHATEST -uniform sampler2D diffuseSampler; -#endif -#include[RENDER_TARGET_COUNT] -#include -#include -void main() { -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -vec3 normalOutput; -#ifdef BUMP -vec3 normalW=normalize(vNormalW); -#include -normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); -#else -normalOutput=normalize(vNormalV); -#endif -#ifdef PREPASS -#ifdef PREPASS_DEPTHNORMAL -gl_FragData[DEPTHNORMAL_INDEX]=vec4(vViewPos.z/vViewPos.w,normalOutput); -#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 -#ifdef HAS_SPECULAR - -vec4 reflectivity=texture2D(reflectivitySampler,vReflectivityUV); -#elif HAS_REFLECTIVITY - -vec4 reflectivity=vec4(texture2D(reflectivitySampler,vReflectivityUV).rgb,1.0); -#else -vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); -#endif -gl_FragData[REFLECTIVITY_INDEX]=reflectivity; -#endif -}`;je.a.ShadersStore.geometryPixelShader=Ig;var Dg=`precision highp float; -precision highp int; -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -attribute vec3 position; -attribute vec3 normal; -#ifdef NEED_UV -varying vec2 vUV; -#ifdef ALPHATEST -uniform mat4 diffuseMatrix; -#endif -#ifdef BUMP -uniform mat4 bumpMatrix; -varying vec2 vBumpUV; -#endif -#ifdef REFLECTIVITY -uniform mat4 reflectivityMatrix; -varying vec2 vReflectivityUV; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif - -uniform mat4 viewProjection; -uniform mat4 view; -#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 previousWorld; -uniform mat4 previousViewProjection; -#ifdef BONES_VELOCITY_ENABLED -#if NUM_BONE_INFLUENCERS>0 -uniform mat4 mPreviousBones[BonesPerMesh]; -#endif -#endif -varying vec4 vCurrentPosition; -varying vec4 vPreviousPosition; -#endif -void main(void) -{ -vec3 positionUpdated=position; -vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -#include -#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) - -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0); -#endif -#include -vec4 pos=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*pos; -#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*previousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0); -#endif -#endif -#if defined(POSITION) || defined(BUMP) -vPositionW=pos.xyz/pos.w; -#endif -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#ifdef NEED_UV -#ifdef UV1 -#ifdef ALPHATEST -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#else -vUV=uv; -#endif -#ifdef BUMP -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef REFLECTIVITY -vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#endif -#ifdef UV2 -#ifdef ALPHATEST -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#else -vUV=uv2; -#endif -#ifdef BUMP -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef REFLECTIVITY -vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#endif -#include -} -`;je.a.ShadersStore.geometryVertexShader=Dg;var ai=function(){function r(t,e){e===void 0&&(e=1),this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthNormalIndex=-1,this._linkedWithPrePass=!1,this._scene=t,this._ratio=e,r._SceneComponentInitialization(this._scene),this._createRenderTargets()}return r.prototype._linkPrePassRenderer=function(t){this._linkedWithPrePass=!0,this._prePassRenderer=t,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(function(e){}))},r.prototype._unlinkPrePassRenderer=function(){this._linkedWithPrePass=!1,this._createRenderTargets()},r.prototype._resetLayout=function(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachments=[]},r.prototype._forceTextureType=function(t,e){t===r.POSITION_TEXTURE_TYPE?(this._positionIndex=e,this._enablePosition=!0):t===r.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=e,this._enableVelocity=!0):t===r.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=e,this._enableReflectivity=!0):t===r.DEPTHNORMAL_TEXTURE_TYPE&&(this._depthNormalIndex=e)},r.prototype._setAttachments=function(t){this._attachments=t},r.prototype._linkInternalTexture=function(t){this._multiRenderTarget._texture=t},Object.defineProperty(r.prototype,"renderList",{get:function(){return this._multiRenderTarget.renderList},set:function(t){this._multiRenderTarget.renderList=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isSupported",{get:function(){return this._multiRenderTarget.isSupported},enumerable:!1,configurable:!0}),r.prototype.getTextureIndex=function(t){switch(t){case r.POSITION_TEXTURE_TYPE:return this._positionIndex;case r.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case r.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;default:return-1}},Object.defineProperty(r.prototype,"enablePosition",{get:function(){return this._enablePosition},set:function(t){this._enablePosition=t,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"enableVelocity",{get:function(){return this._enableVelocity},set:function(t){this._enableVelocity=t,t||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"enableReflectivity",{get:function(){return this._enableReflectivity},set:function(t){this._enableReflectivity=t,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"ratio",{get:function(){return this._ratio},enumerable:!1,configurable:!0}),r.prototype.isReady=function(t,e){var n=t.getMaterial();if(n&&n.disableDepthWrite)return!1;var i=[],o=[Me.b.PositionKind,Me.b.NormalKind],a=t.getMesh();if(n){var s=!1;n.needAlphaTesting()&&(i.push("#define ALPHATEST"),s=!0),n.bumpTexture&&Ft.a.BumpTextureEnabled&&(i.push("#define BUMP"),i.push("#define BUMPDIRECTUV 0"),s=!0),this._enableReflectivity&&(n instanceof Ft.a&&n.specularTexture?(i.push("#define HAS_SPECULAR"),s=!0):n instanceof lo&&n.reflectivityTexture&&(i.push("#define HAS_REFLECTIVITY"),s=!0)),s&&(i.push("#define NEED_UV"),a.isVerticesDataPresent(Me.b.UVKind)&&(o.push(Me.b.UVKind),i.push("#define UV1")),a.isVerticesDataPresent(Me.b.UV2Kind)&&(o.push(Me.b.UV2Kind),i.push("#define UV2")))}this._linkedWithPrePass&&(i.push("#define PREPASS"),this._depthNormalIndex!==-1&&(i.push("#define DEPTHNORMAL_INDEX "+this._depthNormalIndex),i.push("#define PREPASS_DEPTHNORMAL"))),this._enablePosition&&(i.push("#define POSITION"),i.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(i.push("#define VELOCITY"),i.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&i.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(i.push("#define REFLECTIVITY"),i.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),a.useBones&&a.computeBonesUsingShaders?(o.push(Me.b.MatricesIndicesKind),o.push(Me.b.MatricesWeightsKind),a.numBoneInfluencers>4&&(o.push(Me.b.MatricesIndicesExtraKind),o.push(Me.b.MatricesWeightsExtraKind)),i.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),i.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):i.push("#define NUM_BONE_INFLUENCERS 0");var d=a.morphTargetManager,p=0;d&&d.numInfluencers>0&&(p=d.numInfluencers,i.push("#define MORPHTARGETS"),i.push("#define NUM_MORPH_INFLUENCERS "+p),tt.a.PrepareAttributesForMorphTargetsInfluencers(o,a,p)),e&&(i.push("#define INSTANCES"),tt.a.PushAttributesForInstances(o),t.getRenderingMesh().hasThinInstances&&i.push("#define THIN_INSTANCES")),this._linkedWithPrePass?i.push("#define RENDER_TARGET_COUNT "+this._attachments.length):i.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length);var y=i.join(` -`);return this._cachedDefines!==y&&(this._cachedDefines=y,this._effect=this._scene.getEngine().createEffect("geometry",o,["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","morphTargetInfluences","bumpMatrix","reflectivityMatrix","vTangentSpaceParams","vBumpInfos"],["diffuseSampler","bumpSampler","reflectivitySampler"],y,void 0,void 0,void 0,{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:p})),this._effect.isReady()},r.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(r.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(t){this._multiRenderTarget.samples=t},enumerable:!1,configurable:!0}),r.prototype.dispose=function(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()},r.prototype._assignRenderTargetIndices=function(){var t=2;return this._enablePosition&&(this._positionIndex=t,t++),this._enableVelocity&&(this._velocityIndex=t,t++),this._enableReflectivity&&(this._reflectivityIndex=t,t++),t},r.prototype._createRenderTargets=function(){var t=this,e=this._scene.getEngine(),n=this._assignRenderTargetIndices();if(this._multiRenderTarget=new tc("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},n,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:h.a.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=we.a.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=we.a.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add(function(o){o.clear(new M.b(0,0,0,1),!0,!0,!0)}),this._resizeObserver=e.onResizeObservable.add(function(){t._multiRenderTarget&&t._multiRenderTarget.resize({width:e.getRenderWidth()*t._ratio,height:e.getRenderHeight()*t._ratio})});var i=function(o){var a=o.getRenderingMesh(),s=o.getEffectiveMesh(),d=t._scene,p=d.getEngine(),y=o.getMaterial();if(y){if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,t._enableVelocity&&!t._previousTransformationMatrices[s.uniqueId]&&(t._previousTransformationMatrices[s.uniqueId]={world:u.a.Identity(),viewProjection:d.getTransformMatrix()},a.skeleton)){var P=a.skeleton.getTransformMatrices(a);t._previousBonesTransformationMatrices[a.uniqueId]=t._copyBonesTransformationMatrices(P,new Float32Array(P.length))}var O=a._getInstancesRenderList(o._id,!!o.getReplacementMesh());if(!O.mustReturn){var U=p.getCaps().instancedArrays&&(O.visibleInstances[o._id]!==null||a.hasThinInstances),F=s.getWorldMatrix();if(t.isReady(o,U)){if(p.enableEffect(t._effect),a._bind(o,t._effect,y.fillMode),t._effect.setMatrix("viewProjection",d.getTransformMatrix()),t._effect.setMatrix("view",d.getViewMatrix()),y){var z,J=s._instanceDataStorage;if(J.isFrozen||!y.backFaceCulling&&y.overrideMaterialSideOrientation===null)z=J.sideOrientation;else{var ie=s._getWorldMatrixDeterminant();(z=y.overrideMaterialSideOrientation)==null&&(z=y.sideOrientation),ie<0&&(z=z===Ht.a.ClockWiseSideOrientation?Ht.a.CounterClockWiseSideOrientation:Ht.a.ClockWiseSideOrientation)}if(y._preBind(t._effect,z),y.needAlphaTesting()){var se=y.getAlphaTestTexture();se&&(t._effect.setTexture("diffuseSampler",se),t._effect.setMatrix("diffuseMatrix",se.getTextureMatrix()))}y.bumpTexture&&d.getEngine().getCaps().standardDerivatives&&Ft.a.BumpTextureEnabled&&(t._effect.setFloat3("vBumpInfos",y.bumpTexture.coordinatesIndex,1/y.bumpTexture.level,y.parallaxScaleBias),t._effect.setMatrix("bumpMatrix",y.bumpTexture.getTextureMatrix()),t._effect.setTexture("bumpSampler",y.bumpTexture),t._effect.setFloat2("vTangentSpaceParams",y.invertNormalMapX?-1:1,y.invertNormalMapY?-1:1)),t._enableReflectivity&&(y instanceof Ft.a&&y.specularTexture?(t._effect.setMatrix("reflectivityMatrix",y.specularTexture.getTextureMatrix()),t._effect.setTexture("reflectivitySampler",y.specularTexture)):y instanceof lo&&y.reflectivityTexture&&(t._effect.setMatrix("reflectivityMatrix",y.reflectivityTexture.getTextureMatrix()),t._effect.setTexture("reflectivitySampler",y.reflectivityTexture)))}a.useBones&&a.computeBonesUsingShaders&&a.skeleton&&(t._effect.setMatrices("mBones",a.skeleton.getTransformMatrices(a)),t._enableVelocity&&t._effect.setMatrices("mPreviousBones",t._previousBonesTransformationMatrices[a.uniqueId])),tt.a.BindMorphTargetParameters(a,t._effect),t._enableVelocity&&(t._effect.setMatrix("previousWorld",t._previousTransformationMatrices[s.uniqueId].world),t._effect.setMatrix("previousViewProjection",t._previousTransformationMatrices[s.uniqueId].viewProjection)),a._processRendering(s,o,t._effect,y.fillMode,O,U,function(ce,ue){return t._effect.setMatrix("world",ue)})}t._enableVelocity&&(t._previousTransformationMatrices[s.uniqueId].world=F.clone(),t._previousTransformationMatrices[s.uniqueId].viewProjection=t._scene.getTransformMatrix().clone(),a.skeleton&&t._copyBonesTransformationMatrices(a.skeleton.getTransformMatrices(a),t._previousBonesTransformationMatrices[s.uniqueId]))}}};this._multiRenderTarget.customRenderFunction=function(o,a,s,d){var p;if(t._linkedWithPrePass){if(!t._prePassRenderer.enabled)return;t._scene.getEngine().bindAttachments(t._attachments)}if(d.length){for(e.setColorWrite(!1),p=0;p=samplesCount) -break; -vec2 offset=vUV+velocity*(hlim+float(i)); -result+=texture2D(textureSampler,offset); -} -gl_FragColor=result/float(samplesCount); -gl_FragColor.a=1.0; -#else -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,SAMPLES)); -vec4 result=texture2D(textureSampler,vUV); -for (int i=1; i=nSamples) -break; -vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); -result+=texture2D(textureSampler,offset1); -} -gl_FragColor=result/float(nSamples); -#endif -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`;je.a.ShadersStore.motionBlurPixelShader=Ng;var Xc=function(r){function t(e,n,i,o,a,s,d,p,y,P){p===void 0&&(p=h.a.TEXTURETYPE_UNSIGNED_INT),y===void 0&&(y=!1),P===void 0&&(P=!0);var O=r.call(this,e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection"],["velocitySampler"],i,o,a,s,d,`#define GEOMETRY_SUPPORTED -#define SAMPLES 64.0 -#define OBJECT_BASED`,p,void 0,null,y)||this;return O.motionStrength=1,O._motionBlurSamples=32,O._isObjectBased=!0,O._forceGeometryBuffer=!1,O._geometryBufferRenderer=null,O._prePassRenderer=null,O._invViewProjection=null,O._previousViewProjection=null,O._forceGeometryBuffer=P,O._forceGeometryBuffer?(O._geometryBufferRenderer=n.enableGeometryBufferRenderer(),O._geometryBufferRenderer&&(O._geometryBufferRenderer.enableVelocity=!0)):(O._prePassRenderer=n.enablePrePassRenderer(),O._prePassRenderer&&(O._prePassRenderer.markAsDirty(),O._prePassEffectConfiguration=new Lg)),O._applyMode(),O}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"motionBlurSamples",{get:function(){return this._motionBlurSamples},set:function(e){this._motionBlurSamples=e,this._updateEffect()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isObjectBased",{get:function(){return this._isObjectBased},set:function(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"MotionBlurPostProcess"},t.prototype.excludeSkinnedMesh=function(e){if(e.skeleton){var n=void 0;if(this._geometryBufferRenderer)n=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;n=this._prePassRenderer.excludedSkinnedMesh}n.push(e)}},t.prototype.removeExcludedSkinnedMesh=function(e){if(e.skeleton){var n=void 0;if(this._geometryBufferRenderer)n=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;n=this._prePassRenderer.excludedSkinnedMesh}var i=n.indexOf(e);i!==-1&&n.splice(i,1)}},t.prototype.dispose=function(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),r.prototype.dispose.call(this,e)},t.prototype._applyMode=function(){var e=this;if(!this._geometryBufferRenderer&&!this._prePassRenderer)return l.a.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]=h.a.PREPASS_VELOCITY_TEXTURE_TYPE),this.onApply=function(n){return e._onApplyObjectBased(n)}):(this._invViewProjection=u.a.Identity(),this._previousViewProjection=u.a.Identity(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=h.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE),this.onApply=function(n){return e._onApplyScreenBased(n)})},t.prototype._onApplyObjectBased=function(e){if(e.setVector2("screenSize",new u.d(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){var n=this._geometryBufferRenderer.getTextureIndex(ai.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[n])}else this._prePassRenderer&&(n=this._prePassRenderer.getIndex(h.a.PREPASS_VELOCITY_TEXTURE_TYPE),e.setTexture("velocitySampler",this._prePassRenderer.prePassRT.textures[n]))},t.prototype._onApplyScreenBased=function(e){var n=this._scene.getProjectionMatrix().multiply(this._scene.getViewMatrix());if(n.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection=n,e.setVector2("screenSize",new u.d(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){var i=this._geometryBufferRenderer.getTextureIndex(ai.DEPTHNORMAL_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[i])}else this._prePassRenderer&&(i=this._prePassRenderer.getIndex(h.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE),e.setTexture("depthSampler",this._prePassRenderer.prePassRT.textures[i]))},t.prototype._updateEffect=function(){if(this._geometryBufferRenderer||this._prePassRenderer){var e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join(` -`))}},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,i,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"motionStrength",void 0),Object(c.c)([Object(L.c)()],t.prototype,"motionBlurSamples",null),Object(c.c)([Object(L.c)()],t.prototype,"isObjectBased",null),t}(_t);R.a.RegisteredTypes["BABYLON.MotionBlurPostProcess"]=Xc;var wg=` -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); -}`;je.a.ShadersStore.refractionPixelShader=wg;var Yd=function(r){function t(e,n,i,o,a,s,d,p,y,P){var O=r.call(this,e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],s,d,p,y,P)||this;return O._ownRefractionTexture=!0,O.color=i,O.depth=o,O.colorLevel=a,O.refractionTextureUrl=n,O.onActivateObservable.add(function(U){O._refTexture=O._refTexture||new we.a(n,U.getScene())}),O.onApplyObservable.add(function(U){U.setColor3("baseColor",O.color),U.setFloat("depth",O.depth),U.setFloat("colorLevel",O.colorLevel),U.setTexture("refractionSampler",O._refTexture)}),O}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"RefractionPostProcess"},t.prototype.dispose=function(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),r.prototype.dispose.call(this,e)},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.reusable)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"color",void 0),Object(c.c)([Object(L.c)()],t.prototype,"depth",void 0),Object(c.c)([Object(L.c)()],t.prototype,"colorLevel",void 0),Object(c.c)([Object(L.c)()],t.prototype,"refractionTextureUrl",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.RefractionPostProcess"]=Yd;var Fg=` -varying vec2 vUV; -uniform sampler2D textureSampler; -uniform vec2 screenSize; -uniform vec2 sharpnessAmounts; -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.); -}`;je.a.ShadersStore.sharpenPixelShader=Fg;var Yc=function(r){function t(e,n,i,o,a,s,d,p){d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT),p===void 0&&(p=!1);var y=r.call(this,e,"sharpen",["sharpnessAmounts","screenSize"],null,n,i,o,a,s,null,d,void 0,null,p)||this;return y.colorAmount=1,y.edgeAmount=.3,y.onApply=function(P){P.setFloat2("screenSize",y.width,y.height),P.setFloat2("sharpnessAmounts",y.edgeAmount,y.colorAmount)},y}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"SharpenPostProcess"},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"colorAmount",void 0),Object(c.c)([Object(L.c)()],t.prototype,"edgeAmount",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.SharpenPostProcess"]=Yc;var Ur=function(){function r(t,e){this.engine=t,this._name=e,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}return Object.defineProperty(r.prototype,"name",{get:function(){return this._name},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"cameras",{get:function(){return this._cameras},enumerable:!1,configurable:!0}),r.prototype.getClassName=function(){return"PostProcessRenderPipeline"},Object.defineProperty(r.prototype,"isSupported",{get:function(){for(var t in this._renderEffects)if(this._renderEffects.hasOwnProperty(t)&&!this._renderEffects[t].isSupported)return!1;return!0},enumerable:!1,configurable:!0}),r.prototype.addEffect=function(t){this._renderEffects[t._name]=t},r.prototype._rebuild=function(){},r.prototype._enableEffect=function(t,e){var n=this._renderEffects[t];n&&n._enable(Ye.b.MakeArray(e||this._cameras))},r.prototype._disableEffect=function(t,e){var n=this._renderEffects[t];n&&n._disable(Ye.b.MakeArray(e||this._cameras))},r.prototype._attachCameras=function(t,e){var n=Ye.b.MakeArray(t||this._cameras);if(n){var i,o=[];for(i=0;i0){var n=this._renderEffects[e[0]].getPostProcesses();n&&(n[0].samples=t)}return!0},r.prototype.setPrePassRenderer=function(t){return!1},r.prototype.dispose=function(){},Object(c.c)([Object(L.c)()],r.prototype,"_name",void 0),r}(),Kd=function(){function r(){this._renderPipelines={}}return Object.defineProperty(r.prototype,"supportedPipelines",{get:function(){var t=[];for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var n=this._renderPipelines[e];n.isSupported&&t.push(n)}return t},enumerable:!1,configurable:!0}),r.prototype.addPipeline=function(t){this._renderPipelines[t._name]=t},r.prototype.attachCamerasToRenderPipeline=function(t,e,n){n===void 0&&(n=!1);var i=this._renderPipelines[t];i&&i._attachCameras(e,n)},r.prototype.detachCamerasFromRenderPipeline=function(t,e){var n=this._renderPipelines[t];n&&n._detachCameras(e)},r.prototype.enableEffectInPipeline=function(t,e,n){var i=this._renderPipelines[t];i&&i._enableEffect(e,n)},r.prototype.disableEffectInPipeline=function(t,e,n){var i=this._renderPipelines[t];i&&i._disableEffect(e,n)},r.prototype.update=function(){for(var t in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(t)){var e=this._renderPipelines[t];e.isSupported?e._update():(e.dispose(),delete this._renderPipelines[t])}},r.prototype._rebuild=function(){for(var t in this._renderPipelines)this._renderPipelines.hasOwnProperty(t)&&this._renderPipelines[t]._rebuild()},r.prototype.dispose=function(){for(var t in this._renderPipelines)this._renderPipelines.hasOwnProperty(t)&&this._renderPipelines[t].dispose()},r}();Object.defineProperty(_e.a.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){var r=this._getComponent(st.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER);r||(r=new Qd(this),this._addComponent(r)),this._postProcessRenderPipelineManager=new Kd}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});var Qd=function(){function r(t){this.name=st.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=t}return r.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(st.a.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)},r.prototype.rebuild=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()},r.prototype.dispose=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()},r.prototype._gatherRenderTargets=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()},r}(),qd=function(r){function t(e,n,i,o,a){e===void 0&&(e=""),n===void 0&&(n=!0),i===void 0&&(i=te.a.LastCreatedScene),a===void 0&&(a=!0);var s=r.call(this,i.getEngine(),e)||this;s._camerasToBeAttached=[],s.SharpenPostProcessId="SharpenPostProcessEffect",s.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",s.FxaaPostProcessId="FxaaPostProcessEffect",s.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",s.GrainPostProcessId="GrainPostProcessEffect",s._glowLayer=null,s.animations=[],s._imageProcessingConfigurationObserver=null,s._sharpenEnabled=!1,s._bloomEnabled=!1,s._depthOfFieldEnabled=!1,s._depthOfFieldBlurLevel=ar.Low,s._fxaaEnabled=!1,s._imageProcessingEnabled=!0,s._bloomScale=.5,s._chromaticAberrationEnabled=!1,s._grainEnabled=!1,s._buildAllowed=!0,s.onBuildObservable=new x.c,s._resizeObserver=null,s._hardwareScaleLevel=1,s._bloomKernel=64,s._bloomWeight=.15,s._bloomThreshold=.9,s._samples=1,s._hasCleared=!1,s._prevPostProcess=null,s._prevPrevPostProcess=null,s._depthOfFieldSceneObserver=null,s._cameras=o||i.cameras,s._cameras=s._cameras.slice(),s._camerasToBeAttached=s._cameras.slice(),s._buildAllowed=a,s._scene=i;var d=s._scene.getEngine().getCaps();s._hdr=n&&(d.textureHalfFloatRender||d.textureFloatRender),s._hdr?d.textureHalfFloatRender?s._defaultPipelineTextureType=h.a.TEXTURETYPE_HALF_FLOAT:d.textureFloatRender&&(s._defaultPipelineTextureType=h.a.TEXTURETYPE_FLOAT):s._defaultPipelineTextureType=h.a.TEXTURETYPE_UNSIGNED_INT,i.postProcessRenderPipelineManager.addPipeline(s);var p=s._scene.getEngine();return s.sharpen=new Yc("sharpen",1,null,we.a.BILINEAR_SAMPLINGMODE,p,!1,s._defaultPipelineTextureType,!0),s._sharpenEffect=new Rt(p,s.SharpenPostProcessId,function(){return s.sharpen},!0),s.depthOfField=new Hc(s._scene,null,s._depthOfFieldBlurLevel,s._defaultPipelineTextureType,!0),s.bloom=new Gc(s._scene,s._bloomScale,s._bloomWeight,s.bloomKernel,s._defaultPipelineTextureType,!0),s.chromaticAberration=new zc("ChromaticAberration",p.getRenderWidth(),p.getRenderHeight(),1,null,we.a.BILINEAR_SAMPLINGMODE,p,!1,s._defaultPipelineTextureType,!0),s._chromaticAberrationEffect=new Rt(p,s.ChromaticAberrationPostProcessId,function(){return s.chromaticAberration},!0),s.grain=new Wc("Grain",1,null,we.a.BILINEAR_SAMPLINGMODE,p,!1,s._defaultPipelineTextureType,!0),s._grainEffect=new Rt(p,s.GrainPostProcessId,function(){return s.grain},!0),s._resizeObserver=p.onResizeObservable.add(function(){s._hardwareScaleLevel=p.getHardwareScalingLevel(),s.bloomKernel=s.bloomKernel}),s._imageProcessingConfigurationObserver=s._scene.imageProcessingConfiguration.onUpdateParameters.add(function(){s.bloom._downscale._exposure=s._scene.imageProcessingConfiguration.exposure,s.imageProcessingEnabled!==s._scene.imageProcessingConfiguration.isEnabled&&(s._imageProcessingEnabled=s._scene.imageProcessingConfiguration.isEnabled,s._buildPipeline())}),s._buildPipeline(),s}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sharpenEnabled",{get:function(){return this._sharpenEnabled},set:function(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomKernel",{get:function(){return this._bloomKernel},set:function(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomWeight",{get:function(){return this._bloomWeight},set:function(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomThreshold",{get:function(){return this._bloomThreshold},set:function(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomScale",{get:function(){return this._bloomScale},set:function(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),t.prototype._rebuildBloom=function(){var e=this.bloom;this.bloom=new Gc(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(var n=0;n1){for(var i=0,o=this._cameras;i-1&&(e.depthOfField.depthTexture=d.enableDepthRenderer(d.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);var s=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=s.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 Ho("imageProcessing",1,null,we.a.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType),this._hdr?(this.addEffect(new Rt(n,this.ImageProcessingPostProcessId,function(){return e.imageProcessing},!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this.cameras&&this.cameras.length!==0||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new Ro("fxaa",1,null,we.a.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType),this.addEffect(new Rt(n,this.FxaaPostProcessId,function(){return e.fxaa},!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&l.a.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}},t.prototype._disposePostProcesses=function(e){e===void 0&&(e=!1);for(var n=0;n1.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; -} -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; - -}`;je.a.ShadersStore.lensHighlightsPixelShader=Bg;var Ug=` - - - - -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,const in vec2 offset,const 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); -if (size == 0.0) { return col; } - - -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; -} -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; -} -} -`;je.a.ShadersStore.depthOfFieldPixelShader=Ug;var Vg=function(r){function t(e,n,i,o,a){o===void 0&&(o=1);var s=r.call(this,i.getEngine(),e)||this;return s.LensChromaticAberrationEffect="LensChromaticAberrationEffect",s.HighlightsEnhancingEffect="HighlightsEnhancingEffect",s.LensDepthOfFieldEffect="LensDepthOfFieldEffect",s._pentagonBokehIsEnabled=!1,s._scene=i,s._depthTexture=i.enableDepthRenderer().getDepthMap(),n.grain_texture?s._grainTexture=n.grain_texture:s._createGrainTexture(),s._edgeBlur=n.edge_blur?n.edge_blur:0,s._grainAmount=n.grain_amount?n.grain_amount:0,s._chromaticAberration=n.chromatic_aberration?n.chromatic_aberration:0,s._distortion=n.distortion?n.distortion:0,s._highlightsGain=n.dof_gain!==void 0?n.dof_gain:-1,s._highlightsThreshold=n.dof_threshold?n.dof_threshold:1,s._dofDistance=n.dof_focus_distance!==void 0?n.dof_focus_distance:-1,s._dofAperture=n.dof_aperture?n.dof_aperture:1,s._dofDarken=n.dof_darken?n.dof_darken:0,s._dofPentagon=n.dof_pentagon===void 0||n.dof_pentagon,s._blurNoise=n.blur_noise===void 0||n.blur_noise,s._createChromaticAberrationPostProcess(o),s._createHighlightsPostProcess(o),s._createDepthOfFieldPostProcess(o/4),s.addEffect(new Rt(i.getEngine(),s.LensChromaticAberrationEffect,function(){return s._chromaticAberrationPostProcess},!0)),s.addEffect(new Rt(i.getEngine(),s.HighlightsEnhancingEffect,function(){return s._highlightsPostProcess},!0)),s.addEffect(new Rt(i.getEngine(),s.LensDepthOfFieldEffect,function(){return s._depthOfFieldPostProcess},!0)),s._highlightsGain===-1&&s._disableEffect(s.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(s),a&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,a),s}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"LensRenderingPipeline"},Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edgeBlur",{get:function(){return this._edgeBlur},set:function(e){this.setEdgeBlur(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"grainAmount",{get:function(){return this._grainAmount},set:function(e){this.setGrainAmount(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"chromaticAberration",{get:function(){return this._chromaticAberration},set:function(e){this.setChromaticAberration(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dofAperture",{get:function(){return this._dofAperture},set:function(e){this.setAperture(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edgeDistortion",{get:function(){return this._distortion},set:function(e){this.setEdgeDistortion(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dofDistortion",{get:function(){return this._dofDistance},set:function(e){this.setFocusDistance(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"darkenOutOfFocus",{get:function(){return this._dofDarken},set:function(e){this.setDarkenOutOfFocus(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurNoise",{get:function(){return this._blurNoise},set:function(e){this._blurNoise=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pentagonBokeh",{get:function(){return this._pentagonBokehIsEnabled},set:function(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"highlightsGain",{get:function(){return this._highlightsGain},set:function(e){this.setHighlightsGain(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"highlightsThreshold",{get:function(){return this._highlightsThreshold},set:function(e){this.setHighlightsThreshold(e)},enumerable:!1,configurable:!0}),t.prototype.setEdgeBlur=function(e){this._edgeBlur=e},t.prototype.disableEdgeBlur=function(){this._edgeBlur=0},t.prototype.setGrainAmount=function(e){this._grainAmount=e},t.prototype.disableGrain=function(){this._grainAmount=0},t.prototype.setChromaticAberration=function(e){this._chromaticAberration=e},t.prototype.disableChromaticAberration=function(){this._chromaticAberration=0},t.prototype.setEdgeDistortion=function(e){this._distortion=e},t.prototype.disableEdgeDistortion=function(){this._distortion=0},t.prototype.setFocusDistance=function(e){this._dofDistance=e},t.prototype.disableDepthOfField=function(){this._dofDistance=-1},t.prototype.setAperture=function(e){this._dofAperture=e},t.prototype.setDarkenOutOfFocus=function(e){this._dofDarken=e},t.prototype.enablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect(`#define PENTAGON -`),this._pentagonBokehIsEnabled=!0},t.prototype.disablePentagonBokeh=function(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()},t.prototype.enableNoiseBlur=function(){this._blurNoise=!0},t.prototype.disableNoiseBlur=function(){this._blurNoise=!1},t.prototype.setHighlightsGain=function(e){this._highlightsGain=e},t.prototype.setHighlightsThreshold=function(e){this._highlightsGain===-1&&(this._highlightsGain=1),this._highlightsThreshold=e},t.prototype.disableHighlights=function(){this._highlightsGain=-1},t.prototype.dispose=function(e){e===void 0&&(e=!1),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()},t.prototype._createChromaticAberrationPostProcess=function(e){var n=this;this._chromaticAberrationPostProcess=new _t("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,we.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=function(i){i.setFloat("chromatic_aberration",n._chromaticAberration),i.setFloat("screen_width",n._scene.getEngine().getRenderWidth()),i.setFloat("screen_height",n._scene.getEngine().getRenderHeight()),i.setFloat("radialIntensity",1),i.setFloat2("direction",17,17),i.setFloat2("centerPosition",.5,.5)}},t.prototype._createHighlightsPostProcess=function(e){var n=this;this._highlightsPostProcess=new _t("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,we.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?`#define PENTAGON -`:""),this._highlightsPostProcess.onApply=function(i){i.setFloat("gain",n._highlightsGain),i.setFloat("threshold",n._highlightsThreshold),i.setTextureFromPostProcess("textureSampler",n._chromaticAberrationPostProcess),i.setFloat("screen_width",n._scene.getEngine().getRenderWidth()),i.setFloat("screen_height",n._scene.getEngine().getRenderHeight())}},t.prototype._createDepthOfFieldPostProcess=function(e){var n=this;this._depthOfFieldPostProcess=new _t("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,we.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.onApply=function(i){i.setTexture("depthSampler",n._depthTexture),i.setTexture("grainSampler",n._grainTexture),i.setTextureFromPostProcess("textureSampler",n._highlightsPostProcess),i.setTextureFromPostProcess("highlightsSampler",n._depthOfFieldPostProcess),i.setFloat("grain_amount",n._grainAmount),i.setBool("blur_noise",n._blurNoise),i.setFloat("screen_width",n._scene.getEngine().getRenderWidth()),i.setFloat("screen_height",n._scene.getEngine().getRenderHeight()),i.setFloat("distortion",n._distortion),i.setBool("dof_enabled",n._dofDistance!==-1),i.setFloat("screen_distance",1/(.1-1/n._dofDistance)),i.setFloat("aperture",n._dofAperture),i.setFloat("darken",n._dofDarken),i.setFloat("edge_blur",n._edgeBlur),i.setBool("highlights",n._highlightsGain!==-1),n._scene.activeCamera&&(i.setFloat("near",n._scene.activeCamera.minZ),i.setFloat("far",n._scene.activeCamera.maxZ))}},t.prototype._createGrainTexture=function(){this._grainTexture=new yi.a("LensNoiseTexture",512,this._scene,!1,we.a.BILINEAR_SAMPLINGMODE),this._grainTexture.wrapU=we.a.WRAP_ADDRESSMODE,this._grainTexture.wrapV=we.a.WRAP_ADDRESSMODE;for(var e,n,i,o=this._grainTexture.getContext(),a=0;a<512;a++)for(var s=0;s<512;s++)e=Math.floor(255*(n=.42,i=.58,Math.random()*(i-n)+n)),o.fillStyle="rgb("+e+", "+e+", "+e+")",o.fillRect(a,s,1,1);this._grainTexture.update(!1)},t}(Ur),kg=function(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[h.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE]},Gg=` -precision highp float; -uniform sampler2D textureSampler; -uniform float near; -uniform float far; -uniform float radius; -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 -); -varying vec2 vUV; -float perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) { -return ( near*far )/( ( far-near )*invClipZ-far ); -} -float viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) { -return ( near*far/viewZ+far)/( far-near ); -} -float viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) { -return ( viewZ+near )/( near-far ); -} -#ifdef SSAO -uniform sampler2D randomSampler; -#ifndef GEOMETRYBUFFER -uniform sampler2D depthNormalSampler; -#else -uniform sampler2D depthSampler; -uniform sampler2D normalSampler; -#endif -uniform float randTextureTiles; -uniform float samplesFactor; -uniform vec3 sampleSphere[SAMPLES]; -uniform float totalStrength; -uniform float base; -uniform float xViewport; -uniform float yViewport; -uniform float maxZ; -uniform float minZAspect; -uniform vec2 texelSize; -uniform mat4 projection; -void main() -{ -vec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb; -#ifndef GEOMETRYBUFFER -float depth=texture2D(depthNormalSampler,vUV).r; -#else -float depth=texture2D(depthSampler,vUV).r; -#endif -float depthSign=depth/abs(depth); -depth=depth*depthSign; -#ifndef GEOMETRYBUFFER -vec3 normal=texture2D(depthNormalSampler,vUV).gba; -#else -vec3 normal=texture2D(normalSampler,vUV).rgb; -#endif -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 origin=vViewRay*depth; -vec3 rvec=random*2.0-1.0; -rvec.z=0.0; - -float dotProduct=dot(rvec,normal); -rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x); -vec3 tangent=normalize(rvec-normal*dot(rvec,normal)); -vec3 bitangent=cross(normal,tangent); -mat3 tbn=mat3(tangent,bitangent,normal); -float difference; -for (int i=0; i1.0 || offset.y>1.0) { -continue; -} - -#ifndef GEOMETRYBUFFER -float sampleDepth=abs(texture2D(depthNormalSampler,offset.xy).r); -#else -float sampleDepth=abs(texture2D(depthSampler,offset.xy).r); -#endif - -difference=depthSign*samplePosition.z-sampleDepth; -float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference); -occlusion+=(difference>=0.0 ? 1.0 : 0.0)*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 BILATERAL_BLUR -uniform sampler2D depthNormalSampler; -uniform float outSize; -uniform float samplerOffsets[SAMPLES]; -vec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) { -vec4 color=vec4(0.0); -vec2 off1=vec2(1.3846153846)*direction; -vec2 off2=vec2(3.2307692308)*direction; -color+=texture2D(image,uv)*0.2270270270; -color+=texture2D(image,uv+(off1/resolution))*0.3162162162; -color+=texture2D(image,uv-(off1/resolution))*0.3162162162; -color+=texture2D(image,uv+(off2/resolution))*0.0702702703; -color+=texture2D(image,uv-(off2/resolution))*0.0702702703; -return color; -} -vec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) { -vec4 color=vec4(0.0); -vec2 off1=vec2(1.411764705882353)*direction; -vec2 off2=vec2(3.2941176470588234)*direction; -vec2 off3=vec2(5.176470588235294)*direction; -color+=texture2D(image,uv)*0.1964825501511404; -color+=texture2D(image,uv+(off1/resolution))*0.2969069646728344; -color+=texture2D(image,uv-(off1/resolution))*0.2969069646728344; -color+=texture2D(image,uv+(off2/resolution))*0.09447039785044732; -color+=texture2D(image,uv-(off2/resolution))*0.09447039785044732; -color+=texture2D(image,uv+(off3/resolution))*0.010381362401148057; -color+=texture2D(image,uv-(off3/resolution))*0.010381362401148057; -return color; -} -vec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) { -vec4 color=vec4(0.0); -vec2 off1=vec2(1.411764705882353)*direction; -vec2 off2=vec2(3.2941176470588234)*direction; -vec2 off3=vec2(5.176470588235294)*direction; -float compareDepth=abs(texture2D(depthNormalSampler,uv).r); -float sampleDepth; -float weight; -float weightSum=30.0; -color+=texture2D(image,uv)*30.0; -sampleDepth=abs(texture2D(depthNormalSampler,uv+(off1/resolution)).r); -weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0); -weightSum+=weight; -color+=texture2D(image,uv+(off1/resolution))*weight; -sampleDepth=abs(texture2D(depthNormalSampler,uv-(off1/resolution)).r); -weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0); -weightSum+=weight; -color+=texture2D(image,uv-(off1/resolution))*weight; -sampleDepth=abs(texture2D(depthNormalSampler,uv+(off2/resolution)).r); -weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0); -weightSum+=weight; -color+=texture2D(image,uv+(off2/resolution))*weight; -sampleDepth=abs(texture2D(depthNormalSampler,uv-(off2/resolution)).r); -weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0); -weightSum+=weight; -color+=texture2D(image,uv-(off2/resolution))*weight; -sampleDepth=abs(texture2D(depthNormalSampler,uv+(off3/resolution)).r); -weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0); -weightSum+=weight; -color+=texture2D(image,uv+(off3/resolution))*weight; -sampleDepth=abs(texture2D(depthNormalSampler,uv-(off3/resolution)).r); -weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0); -weightSum+=weight; -color+=texture2D(image,uv-(off3/resolution))*weight; -return color/weightSum; -} -void main() -{ -#if EXPENSIVE -float compareDepth=abs(texture2D(depthNormalSampler,vUV).r); -float texelsize=1.0/outSize; -float result=0.0; -float weightSum=0.0; -for (int i=0; i=2},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"SSAO2RenderingPipeline"},t.prototype.dispose=function(e){e===void 0&&(e=!1);for(var n=0;n0?i._ssaoCombinePostProcess.width:i._originalColorPostProcess.width),s.setFloat("near",i._scene.activeCamera.minZ),s.setFloat("far",i._scene.activeCamera.maxZ),s.setFloat("radius",i.radius),i._forceGeometryBuffer?s.setTexture("depthNormalSampler",i._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]):s.setTexture("depthNormalSampler",i._prePassRenderer.prePassRT.textures[i._prePassRenderer.getIndex(h.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE)]),s.setArray("samplerOffsets",i._samplerOffsets))},this._blurVPostProcess=new _t("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthNormalSampler"],n,null,we.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,`#define BILATERAL_BLUR -#define BILATERAL_BLUR_V -#define SAMPLES 16 -#define EXPENSIVE `+(o?"1":"0")+` -`),this._blurVPostProcess.onApply=function(s){i._scene.activeCamera&&(s.setFloat("outSize",i._ssaoCombinePostProcess.height>0?i._ssaoCombinePostProcess.height:i._originalColorPostProcess.height),s.setFloat("near",i._scene.activeCamera.minZ),s.setFloat("far",i._scene.activeCamera.maxZ),s.setFloat("radius",i.radius),i._forceGeometryBuffer?s.setTexture("depthNormalSampler",i._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]):s.setTexture("depthNormalSampler",i._prePassRenderer.prePassRT.textures[i._prePassRenderer.getIndex(h.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE)]),s.setArray("samplerOffsets",i._samplerOffsets))},this._blurHPostProcess.samples=this.textureSamples,this._blurVPostProcess.samples=this.textureSamples},t.prototype._rebuild=function(){r.prototype._rebuild.call(this)},t.prototype._radicalInverse_VdC=function(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]},t.prototype._hammersley=function(e,n){return[e/n,this._radicalInverse_VdC(e)]},t.prototype._hemisphereSample_uniform=function(e,n){var i=2*n*Math.PI,o=1-(.85*e+.15),a=Math.sqrt(1-o*o);return new u.e(Math.cos(i)*a,Math.sin(i)*a,o)},t.prototype._generateHemisphere=function(){for(var e,n=this.samples,i=[],o=0;o0.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; -} - -ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) -{ -ReflectionInfo info; -vec4 projectedCoord; -float sampledDepth; -dir*=step; -for(int i=0; i>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join(` -`))},t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,i,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"threshold",void 0),Object(c.c)([Object(L.c)()],t.prototype,"strength",void 0),Object(c.c)([Object(L.c)()],t.prototype,"reflectionSpecularFalloffExponent",void 0),Object(c.c)([Object(L.c)()],t.prototype,"step",void 0),Object(c.c)([Object(L.c)()],t.prototype,"roughnessFactor",void 0),Object(c.c)([Object(L.c)()],t.prototype,"enableSmoothReflections",null),Object(c.c)([Object(L.c)()],t.prototype,"reflectionSamples",null),Object(c.c)([Object(L.c)()],t.prototype,"smoothSteps",null),t}(_t);R.a.RegisteredTypes["BABYLON.ScreenSpaceReflectionPostProcess"]=Kc;var Yg=`uniform sampler2D textureSampler; -varying vec2 vUV; -#if defined(PASS_POST_PROCESS) -void main(void) -{ -vec4 color=texture2D(textureSampler,vUV); -gl_FragColor=color; -} -#endif -#if defined(DOWN_SAMPLE_X4) -uniform vec2 dsOffsets[16]; -void main(void) -{ -vec4 average=vec4(0.0,0.0,0.0,0.0); -average=texture2D(textureSampler,vUV+dsOffsets[0]); -average+=texture2D(textureSampler,vUV+dsOffsets[1]); -average+=texture2D(textureSampler,vUV+dsOffsets[2]); -average+=texture2D(textureSampler,vUV+dsOffsets[3]); -average+=texture2D(textureSampler,vUV+dsOffsets[4]); -average+=texture2D(textureSampler,vUV+dsOffsets[5]); -average+=texture2D(textureSampler,vUV+dsOffsets[6]); -average+=texture2D(textureSampler,vUV+dsOffsets[7]); -average+=texture2D(textureSampler,vUV+dsOffsets[8]); -average+=texture2D(textureSampler,vUV+dsOffsets[9]); -average+=texture2D(textureSampler,vUV+dsOffsets[10]); -average+=texture2D(textureSampler,vUV+dsOffsets[11]); -average+=texture2D(textureSampler,vUV+dsOffsets[12]); -average+=texture2D(textureSampler,vUV+dsOffsets[13]); -average+=texture2D(textureSampler,vUV+dsOffsets[14]); -average+=texture2D(textureSampler,vUV+dsOffsets[15]); -average/=16.0; -gl_FragColor=average; -} -#endif -#if defined(BRIGHT_PASS) -uniform vec2 dsOffsets[4]; -uniform float brightThreshold; -void main(void) -{ -vec4 average=vec4(0.0,0.0,0.0,0.0); -average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y)); -average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y)); -average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y)); -average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y)); -average*=0.25; -float luminance=length(average.rgb); -if (luminanceshadowPixelDepth) -accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection)); -currentPosition+=stepL; -} -accumFog/=NB_STEPS; -vec3 color=accumFog*scatteringPower; -gl_FragColor=vec4(color*exp(color) ,1.0); -} -#endif -#if defined(VLSMERGE) -uniform sampler2D originalSampler; -void main(void) -{ -gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV); -} -#endif -#if defined(LUMINANCE) -uniform vec2 lumOffsets[4]; -void main() -{ -float average=0.0; -vec4 color=vec4(0.0); -float maximum=-1e20; -vec3 weight=vec3(0.299,0.587,0.114); -for (int i=0; i<4; i++) -{ -color=texture2D(textureSampler,vUV+ lumOffsets[i]); - -float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); - -#ifdef WEIGHTED_AVERAGE -float GreyValue=dot(color.rgb,weight); -#endif -#ifdef BRIGHTNESS -float GreyValue=max(color.r,max(color.g,color.b)); -#endif -#ifdef HSL_COMPONENT -float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); -#endif -#ifdef MAGNITUDE -float GreyValue=length(color.rgb); -#endif -maximum=max(maximum,GreyValue); -average+=(0.25*log(1e-5+GreyValue)); -} -average=exp(average); -gl_FragColor=vec4(average,maximum,0.0,1.0); -} -#endif -#if defined(LUMINANCE_DOWN_SAMPLE) -uniform vec2 dsOffsets[9]; -uniform float halfDestPixelSize; -#ifdef FINAL_DOWN_SAMPLER -#include -#endif -void main() -{ -vec4 color=vec4(0.0); -float average=0.0; -for (int i=0; i<9; i++) -{ -color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]); -average+=color.r; -} -average/=9.0; -#ifdef FINAL_DOWN_SAMPLER -gl_FragColor=pack(average); -#else -gl_FragColor=vec4(average,average,0.0,1.0); -#endif -} -#endif -#if defined(HDR) -uniform sampler2D textureAdderSampler; -uniform float averageLuminance; -void main() -{ -vec4 color=texture2D(textureAdderSampler,vUV); -#ifndef AUTO_EXPOSURE -vec4 adjustedColor=color/averageLuminance; -color=adjustedColor; -color.a=1.0; -#endif -gl_FragColor=color; -} -#endif -#if defined(LENS_FLARE) -#define GHOSTS 3 -uniform sampler2D lensColorSampler; -uniform float strength; -uniform float ghostDispersal; -uniform float haloWidth; -uniform vec2 resolution; -uniform float distortionStrength; -float hash(vec2 p) -{ -float h=dot(p,vec2(127.1,311.7)); -return -1.0+2.0*fract(sin(h)*43758.5453123); -} -float noise(in vec2 p) -{ -vec2 i=floor(p); -vec2 f=fract(p); -vec2 u=f*f*(3.0-2.0*f); -return mix(mix(hash(i+vec2(0.0,0.0)), -hash(i+vec2(1.0,0.0)),u.x), -mix(hash(i+vec2(0.0,1.0)), -hash(i+vec2(1.0,1.0)),u.x),u.y); -} -float fbm(vec2 p) -{ -float f=0.0; -f+=0.5000*noise(p); p*=2.02; -f+=0.2500*noise(p); p*=2.03; -f+=0.1250*noise(p); p*=2.01; -f+=0.0625*noise(p); p*=2.04; -f/=0.9375; -return f; -} -vec3 pattern(vec2 uv) -{ -vec2 p=-1.0+2.0*uv; -float p2=dot(p,p); -float f=fbm(vec2(15.0*p2))/2.0; -float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5))); -float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5))); -float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5))); -return (1.0-f)*vec3(r,g,b); -} -float luminance(vec3 color) -{ -return dot(color.rgb,vec3(0.2126,0.7152,0.0722)); -} -vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) -{ -return vec4( -texture2D(tex,texcoord+direction*distortion.r).r, -texture2D(tex,texcoord+direction*distortion.g).g, -texture2D(tex,texcoord+direction*distortion.b).b, -1.0 -); -} -void main(void) -{ -vec2 uv=-vUV+vec2(1.0); -vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal; -vec2 texelSize=1.0/resolution; -vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength); -vec4 result=vec4(0.0); -float ghostIndice=1.0; -for (int i=0; i=nSamples) -break; -vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); -result+=texture2D(textureSampler,offset1); -} -gl_FragColor=result/float(nSamples); -} -#endif -`;je.a.ShadersStore.standardPixelShader=Yg;var Jd=function(r){function t(e,n,i,o,a){o===void 0&&(o=null);var s=r.call(this,n.getEngine(),e)||this;return s.downSampleX4PostProcess=null,s.brightPassPostProcess=null,s.blurHPostProcesses=[],s.blurVPostProcesses=[],s.textureAdderPostProcess=null,s.volumetricLightPostProcess=null,s.volumetricLightSmoothXPostProcess=null,s.volumetricLightSmoothYPostProcess=null,s.volumetricLightMergePostProces=null,s.volumetricLightFinalPostProcess=null,s.luminancePostProcess=null,s.luminanceDownSamplePostProcesses=[],s.hdrPostProcess=null,s.textureAdderFinalPostProcess=null,s.lensFlareFinalPostProcess=null,s.hdrFinalPostProcess=null,s.lensFlarePostProcess=null,s.lensFlareComposePostProcess=null,s.motionBlurPostProcess=null,s.depthOfFieldPostProcess=null,s.fxaaPostProcess=null,s.screenSpaceReflectionPostProcess=null,s.brightThreshold=1,s.blurWidth=512,s.horizontalBlur=!1,s.lensTexture=null,s.volumetricLightCoefficient=.2,s.volumetricLightPower=4,s.volumetricLightBlurScale=64,s.sourceLight=null,s.hdrMinimumLuminance=1,s.hdrDecreaseRate=.5,s.hdrIncreaseRate=.5,s.lensColorTexture=null,s.lensFlareStrength=20,s.lensFlareGhostDispersal=1.4,s.lensFlareHaloWidth=.7,s.lensFlareDistortionStrength=16,s.lensFlareBlurWidth=512,s.lensStarTexture=null,s.lensFlareDirtTexture=null,s.depthOfFieldDistance=10,s.depthOfFieldBlurWidth=64,s.animations=[],s._currentDepthOfFieldSource=null,s._fixedExposure=1,s._currentExposure=1,s._hdrAutoExposure=!1,s._hdrCurrentLuminance=1,s._motionStrength=1,s._isObjectBasedMotionBlur=!1,s._camerasToBeAttached=[],s._bloomEnabled=!1,s._depthOfFieldEnabled=!1,s._vlsEnabled=!1,s._lensFlareEnabled=!1,s._hdrEnabled=!1,s._motionBlurEnabled=!1,s._fxaaEnabled=!1,s._screenSpaceReflectionsEnabled=!1,s._motionBlurSamples=64,s._volumetricLightStepsCount=50,s._samples=1,s._cameras=a||n.cameras,s._cameras=s._cameras.slice(),s._camerasToBeAttached=s._cameras.slice(),s._scene=n,s._basePostProcess=o,s._ratio=i,s._floatTextureType=n.getEngine().getCaps().textureFloatRender?h.a.TEXTURETYPE_FLOAT:h.a.TEXTURETYPE_HALF_FLOAT,n.postProcessRenderPipelineManager.addPipeline(s),s._buildPipeline(),s}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"exposure",{get:function(){return this._fixedExposure},set:function(e){this._fixedExposure=e,this._currentExposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hdrAutoExposure",{get:function(){return this._hdrAutoExposure},set:function(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){var n=["#define HDR"];e&&n.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(n.join(` -`))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"motionStrength",{get:function(){return this._motionStrength},set:function(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"objectBasedMotionBlur",{get:function(){return this._isObjectBasedMotionBlur},set:function(e){var n=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,n&&this._buildPipeline()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"BloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"DepthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"LensFlareEnabled",{get:function(){return this._lensFlareEnabled},set:function(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"HDREnabled",{get:function(){return this._hdrEnabled},set:function(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"VLSEnabled",{get:function(){return this._vlsEnabled},set:function(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void l.a.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"MotionBlurEnabled",{get:function(){return this._motionBlurEnabled},set:function(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"screenSpaceReflectionsEnabled",{get:function(){return this._screenSpaceReflectionsEnabled},set:function(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"volumetricLightStepsCount",{get:function(){return this._volumetricLightStepsCount},set:function(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect(`#define VLS -#define NB_STEPS `+e.toFixed(1)),this._volumetricLightStepsCount=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"motionBlurSamples",{get:function(){return this._motionBlurSamples},set:function(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect(`#define MOTION_BLUR -#define MAX_MOTION_SAMPLES `+e.toFixed(1))),this._motionBlurSamples=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!1,configurable:!0}),t.prototype._buildPipeline=function(){var e=this,n=this._ratio,i=this._scene;this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new Kc("HDRPass",i,n,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(function(){e._currentDepthOfFieldSource=e.screenSpaceReflectionPostProcess}),this.addEffect(new Rt(i.getEngine(),"HDRScreenSpaceReflections",function(){return e.screenSpaceReflectionPostProcess},!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new _t("HDRPass","standard",[],[],n,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(function(){e._currentDepthOfFieldSource=e.originalPostProcess}),this.addEffect(new Rt(i.getEngine(),"HDRPassPostProcess",function(){return e.originalPostProcess},!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(i,n/4),this._createBrightPassPostProcess(i,n/4),this._createBlurPostProcesses(i,n/4,1),this._createTextureAdderPostProcess(i,n),this.textureAdderFinalPostProcess=new _t("HDRDepthOfFieldSource","standard",[],[],n,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(i.getEngine(),"HDRBaseDepthOfFieldSource",function(){return e.textureAdderFinalPostProcess},!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(i,n),this.volumetricLightFinalPostProcess=new _t("HDRVLSFinal","standard",[],[],n,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(i.getEngine(),"HDRVLSFinal",function(){return e.volumetricLightFinalPostProcess},!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(i,n),this.lensFlareFinalPostProcess=new _t("HDRPostLensFlareDepthOfFieldSource","standard",[],[],n,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(i.getEngine(),"HDRPostLensFlareDepthOfFieldSource",function(){return e.lensFlareFinalPostProcess},!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(i,this._floatTextureType),this._createHdrPostProcess(i,n),this.hdrFinalPostProcess=new _t("HDRPostHDReDepthOfFieldSource","standard",[],[],n,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(i.getEngine(),"HDRPostHDReDepthOfFieldSource",function(){return e.hdrFinalPostProcess},!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(i,n/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(i,n)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(i,n),this._fxaaEnabled&&(this.fxaaPostProcess=new Ro("fxaa",1,null,we.a.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(i.getEngine(),"HDRFxaa",function(){return e.fxaaPostProcess},!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&l.a.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")},t.prototype._createDownSampleX4PostProcess=function(e,n){var i=this,o=new Array(32);this.downSampleX4PostProcess=new _t("HDRDownSampleX4","standard",["dsOffsets"],[],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=function(a){for(var s=0,d=i.downSampleX4PostProcess.width,p=i.downSampleX4PostProcess.height,y=-2;y<2;y++)for(var P=-2;P<2;P++)o[s]=(y+.5)*(1/d),o[s+1]=(P+.5)*(1/p),s+=2;a.setArray2("dsOffsets",o)},this.addEffect(new Rt(e.getEngine(),"HDRDownSampleX4",function(){return i.downSampleX4PostProcess},!0))},t.prototype._createBrightPassPostProcess=function(e,n){var i=this,o=new Array(8);this.brightPassPostProcess=new _t("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=function(a){var s=1/i.brightPassPostProcess.width,d=1/i.brightPassPostProcess.height;o[0]=-.5*s,o[1]=.5*d,o[2]=.5*s,o[3]=.5*d,o[4]=-.5*s,o[5]=-.5*d,o[6]=.5*s,o[7]=-.5*d,a.setArray2("dsOffsets",o),a.setFloat("brightThreshold",i.brightThreshold)},this.addEffect(new Rt(e.getEngine(),"HDRBrightPass",function(){return i.brightPassPostProcess},!0))},t.prototype._createBlurPostProcesses=function(e,n,i,o){var a=this;o===void 0&&(o="blurWidth");var s=e.getEngine(),d=new _n("HDRBlurH_"+i,new u.d(1,0),this[o],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),p=new _n("HDRBlurV_"+i,new u.d(0,1),this[o],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);d.onActivateObservable.add(function(){var y=d.width/s.getRenderWidth();d.kernel=a[o]*y}),p.onActivateObservable.add(function(){var y=p.height/s.getRenderHeight();p.kernel=a.horizontalBlur?64*y:a[o]*y}),this.addEffect(new Rt(e.getEngine(),"HDRBlurH"+i,function(){return d},!0)),this.addEffect(new Rt(e.getEngine(),"HDRBlurV"+i,function(){return p},!0)),this.blurHPostProcesses.push(d),this.blurVPostProcesses.push(p)},t.prototype._createTextureAdderPostProcess=function(e,n){var i=this;this.textureAdderPostProcess=new _t("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=function(o){o.setTextureFromPostProcess("otherSampler",i._vlsEnabled?i._currentDepthOfFieldSource:i.originalPostProcess),o.setTexture("lensSampler",i.lensTexture),o.setFloat("exposure",i._currentExposure),i._currentDepthOfFieldSource=i.textureAdderFinalPostProcess},this.addEffect(new Rt(e.getEngine(),"HDRTextureAdder",function(){return i.textureAdderPostProcess},!0))},t.prototype._createVolumetricLightPostProcess=function(e,n){var i=this,o=e.enableGeometryBufferRenderer();o.enablePosition=!0;var a=o.getGBuffer();this.volumetricLightPostProcess=new _t("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],n/8,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS -#define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));var s=u.d.Zero();this.volumetricLightPostProcess.onApply=function(d){if(i.sourceLight&&i.sourceLight.getShadowGenerator()&&i._scene.activeCamera){var p=i.sourceLight.getShadowGenerator();d.setTexture("shadowMapSampler",p.getShadowMap()),d.setTexture("positionSampler",a.textures[2]),d.setColor3("sunColor",i.sourceLight.diffuse),d.setVector3("sunDirection",i.sourceLight.getShadowDirection()),d.setVector3("cameraPosition",i._scene.activeCamera.globalPosition),d.setMatrix("shadowViewProjection",p.getTransformMatrix()),d.setFloat("scatteringCoefficient",i.volumetricLightCoefficient),d.setFloat("scatteringPower",i.volumetricLightPower),s.x=i.sourceLight.getDepthMinZ(i._scene.activeCamera),s.y=i.sourceLight.getDepthMaxZ(i._scene.activeCamera),d.setVector2("depthValues",s)}},this.addEffect(new Rt(e.getEngine(),"HDRVLS",function(){return i.volumetricLightPostProcess},!0)),this._createBlurPostProcesses(e,n/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new _t("HDRVLSMerge","standard",[],["originalSampler"],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=function(d){d.setTextureFromPostProcess("originalSampler",i._bloomEnabled?i.textureAdderFinalPostProcess:i.originalPostProcess),i._currentDepthOfFieldSource=i.volumetricLightFinalPostProcess},this.addEffect(new Rt(e.getEngine(),"HDRVLSMerge",function(){return i.volumetricLightMergePostProces},!0))},t.prototype._createLuminancePostProcesses=function(e,n){var i=this,o=Math.pow(3,t.LuminanceSteps);this.luminancePostProcess=new _t("HDRLuminance","standard",["lumOffsets"],[],{width:o,height:o},null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",n);var a=[];this.luminancePostProcess.onApply=function(P){var O=1/i.luminancePostProcess.width,U=1/i.luminancePostProcess.height;a[0]=-.5*O,a[1]=.5*U,a[2]=.5*O,a[3]=.5*U,a[4]=-.5*O,a[5]=-.5*U,a[6]=.5*O,a[7]=-.5*U,P.setArray2("lumOffsets",a)},this.addEffect(new Rt(e.getEngine(),"HDRLuminance",function(){return i.luminancePostProcess},!0));for(var s=t.LuminanceSteps-1;s>=0;s--){o=Math.pow(3,s);var d=`#define LUMINANCE_DOWN_SAMPLE -`;s===0&&(d+="#define FINAL_DOWN_SAMPLER");var p=new _t("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:o,height:o},null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,d,n);this.luminanceDownSamplePostProcesses.push(p)}var y=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(function(P,O){var U=new Array(18);P.onApply=function(F){if(y){for(var z=0,J=-1;J<2;J++)for(var ie=-1;ie<2;ie++)U[z]=J/y.width,U[z+1]=ie/y.height,z+=2;F.setArray2("dsOffsets",U),F.setFloat("halfDestPixelSize",.5/y.width),y=O===i.luminanceDownSamplePostProcesses.length-1?i.luminancePostProcess:P}},O===i.luminanceDownSamplePostProcesses.length-1&&(P.onAfterRender=function(){var F=e.getEngine().readPixels(0,0,1,1),z=new u.f(1/16581375,1/65025,1/255,1);i._hdrCurrentLuminance=(F[0]*z.x+F[1]*z.y+F[2]*z.z+F[3]*z.w)/100}),i.addEffect(new Rt(e.getEngine(),"HDRLuminanceDownSample"+O,function(){return P},!0))})},t.prototype._createHdrPostProcess=function(e,n){var i=this,o=["#define HDR"];this._hdrAutoExposure&&o.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new _t("HDR","standard",["averageLuminance"],["textureAdderSampler"],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o.join(` -`),h.a.TEXTURETYPE_UNSIGNED_INT);var a=1,s=0,d=0;this.hdrPostProcess.onApply=function(p){if(p.setTextureFromPostProcess("textureAdderSampler",i._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),a<0)a=i._hdrCurrentLuminance;else{var y=(d-s)/1e3;i._hdrCurrentLuminancea-i.hdrIncreaseRate*y?a-=i.hdrIncreaseRate*y:a=i._hdrCurrentLuminance}i.hdrAutoExposure?i._currentExposure=i._fixedExposure/a:(a=$.a.Clamp(a,i.hdrMinimumLuminance,1e20),p.setFloat("averageLuminance",a)),d=s,i._currentDepthOfFieldSource=i.hdrFinalPostProcess},this.addEffect(new Rt(e.getEngine(),"HDR",function(){return i.hdrPostProcess},!0))},t.prototype._createLensFlarePostProcess=function(e,n){var i=this;this.lensFlarePostProcess=new _t("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],n/2,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(e.getEngine(),"HDRLensFlare",function(){return i.lensFlarePostProcess},!0)),this._createBlurPostProcesses(e,n/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new _t("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",h.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Rt(e.getEngine(),"HDRLensFlareCompose",function(){return i.lensFlareComposePostProcess},!0));var o=new u.d(0,0);this.lensFlarePostProcess.onApply=function(d){d.setTextureFromPostProcess("textureSampler",i._bloomEnabled?i.blurHPostProcesses[0]:i.originalPostProcess),d.setTexture("lensColorSampler",i.lensColorTexture),d.setFloat("strength",i.lensFlareStrength),d.setFloat("ghostDispersal",i.lensFlareGhostDispersal),d.setFloat("haloWidth",i.lensFlareHaloWidth),o.x=i.lensFlarePostProcess.width,o.y=i.lensFlarePostProcess.height,d.setVector2("resolution",o),d.setFloat("distortionStrength",i.lensFlareDistortionStrength)};var a=u.a.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=u.a.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(d){if(i._scene.activeCamera){d.setTextureFromPostProcess("otherSampler",i.lensFlarePostProcess),d.setTexture("lensDirtSampler",i.lensFlareDirtTexture),d.setTexture("lensStarSampler",i.lensStarTexture);var p=i._scene.activeCamera.getViewMatrix().getRow(0),y=i._scene.activeCamera.getViewMatrix().getRow(2),P=u.e.Dot(p.toVector3(),new u.e(1,0,0))+u.e.Dot(y.toVector3(),new u.e(0,0,1));P*=4;var O=u.a.FromValues(.5*Math.cos(P),-Math.sin(P),0,0,Math.sin(P),.5*Math.cos(P),0,0,0,0,1,0,0,0,0,1),U=s.multiply(O).multiply(a);d.setMatrix("lensStarMatrix",U),i._currentDepthOfFieldSource=i.lensFlareFinalPostProcess}}},t.prototype._createDepthOfFieldPostProcess=function(e,n){var i=this;this.depthOfFieldPostProcess=new _t("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",h.a.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(o){o.setTextureFromPostProcess("otherSampler",i._currentDepthOfFieldSource),o.setTexture("depthSampler",i._getDepthTexture()),o.setFloat("distance",i.depthOfFieldDistance)},this.addEffect(new Rt(e.getEngine(),"HDRDepthOfField",function(){return i.depthOfFieldPostProcess},!0))},t.prototype._createMotionBlurPostProcess=function(e,n){var i=this;if(this._isObjectBasedMotionBlur){var o=new Xc("HDRMotionBlur",e,n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,h.a.TEXTURETYPE_UNSIGNED_INT);o.motionStrength=this.motionStrength,o.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=o}else{this.motionBlurPostProcess=new _t("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],n,null,we.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR -#define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),h.a.TEXTURETYPE_UNSIGNED_INT);var a=0,s=u.a.Identity(),d=u.a.Identity(),p=u.a.Identity(),y=u.d.Zero();this.motionBlurPostProcess.onApply=function(P){(p=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(d),P.setMatrix("inverseViewProjection",d),P.setMatrix("prevViewProjection",s),s=p,y.x=i.motionBlurPostProcess.width,y.y=i.motionBlurPostProcess.height,P.setVector2("screenSize",y),a=e.getEngine().getFps()/60,P.setFloat("motionScale",a),P.setFloat("motionStrength",i.motionStrength),P.setTexture("depthSampler",i._getDepthTexture())}}this.addEffect(new Rt(e.getEngine(),"HDRMotionBlur",function(){return i.motionBlurPostProcess},!0))},t.prototype._getDepthTexture=function(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()},t.prototype._disposePostProcesses=function(){for(var e=0;e0.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); -} -`;je.a.ShadersStore.stereoscopicInterlacePixelShader=Kg;var Qg=function(r){function t(e,n,i,o,a,s,d){var p=r.call(this,e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,n[1],a,s,d,o?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return p._passedProcess=n[0]._rigPostProcess,p._stepSize=new u.d(1/p.width,1/p.height),p.onSizeChangedObservable.add(function(){p._stepSize=new u.d(1/p.width,1/p.height)}),p.onApplyObservable.add(function(y){y.setTextureFromPostProcess("camASampler",p._passedProcess),y.setFloat2("stepSize",p._stepSize.x,p._stepSize.y)}),p}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicInterlacePostProcessI"},t}(_t),qg=function(r){function t(e,n,i,o,a,s){var d=r.call(this,e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,n[1],o,a,s,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return d._passedProcess=n[0]._rigPostProcess,d._stepSize=new u.d(1/d.width,1/d.height),d.onSizeChangedObservable.add(function(){d._stepSize=new u.d(1/d.width,1/d.height)}),d.onApplyObservable.add(function(p){p.setTextureFromPostProcess("camASampler",d._passedProcess),p.setFloat2("stepSize",d._stepSize.x,d._stepSize.y)}),d}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicInterlacePostProcess"},t}(_t),Zg=` -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)); -} -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); -}`;je.a.ShadersStore.tonemapPixelShader=Zg;var sr;(function(r){r[r.Hable=0]="Hable",r[r.Reinhard=1]="Reinhard",r[r.HejiDawson=2]="HejiDawson",r[r.Photographic=3]="Photographic"})(sr||(sr={}));var Jg=function(r){function t(e,n,i,o,a,s,d){a===void 0&&(a=h.a.TEXTURE_BILINEAR_SAMPLINGMODE),d===void 0&&(d=h.a.TEXTURETYPE_UNSIGNED_INT);var p=r.call(this,e,"tonemap",["_ExposureAdjustment"],null,1,o,a,s,!0,null,d)||this;p._operator=n,p.exposureAdjustment=i;var y="#define ";return p._operator===sr.Hable?y+="HABLE_TONEMAPPING":p._operator===sr.Reinhard?y+="REINHARD_TONEMAPPING":p._operator===sr.HejiDawson?y+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":p._operator===sr.Photographic&&(y+="PHOTOGRAPHIC_TONEMAPPING"),p.updateEffect(y),p.onApply=function(P){P.setFloat("_ExposureAdjustment",p.exposureAdjustment)},p}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"TonemapPostProcess"},t}(_t),$g=`uniform sampler2D textureSampler; -uniform sampler2D lightScatteringSampler; -uniform float decay; -uniform float exposure; -uniform float weight; -uniform float density; -uniform vec2 meshPositionOnScreen; -varying vec2 vUV; -void main(void) { -vec2 tc=vUV; -vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy); -deltaTexCoord*=1.0/float(NUM_SAMPLES)*density; -float illuminationDecay=1.0; -vec4 color=texture2D(lightScatteringSampler,tc)*0.4; -for(int i=0; i -#include -#include[0..maxSimultaneousMorphTargets] - -#include -uniform mat4 viewProjection; -uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -void main(void) -{ -vec3 positionUpdated=position; -#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -#include -#include -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;je.a.ShadersStore.volumetricLightScatteringPassVertexShader=ev;var tv=`#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -#endif -#if defined(ALPHATEST) -uniform sampler2D diffuseSampler; -#endif -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); -} -`;je.a.ShadersStore.volumetricLightScatteringPassPixelShader=tv;var $d=function(r){function t(e,n,i,o,a,s,d,p,y){a===void 0&&(a=100),s===void 0&&(s=we.a.BILINEAR_SAMPLINGMODE);var P=r.call(this,e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,i,s,d,p,"#define NUM_SAMPLES "+a)||this;return P._screenCoordinates=u.d.Zero(),P.customMeshPosition=u.e.Zero(),P.useCustomMeshPosition=!1,P.invert=!0,P.excludedMeshes=new Array,P.exposure=.3,P.decay=.96815,P.weight=.58767,P.density=.926,d=(y=i===null?y:i.getScene()).getEngine(),P._viewPort=new Wn.a(0,0,1,1).toGlobal(d.getRenderWidth(),d.getRenderHeight()),P.mesh=o!==null?o:t.CreateDefaultMesh("VolumetricLightScatteringMesh",y),P._createPass(y,n.passRatio||n),P.onActivate=function(O){P.isSupported||P.dispose(O),P.onActivate=null},P.onApplyObservable.add(function(O){P._updateMeshScreenCoordinates(y),O.setTexture("lightScatteringSampler",P._volumetricLightScatteringRTT),O.setFloat("exposure",P.exposure),O.setFloat("decay",P.decay),O.setFloat("weight",P.weight),O.setFloat("density",P.density),O.setVector2("meshPositionOnScreen",P._screenCoordinates)}),P}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"useDiffuseColor",{get:function(){return l.a.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(e){l.a.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},t.prototype._isReady=function(e,n){var i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);var o=[],a=[Me.b.PositionKind],s=e.getMaterial();s&&(s.needAlphaTesting()&&o.push("#define ALPHATEST"),i.isVerticesDataPresent(Me.b.UVKind)&&(a.push(Me.b.UVKind),o.push("#define UV1")),i.isVerticesDataPresent(Me.b.UV2Kind)&&(a.push(Me.b.UV2Kind),o.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(a.push(Me.b.MatricesIndicesKind),a.push(Me.b.MatricesWeightsKind),o.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),o.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):o.push("#define NUM_BONE_INFLUENCERS 0"),n&&(o.push("#define INSTANCES"),tt.a.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES"));var d=o.join(` -`);return this._cachedDefines!==d&&(this._cachedDefines=d,this._volumetricLightScatteringPass=i.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers})),this._volumetricLightScatteringPass.isReady()},t.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},t.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},t.prototype.dispose=function(e){var n=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);n!==-1&&e.getScene().customRenderTargets.splice(n,1),this._volumetricLightScatteringRTT.dispose(),r.prototype.dispose.call(this,e)},t.prototype.getPass=function(){return this._volumetricLightScatteringRTT},t.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1},t.prototype._createPass=function(e,n){var i=this,o=e.getEngine();this._volumetricLightScatteringRTT=new sn("volumetricLightScatteringMap",{width:o.getRenderWidth()*n,height:o.getRenderHeight()*n},e,!1,!0,h.a.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=we.a.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=we.a.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var a=this.getCamera();a?a.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);var s,d=function(y){var P=y.getRenderingMesh(),O=y.getEffectiveMesh();if(!i._meshExcluded(P)){O._internalAbstractMeshDataInfo._isActiveIntermediate=!1;var U=y.getMaterial();if(U){var F=P.getScene(),z=F.getEngine();z.setState(U.backFaceCulling);var J=P._getInstancesRenderList(y._id,!!y.getReplacementMesh());if(!J.mustReturn){var ie=z.getCaps().instancedArrays&&(J.visibleInstances[y._id]!==null||P.hasThinInstances);if(i._isReady(y,ie)){var se=i._volumetricLightScatteringPass;if(P===i.mesh&&(se=y.effect?y.effect:U.getEffect()),z.enableEffect(se),P._bind(y,se,U.fillMode),P===i.mesh)U.bind(O.getWorldMatrix(),P);else{if(i._volumetricLightScatteringPass.setMatrix("viewProjection",F.getTransformMatrix()),U&&U.needAlphaTesting()){var ce=U.getAlphaTestTexture();i._volumetricLightScatteringPass.setTexture("diffuseSampler",ce),ce&&i._volumetricLightScatteringPass.setMatrix("diffuseMatrix",ce.getTextureMatrix())}P.useBones&&P.computeBonesUsingShaders&&P.skeleton&&i._volumetricLightScatteringPass.setMatrices("mBones",P.skeleton.getTransformMatrices(P))}P._processRendering(O,y,i._volumetricLightScatteringPass,Ht.a.TriangleFillMode,J,ie,function(ue,fe){return se.setMatrix("world",fe)})}}}}},p=new M.b(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function(){s=e.clearColor,e.clearColor=p}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function(){e.clearColor=s}),this._volumetricLightScatteringRTT.customRenderFunction=function(y,P,O,U){var F,z=e.getEngine();if(U.length){for(z.setColorWrite(!1),F=0;Fue._alphaIndex?1:ce._alphaIndexue._distanceToCamera?-1:0}),z.setAlphaMode(h.a.ALPHA_COMBINE),F=0;F1||e.getCaps().drawBuffersExtension)},enumerable:!1,configurable:!0}),t._Parse=function(e,n,i,o){return L.a.Parse(function(){return new t(e.name,i,e.options,n,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)},e,i,o)},Object(c.c)([Object(L.c)()],t.prototype,"ridge",void 0),Object(c.c)([Object(L.c)()],t.prototype,"valley",void 0),t}(_t);R.a.RegisteredTypes["BABYLON.ScreenSpaceCurvaturePostProcess"]=ef,f(166),f(167),Object.defineProperty(_e.a.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(r){this._forceShowBoundingBoxes=r,r&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),_e.a.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new tf(this)),this._boundingBoxRenderer},Object.defineProperty(Dt.a.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(r){this._showBoundingBox=r,r&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});var tf=function(){function r(t){this.name=st.a.NAME_BOUNDINGBOXRENDERER,this.frontColor=new M.a(1,1,1),this.backColor=new M.a(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new x.c,this.onAfterBoxRenderingObservable=new x.c,this.onResourcesReadyObservable=new x.c,this.enabled=!0,this.renderList=new li.a(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=t,t._addComponent(this)}return r.prototype.register=function(){this.scene._beforeEvaluateActiveMeshStage.registerStep(st.a.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(st.a.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(st.a.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(st.a.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)},r.prototype._evaluateSubMesh=function(t,e){if(t.showSubMeshesBoundingBox){var n=e.getBoundingInfo();n!=null&&(n.boundingBox._tag=t.renderingGroupId,this.renderList.push(n.boundingBox))}},r.prototype._preActiveMesh=function(t){if(t.showBoundingBox||this.scene.forceShowBoundingBoxes){var e=t.getBoundingInfo();e.boundingBox._tag=t.renderingGroupId,this.renderList.push(e.boundingBox)}},r.prototype._prepareResources=function(){if(!this._colorShader){this._colorShader=new fa.a("colorShader",this.scene,"color",{attributes:[Me.b.PositionKind],uniforms:["world","viewProjection","color"]}),this._colorShader.reservedDataStore={hidden:!0};var t=this.scene.getEngine(),e=ft.a.CreateBox({size:1});this._vertexBuffers[Me.b.PositionKind]=new Me.b(t,e.positions,Me.b.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=e.indices,this.onResourcesReadyObservable.notifyObservers(this)}},r.prototype._createIndexBuffer=function(){var t=this.scene.getEngine();this._indexBuffer=t.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])},r.prototype.rebuild=function(){var t=this._vertexBuffers[Me.b.PositionKind];t&&t._rebuild(),this._createIndexBuffer()},r.prototype.reset=function(){this.renderList.reset()},r.prototype.render=function(t){if(this.renderList.length!==0&&this.enabled&&(this._prepareResources(),this._colorShader.isReady())){var e=this.scene.getEngine();e.setDepthWrite(!1),this._colorShader._preBind();for(var n=0;n - -attribute vec3 position; -attribute vec4 normal; - -uniform mat4 viewProjection; -uniform float width; -uniform float aspectRatio; -void main(void) { -#include -mat4 worldViewProjection=viewProjection*finalWorld; -vec4 viewPosition=worldViewProjection*vec4(position,1.0); -vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0); -vec2 currentScreen=viewPosition.xy/viewPosition.w; -vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w; -currentScreen.x*=aspectRatio; -nextScreen.x*=aspectRatio; -vec2 dir=normalize(nextScreen-currentScreen); -vec2 normalDir=vec2(-dir.y,dir.x); -normalDir*=width/2.0; -normalDir.x/=aspectRatio; -vec4 offset=vec4(normalDir*normal.w,0.0,0.0); -gl_Position=viewPosition+offset; -}`;je.a.ShadersStore.lineVertexShader=iv,Dt.a.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Dt.a.prototype.enableEdgesRendering=function(r,t,e){return r===void 0&&(r=.95),t===void 0&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new Qc(this,r,t,!0,e),this},Object.defineProperty(Dt.a.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),Eo.b.prototype.enableEdgesRendering=function(r,t){return r===void 0&&(r=.95),t===void 0&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new rf(this,r,t),this},Eo.a.prototype.enableEdgesRendering=function(r,t){return r===void 0&&(r=.95),t===void 0&&(t=!1),Eo.b.prototype.enableEdgesRendering.apply(this,arguments),this};var rv=function(){this.edges=new Array,this.edgesConnectedCount=0},Qc=function(){function r(t,e,n,i,o){var a,s=this;e===void 0&&(e=.95),n===void 0&&(n=!1),i===void 0&&(i=!0),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new li.a(32),this._source=t,this._checkVerticesInsteadOfIndices=n,this._options=o??null,this._epsilon=e,this._prepareRessources(),i&&((a=o?.useAlternateEdgeFinder)===null||a===void 0||a?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(function(){s._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(function(){s.dispose()})}return Object.defineProperty(r.prototype,"linesPositions",{get:function(){return this._linesPositions},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"linesNormals",{get:function(){return this._linesNormals},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"linesIndices",{get:function(){return this._linesIndices},enumerable:!1,configurable:!0}),r.GetShader=function(t){if(!t._edgeRenderLineShader){var e=new fa.a("lineShader",t,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]});e.disableDepthWrite=!0,e.backFaceCulling=!1,t._edgeRenderLineShader=e}return t._edgeRenderLineShader},r.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=r.GetShader(this._source.getScene()))},r.prototype._rebuild=function(){var t=this._buffers[Me.b.PositionKind];t&&t._rebuild(),(t=this._buffers[Me.b.NormalKind])&&t._rebuild();var e=this._source.getScene().getEngine();this._ib=e.createIndexBuffer(this._linesIndices)},r.prototype.dispose=function(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);var t=this._buffers[Me.b.PositionKind];t&&(t.dispose(),this._buffers[Me.b.PositionKind]=null),(t=this._buffers[Me.b.NormalKind])&&(t.dispose(),this._buffers[Me.b.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},r.prototype._processEdgeForAdjacencies=function(t,e,n,i,o){return t===n&&e===i||t===i&&e===n?0:t===i&&e===o||t===o&&e===i?1:t===o&&e===n||t===n&&e===o?2:-1},r.prototype._processEdgeForAdjacenciesWithVertices=function(t,e,n,i,o){var a=1e-10;return t.equalsWithEpsilon(n,a)&&e.equalsWithEpsilon(i,a)||t.equalsWithEpsilon(i,a)&&e.equalsWithEpsilon(n,a)?0:t.equalsWithEpsilon(i,a)&&e.equalsWithEpsilon(o,a)||t.equalsWithEpsilon(o,a)&&e.equalsWithEpsilon(i,a)?1:t.equalsWithEpsilon(o,a)&&e.equalsWithEpsilon(n,a)||t.equalsWithEpsilon(n,a)&&e.equalsWithEpsilon(o,a)?2:-1},r.prototype._checkEdge=function(t,e,n,i,o){var a;e===void 0?a=!0:a=u.e.Dot(n[t],n[e])=0&&Ee.push(Se);for(var Le=0;Le=t[0].length&&t[1].length>=t[2].length?a=1:t[2].length>=t[0].length&&t[2].length>=t[1].length&&(a=2);for(var s=0;s<3;++s)s===a?t[s].sort(function(Pe,Ee){return Pe[1]Ee[1]?1:0}):t[s].sort(function(Pe,Ee){return Pe[1]>Ee[1]?-1:Pe[1]=a+1;--P)o(t[P%3],p,P!==a+2?i[n[e+(P+1)%3]]:-1);var O=p.length;n.push(i[n[e+a]],d[0],p[0]),n.push(i[n[e+(a+1)%3]],p[O-1],d[y-1]);for(var U=y<=O,F=U?y:O,z=U?O:y,J=U?y-1:O-1,ie=U?0:1,se=y+O-2,ce=0,ue=0,fe=U?d:p,ve=U?p:d,Te=0;se-- >0;){ie?n.push(fe[ce],ve[ue]):n.push(ve[ue],fe[ce]);var Oe=void 0;(Te+=F)>=z&&ceKe){var Et=Fe;Fe=Ke,Ke=Et}($t=zt[Mt=Fe+"_"+Ke])?$t.done||(u.e.Dot(Yt,$t.normal)0||this._source.hasThinInstances)},r.prototype.render=function(){var t=this._source.getScene();if(this.isReady()&&t.activeCamera){var e=t.getEngine();this._lineShader._preBind(),this._source.edgesColor.a!==1?e.setAlphaMode(h.a.ALPHA_COMBINE):e.setAlphaMode(h.a.ALPHA_DISABLE);var n=this._source.hasInstances&&this.customInstances.length>0,i=n||this._source.hasThinInstances,o=0;if(i)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"),n){var a=this._source._instanceDataStorage;if(o=this.customInstances.length,!a.isFrozen){for(var s=0,d=0;d0&&(e.push(!0),n.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(t),this._clearAttachments=this._engine.buildTextureLayout(e),this._defaultAttachments=this._engine.buildTextureLayout(n)},r.prototype._createCompositionEffect=function(){this.prePassRT=new tc("sceneprePassRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},this.mrtCount,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:h.a.TEXTURETYPE_UNSIGNED_INT,types:this._mrtFormats}),this.prePassRT.samples=1,this._initializeAttachments(),this._useGeometryBufferFallback&&!this._geometryBuffer&&(this.useGeometryBufferFallback=!0),this.imageProcessingPostProcess=new Ho("sceneCompositionPass",1,null,void 0,this._engine),this.imageProcessingPostProcess.autoClear=!1},Object.defineProperty(r.prototype,"isSupported",{get:function(){return this._engine.webGLVersion>1||this._scene.getEngine().getCaps().drawBuffersExtension},enumerable:!1,configurable:!0}),r.prototype.bindAttachmentsForEffect=function(t,e){if(this.enabled){if(t._multiTarget)this._engine.bindAttachments(this._multiRenderAttachments);else if(this._engine.bindAttachments(this._defaultAttachments),this._geometryBuffer){var n=e.getMaterial();n&&this.excludedMaterials.indexOf(n)===-1&&this._geometryBuffer.renderList.push(e.getRenderingMesh())}}},r.prototype.restoreAttachments=function(){this.enabled&&this._defaultAttachments&&this._engine.bindAttachments(this._defaultAttachments)},r.prototype._beforeCameraDraw=function(){this._isDirty&&this._update(),this._geometryBuffer&&(this._geometryBuffer.renderList.length=0),this._bindFrameBuffer()},r.prototype._afterCameraDraw=function(){if(this._enabled){var t=this._scene.activeCamera&&this._scene.activeCamera._getFirstPostProcess();t&&this._postProcesses.length&&this._scene.postProcessManager._prepareFrame(),this._scene.postProcessManager.directRender(this._postProcesses,t?t.inputTexture:null)}},r.prototype._checkRTSize=function(){var t=this._engine.getRenderWidth(!0),e=this._engine.getRenderHeight(!0),n=this.prePassRT.getRenderWidth(),i=this.prePassRT.getRenderHeight();n===t&&i===e||(this.prePassRT.resize({width:t,height:e}),this._updateGeometryBufferLayout(),this._bindPostProcessChain())},r.prototype._bindFrameBuffer=function(){if(this._enabled){this._checkRTSize();var t=this.prePassRT.getInternalTexture();t&&this._engine.bindFramebuffer(t)}},r.prototype.clear=function(){this._enabled&&(this._bindFrameBuffer(),this._engine.clear(this._scene.clearColor,this._scene.autoClear||this._scene.forceWireframe||this._scene.forcePointsCloud,this._scene.autoClearDepthAndStencil,this._scene.autoClearDepthAndStencil),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._engine.bindAttachments(this._defaultAttachments))},r.prototype._setState=function(t){this._enabled=t,this._scene.prePass=t,this.imageProcessingPostProcess&&(this.imageProcessingPostProcess.imageProcessingConfiguration.applyByPostProcess=t)},r.prototype._updateGeometryBufferLayout=function(){if(this._geometryBuffer){this._geometryBuffer._resetLayout();for(var t=[],e=0;e -#include -#include -#include -varying vec2 vUV; -uniform vec2 texelSize; -uniform sampler2D textureSampler; -uniform sampler2D irradianceSampler; -uniform sampler2D depthSampler; -uniform sampler2D albedoSampler; -uniform vec2 viewportSize; -uniform float metersPerUnit; -const float LOG2_E=1.4426950408889634; -const float SSS_PIXELS_PER_SAMPLE=4.; -const int _SssSampleBudget=40; -#define rcp(x) 1./x -#define Sq(x) x*x -#define SSS_BILATERAL_FILTER true - - -vec3 EvalBurleyDiffusionProfile(float r,vec3 S) -{ -vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); -vec3 expSum=exp_13*(1.+exp_13*exp_13); -return (S*rcp(8.*PI))*expSum; -} - - - - - - -vec2 SampleBurleyDiffusionProfile(float u,float rcpS) -{ -u=1.-u; -float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u)); -float n=exp2(log2(g)*(-1.0/3.0)); -float p=(g*n)*n; -float c=1.+p+n; -float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); -float x=(3./LOG2_E)*log2(c)-d; - - - - - - -float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u))); -float r=x*rcpS; -float rcpPdf=(8.*PI*rcpS)*rcpExp; -return vec2(r,rcpPdf); -} - - -vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) -{ -#ifndef SSS_BILATERAL_FILTER -z=0.; -#endif - - - -float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit)); -float area=rcpPdf; -#if SSS_CLAMP_ARTIFACT -return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); -#else -return EvalBurleyDiffusionProfile(r,S)*area; -#endif -} -void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, -float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) -{ - -float scale=rcp(float(n)); -float offset=rcp(float(n))*0.5; - -float sinPhase,cosPhase; -sinPhase=sin(phase); -cosPhase=cos(phase); -vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d); -float r=bdp.x; -float rcpPdf=bdp.y; -float phi=SampleDiskGolden(i,n).y; -float sinPhi,cosPhi; -sinPhi=sin(phi); -cosPhi=cos(phi); -float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; -float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; -vec2 vec=r*vec2(cosPsi,sinPsi); - -vec2 position; -float xy2; -position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize; -xy2=r*r; -vec4 textureSample=texture2D(irradianceSampler,position); -float viewZ=texture2D(depthSampler,position).r; -vec3 irradiance=textureSample.rgb; -if (testLightingForSSS(textureSample.a)) -{ - -float relZ=viewZ-centerPosVS.z; -vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf); -totalIrradiance+=weight*irradiance; -totalWeight+=weight; -} -else -{ - - - - - - -} -} -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=5)return l.a.Error("You already reached the maximum number of diffusion profiles."),0;for(var e=0;e -void main(void) { -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#include -gl_FragColor=color; -}`;je.a.ShadersStore.outlinePixelShader=lv;var uv=` -attribute vec3 position; -attribute vec3 normal; -#include -#include -#include[0..maxSimultaneousMorphTargets] - -uniform float offset; -#include -uniform mat4 viewProjection; -#ifdef ALPHATEST -varying vec2 vUV; -uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include -void main(void) -{ -vec3 positionUpdated=position; -vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include[0..maxSimultaneousMorphTargets] -vec3 offsetPosition=positionUpdated+(normalUpdated*offset); -#include -#include -gl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0); -#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 -} -`;je.a.ShadersStore.outlineVertexShader=uv,_e.a.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new cf(this)),this._outlineRenderer},Object.defineProperty(De.a.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(r){r&&this.getScene().getOutlineRenderer(),this._renderOutline=r},enumerable:!0,configurable:!0}),Object.defineProperty(De.a.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(r){r&&this.getScene().getOutlineRenderer(),this._renderOverlay=r},enumerable:!0,configurable:!0});var cf=function(){function r(t){this.name=st.a.NAME_OUTLINERENDERER,this.zOffset=1,this.scene=t,this._engine=t.getEngine(),this.scene._addComponent(this)}return r.prototype.register=function(){this.scene._beforeRenderingMeshStage.registerStep(st.a.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(st.a.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)},r.prototype.rebuild=function(){},r.prototype.dispose=function(){},r.prototype.render=function(t,e,n){var i=this;n===void 0&&(n=!1);var o=this.scene,a=o.getEngine(),s=a.getCaps().instancedArrays&&(e.visibleInstances[t._id]!==null&&e.visibleInstances[t._id]!==void 0||t.getRenderingMesh().hasThinInstances);if(this.isReady(t,s)){var d=t.getMesh(),p=d._internalAbstractMeshDataInfo._actAsRegularMesh?d:null,y=t.getRenderingMesh(),P=p||y,O=t.getMaterial();if(O&&o.activeCamera){if(a.enableEffect(this._effect),O.useLogarithmicDepth&&this._effect.setFloat("logarithmicDepthConstant",2/(Math.log(o.activeCamera.maxZ+1)/Math.LN2)),this._effect.setFloat("offset",n?0:y.outlineWidth),this._effect.setColor4("color",n?y.overlayColor:y.outlineColor,n?y.overlayAlpha:O.alpha),this._effect.setMatrix("viewProjection",o.getTransformMatrix()),this._effect.setMatrix("world",P.getWorldMatrix()),y.useBones&&y.computeBonesUsingShaders&&y.skeleton&&this._effect.setMatrices("mBones",y.skeleton.getTransformMatrices(y)),tt.a.BindMorphTargetParameters(y,this._effect),y._bind(t,this._effect,O.fillMode),O&&O.needAlphaTesting()){var U=O.getAlphaTestTexture();U&&(this._effect.setTexture("diffuseSampler",U),this._effect.setMatrix("diffuseMatrix",U.getTextureMatrix()))}a.setZOffset(-this.zOffset),y._processRendering(P,t,this._effect,O.fillMode,e,s,function(F,z){i._effect.setMatrix("world",z)}),a.setZOffset(0)}}},r.prototype.isReady=function(t,e){var n=[],i=[Me.b.PositionKind,Me.b.NormalKind],o=t.getMesh(),a=t.getMaterial();a&&(a.needAlphaTesting()&&(n.push("#define ALPHATEST"),o.isVerticesDataPresent(Me.b.UVKind)&&(i.push(Me.b.UVKind),n.push("#define UV1")),o.isVerticesDataPresent(Me.b.UV2Kind)&&(i.push(Me.b.UV2Kind),n.push("#define UV2"))),a.useLogarithmicDepth&&n.push("#define LOGARITHMICDEPTH")),o.useBones&&o.computeBonesUsingShaders?(i.push(Me.b.MatricesIndicesKind),i.push(Me.b.MatricesWeightsKind),o.numBoneInfluencers>4&&(i.push(Me.b.MatricesIndicesExtraKind),i.push(Me.b.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),n.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");var s=o.morphTargetManager,d=0;s&&s.numInfluencers>0&&(d=s.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),tt.a.PrepareAttributesForMorphTargetsInfluencers(i,o,d)),e&&(n.push("#define INSTANCES"),tt.a.PushAttributesForInstances(i),t.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));var p=n.join(` -`);return this._cachedDefines!==p&&(this._cachedDefines=p,this._effect=this.scene.getEngine().createEffect("outline",i,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences"],["diffuseSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d})),this._effect.isReady()},r.prototype._beforeRenderingMesh=function(t,e,n){if(this._savedDepthWrite=this._engine.getDepthWrite(),t.renderOutline){var i=e.getMaterial();i&&i.needAlphaBlendingForMesh(t)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(h.a.REPLACE),this._engine.setStencilFunction(h.a.ALWAYS),this._engine.setStencilMask(r._StencilReference),this._engine.setStencilFunctionReference(r._StencilReference),this.render(e,n,!0),this._engine.setColorWrite(!0),this._engine.setStencilFunction(h.a.NOTEQUAL)),this._engine.setDepthWrite(!1),this.render(e,n),this._engine.setDepthWrite(this._savedDepthWrite),i&&i.needAlphaBlendingForMesh(t)&&this._engine.restoreStencilState()}},r.prototype._afterRenderingMesh=function(t,e,n){if(t.renderOverlay){var i=this._engine.getAlphaMode(),o=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(h.a.ALPHA_COMBINE),this.render(e,n,!0),this._engine.setAlphaMode(i),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=o}t.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(e,n),this._engine.setColorWrite(!0))},r._StencilReference=4,r}(),hv=f(148),lf=function(r){function t(e,n){var i=r.call(this)||this;return i.name=e,i.animations=new Array,i.isPickable=!1,i.useAlphaForPicking=!1,i.onDisposeObservable=new x.c,i._onAnimationEnd=null,i._endAnimation=function(){i._onAnimationEnd&&i._onAnimationEnd(),i.disposeWhenFinishedAnimating&&i.dispose()},i.color=new M.b(1,1,1,1),i.position=u.e.Zero(),i._manager=n,i._manager.sprites.push(i),i.uniqueId=i._manager.scene.getUniqueId(),i}return Object(c.d)(t,r),Object.defineProperty(t.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"manager",{get:function(){return this._manager},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"Sprite"},Object.defineProperty(t.prototype,"fromIndex",{get:function(){return this._fromIndex},set:function(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toIndex",{get:function(){return this._toIndex},set:function(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loopAnimation",{get:function(){return this._loopAnimation},set:function(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"delay",{get:function(){return Math.max(this._delay,1)},set:function(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)},enumerable:!1,configurable:!0}),t.prototype.playAnimation=function(e,n,i,o,a){a===void 0&&(a=null),this._onAnimationEnd=a,r.prototype.playAnimation.call(this,e,n,i,o,this._endAnimation)},t.prototype.dispose=function(){for(var e=0;ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))},r}());_e.a.prototype._internalPickSprites=function(r,t,e,n){if(!tr.a)return null;var i=null;if(!n){if(!this.activeCamera)return null;n=this.activeCamera}if(this.spriteManagers.length>0)for(var o=0;o=i.distance))&&(i=s,e))break}}return i||new tr.a},_e.a.prototype._internalMultiPickSprites=function(r,t,e){if(!tr.a)return null;var n=new Array;if(!e){if(!this.activeCamera)return null;e=this.activeCamera}if(this.spriteManagers.length>0)for(var i=0;i0&&(n=o.pickSprite(t,e,this._spritePredicate,!1,o.cameraToUseForPointers||void 0))&&n.hit&&n.pickedSprite&&n.pickedSprite.actionManager){switch(o._pickedDownSprite=n.pickedSprite,i.button){case 0:n.pickedSprite.actionManager.processTrigger(h.a.ACTION_OnLeftPickTrigger,m.a.CreateNewFromSprite(n.pickedSprite,o,i));break;case 1:n.pickedSprite.actionManager.processTrigger(h.a.ACTION_OnCenterPickTrigger,m.a.CreateNewFromSprite(n.pickedSprite,o,i));break;case 2:n.pickedSprite.actionManager.processTrigger(h.a.ACTION_OnRightPickTrigger,m.a.CreateNewFromSprite(n.pickedSprite,o,i))}n.pickedSprite.actionManager&&n.pickedSprite.actionManager.processTrigger(h.a.ACTION_OnPickDownTrigger,m.a.CreateNewFromSprite(n.pickedSprite,o,i))}return n},r.prototype._pointerUp=function(t,e,n,i){var o=this.scene;if(o.spriteManagers.length>0){var a=o.pickSprite(t,e,this._spritePredicate,!1,o.cameraToUseForPointers||void 0);a&&(a.hit&&a.pickedSprite&&a.pickedSprite.actionManager&&(a.pickedSprite.actionManager.processTrigger(h.a.ACTION_OnPickUpTrigger,m.a.CreateNewFromSprite(a.pickedSprite,o,i)),a.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||a.pickedSprite.actionManager.processTrigger(h.a.ACTION_OnPickTrigger,m.a.CreateNewFromSprite(a.pickedSprite,o,i)))),o._pickedDownSprite&&o._pickedDownSprite.actionManager&&o._pickedDownSprite!==a.pickedSprite&&o._pickedDownSprite.actionManager.processTrigger(h.a.ACTION_OnPickOutTrigger,m.a.CreateNewFromSprite(o._pickedDownSprite,o,i)))}return n},r}();je.a.IncludesShadersStore.imageProcessingCompatibility=`#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); -#endif`;var dv=`uniform bool alphaTest; -varying vec4 vColor; - -varying vec2 vUV; -uniform sampler2D diffuseSampler; - -#include -void main(void) { -vec4 color=texture2D(diffuseSampler,vUV); -if (alphaTest) -{ -if (color.a<0.95) -discard; -} -color*=vColor; -#include -gl_FragColor=color; -#include -}`;je.a.ShadersStore.spritesPixelShader=dv;var fv=` -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 -void main(void) { -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 -}`;je.a.ShadersStore.spritesVertexShader=fv;var pv=function(){function r(t,e,n,i){if(n===void 0&&(n=.01),i===void 0&&(i=null),this.blendMode=h.a.ALPHA_COMBINE,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=e,this._epsilon=n,this._engine=t,this._useInstancing=t.getCaps().instancedArrays,this._useVAO=t.getCaps().vertexArrayObject&&!t.disableVertexArrayObjects,this._scene=i,!this._useInstancing){for(var o=[],a=0,s=0;s>0;e._xOffset=(e.cellIndex-y*p)*this.cellWidth/o.width,e._yOffset=y*this.cellHeight/o.height,e._xSize=this.cellWidth,e._ySize=this.cellHeight}this._vertexData[d]=e.position.x,this._vertexData[d+1]=e.position.y,this._vertexData[d+2]=e.position.z,this._vertexData[d+3]=e.angle,this._vertexData[d+4]=e.width,this._vertexData[d+5]=e.height,this._useInstancing?d-=2:(this._vertexData[d+6]=n,this._vertexData[d+7]=i),this._vertexData[d+8]=a?e.invertU?0:1:e.invertU?1:0,this._vertexData[d+9]=e.invertV?1:0,this._vertexData[d+10]=e._xOffset,this._vertexData[d+11]=e._yOffset,this._vertexData[d+12]=e._xSize/o.width,this._vertexData[d+13]=e._ySize/o.height,this._vertexData[d+14]=e.color.r,this._vertexData[d+15]=e.color.g,this._vertexData[d+16]=e.color.b,this._vertexData[d+17]=e.color.a},r.prototype.dispose=function(){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)},r}(),hf=function(){function r(t,e,n,i,o,a,s,d,p){var y=this;a===void 0&&(a=.01),s===void 0&&(s=we.a.TRILINEAR_SAMPLINGMODE),d===void 0&&(d=!1),p===void 0&&(p=null),this.name=t,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.onDisposeObservable=new x.c,this.disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=function(O,U){O.cellRef||(O.cellIndex=0);var F=O.cellIndex;typeof F=="number"&&isFinite(F)&&Math.floor(F)===F&&(O.cellRef=y._spriteMap[O.cellIndex]),O._xOffset=y._cellData[O.cellRef].frame.x/U.width,O._yOffset=y._cellData[O.cellRef].frame.y/U.height,O._xSize=y._cellData[O.cellRef].frame.w,O._ySize=y._cellData[O.cellRef].frame.h},o||(o=Ue.a.LastCreatedScene),o._getComponent(st.a.NAME_SPRITE)||o._addComponent(new uf(o)),this._fromPacked=d,this._scene=o;var P=this._scene.getEngine();if(this._spriteRenderer=new pv(P,n,a,o),i.width&&i.height)this.cellWidth=i.width,this.cellHeight=i.height;else{if(i===void 0)return void(this._spriteRenderer=null);this.cellWidth=i,this.cellHeight=i}this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),e&&(this.texture=new we.a(e,o,!0,!1,s)),this._fromPacked&&this._makePacked(e,p)}return Object.defineProperty(r.prototype,"onDispose",{set:function(t){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(t)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"children",{get:function(){return this.sprites},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"capacity",{get:function(){return this._spriteRenderer.capacity},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"texture",{get:function(){return this._spriteRenderer.texture},set:function(t){t.wrapU=we.a.CLAMP_ADDRESSMODE,t.wrapV=we.a.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=t,this._textureContent=null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"cellWidth",{get:function(){return this._spriteRenderer.cellWidth},set:function(t){this._spriteRenderer.cellWidth=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"cellHeight",{get:function(){return this._spriteRenderer.cellHeight},set:function(t){this._spriteRenderer.cellHeight=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"fogEnabled",{get:function(){return this._spriteRenderer.fogEnabled},set:function(t){this._spriteRenderer.fogEnabled=t},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"blendMode",{get:function(){return this._spriteRenderer.blendMode},set:function(t){this._spriteRenderer.blendMode=t},enumerable:!1,configurable:!0}),r.prototype.getClassName=function(){return"SpriteManager"},r.prototype._makePacked=function(t,e){var n=this;if(e!==null)try{var i=void 0;if((i=typeof e=="string"?JSON.parse(e):e).frames.length){for(var o={},a=0;a0);var P=t.substring(0,y-1)+".json",O=new XMLHttpRequest;O.open("GET",P,!0),O.onerror=function(){l.a.Error("JSON ERROR: Unable to load JSON file."),n._fromPacked=!1,n._packedAndReady=!1},O.onload=function(){try{var U=JSON.parse(O.response),F=Reflect.ownKeys(U.frames);n._spriteMap=F,n._packedAndReady=!0,n._cellData=U.frames}catch{throw n._fromPacked=!1,n._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}},O.send()}},r.prototype._checkTextureAlpha=function(t,e,n,i,o){if(!t.useAlphaForPicking||!this.texture)return!0;var a=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(a.width*a.height*4),this.texture.readPixels(0,0,this._textureContent));var s=u.c.Vector3[0];s.copyFrom(e.direction),s.normalize(),s.scaleInPlace(n),s.addInPlace(e.origin);var d=(s.x-i.x)/(o.x-i.x)-.5,p=1-(s.y-i.y)/(o.y-i.y)-.5,y=t.angle,P=d*Math.cos(y)-p*Math.sin(y)+.5,O=d*Math.sin(y)+p*Math.cos(y)+.5,U=t._xOffset*a.width+P*t._xSize|0,F=t._yOffset*a.height+O*t._ySize|0;return this._textureContent[4*(U+F*a.width)+3]>.5},r.prototype.intersects=function(t,e,n,i){for(var o=Math.min(this.capacity,this.sprites.length),a=u.e.Zero(),s=u.e.Zero(),d=Number.MAX_VALUE,p=null,y=u.c.Vector3[0],P=u.c.Vector3[1],O=e.getViewMatrix(),U=0;Uz){if(!this._checkTextureAlpha(F,t,z,a,s))continue;if(d=z,p=F,i)break}}}}if(p){var J=new tr.a;O.invertToRef(u.c.Matrix[0]),J.hit=!0,J.pickedSprite=p,J.distance=d;var ie=u.c.Vector3[2];return ie.copyFrom(t.direction),ie.normalize(),ie.scaleInPlace(d),t.origin.addToRef(ie,y),J.pickedPoint=u.e.TransformCoordinates(y,u.c.Matrix[0]),J}return null},r.prototype.multiIntersects=function(t,e,n){for(var i,o=Math.min(this.capacity,this.sprites.length),a=u.e.Zero(),s=u.e.Zero(),d=[],p=u.c.Vector3[0].copyFromFloats(0,0,0),y=u.c.Vector3[1].copyFromFloats(0,0,0),P=e.getViewMatrix(),O=0;O0.) { -mt=mod(time*animationData.z,1.0); -for(float f=0.; fmt){ -frameID=animationData.x; -break; -} -animationData=texture2D(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.); -} -} - -mat4 frameData=getFrameData(frameID+0.5); -vec2 frameSize=(frameData[0].wz)/spriteMapSize; -vec2 offset=frameData[0].xy*sheetUnits; -vec2 ratio=frameData[2].xy/frameData[0].wz; - -if (frameData[2].z == 1.){ -tileUV.xy=tileUV.yx; -} -if (i == 0){ -color=texture2D(spriteSheet,tileUV*frameSize+offset); -} else { -vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset); -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; -}`;je.a.ShadersStore.spriteMapPixelShader=_v;var mv=`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; -}`;je.a.ShadersStore.spriteMapVertexShader=mv;var di,gv=function(){function r(t,e,n,i,o){var a=this;this.name=t,this.sprites=[],this.atlasJSON=e,this.sprites=this.atlasJSON.frames,this.spriteSheet=n,this.options=i,i.stageSize=i.stageSize||new u.d(1,1),i.outputSize=i.outputSize||i.stageSize,i.outputPosition=i.outputPosition||u.e.Zero(),i.outputRotation=i.outputRotation||u.e.Zero(),i.layerCount=i.layerCount||1,i.maxAnimationFrames=i.maxAnimationFrames||0,i.baseTile=i.baseTile||0,i.flipU=i.flipU||!1,i.colorMultiply=i.colorMultiply||new u.e(1,1,1),this._scene=o,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(var s=0;s0&&(t+=` -\r`),t+=this._tileMaps[e]._texture._bufferView.toString();var n=document.createElement("a");n.href="data:octet/stream;charset=utf-8,"+encodeURI(t),n.target="_blank",n.download=this.name+".tilemaps",n.click(),n.remove()},r.prototype.loadTileMaps=function(t){var e=this,n=new XMLHttpRequest;n.open("GET",t);var i=this.options.layerCount||0;n.onload=function(){for(var o=n.response.split(` -\r`),a=0;a-1&&this._tasks.splice(e,1)},r.prototype._decreaseWaitingTasksCount=function(t){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,t),this.onProgressObservable.notifyObservers(new df(this._waitingTasksCount,this._totalTasksCount,t))}catch(a){l.a.Error("Error running progress callbacks."),console.log(a)}if(this._waitingTasksCount===0){try{var e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(var n=0,i=e;n-1&&this._tasks.splice(o,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(a){l.a.Error("Error running tasks-done callbacks."),console.log(a)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}},r.prototype._runTask=function(t){var e=this,n=function(i,o){t._setErrorObject(i,o),e.onTaskError&&e.onTaskError(t),e.onTaskErrorObservable.notifyObservers(t),e._decreaseWaitingTasksCount(t)};t.run(this._scene,function(){try{e.onTaskSuccess&&e.onTaskSuccess(t),e.onTaskSuccessObservable.notifyObservers(t),e._decreaseWaitingTasksCount(t)}catch(i){n("Error executing task success callbacks",i)}},n)},r.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},r.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,this._waitingTasksCount===0)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var t=0;t=0&&this._meshes.splice(n,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(var i=0;i0&&this._textureLoadingCallback(t)}this._currentScene.render()}},r.prototype.drag=function(t){t.stopPropagation(),t.preventDefault()},r.prototype.drop=function(t){t.stopPropagation(),t.preventDefault(),this.loadFiles(t)},r.prototype._traverseFolder=function(t,e,n,i){var o=this,a=t.createReader(),s=t.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");a.readEntries(function(d){n.count+=d.length;for(var p=0,y=d;p0)){for(var n=new Array,i=[],o=t.dataTransfer?t.dataTransfer.items:null,a=0;a0&&l.a.ClearLogCache(),this._engine.stopRenderLoop()),Ut.ShowLoadingScreen=!1,this._engine.displayLoadingUI(),Ut.LoadAsync("file:",this._sceneFileToLoad,this._engine,function(e){t._progressCallback&&t._progressCallback(e)}).then(function(e){t._currentScene&&t._currentScene.dispose(),t._currentScene=e,t._sceneLoadedCallback&&t._sceneLoadedCallback(t._sceneFileToLoad,t._currentScene),t._currentScene.executeWhenReady(function(){t._engine.hideLoadingUI(),t._engine.runRenderLoop(function(){t.renderFunction()})})}).catch(function(e){t._engine.hideLoadingUI(),t._errorCallback&&t._errorCallback(t._sceneFileToLoad,t._currentScene,e.message)})):l.a.Error("Please provide a valid .babylon file.")},r}(),Ef=f(146),xv=f(145),pi=function(){function r(t){t===void 0&&(t=0),this.priority=t}return r.prototype.getDescription=function(){return""},r.prototype.apply=function(t,e){return!0},r}(),Ra=function(r){function t(e,n,i){e===void 0&&(e=0),n===void 0&&(n=1024),i===void 0&&(i=.5);var o=r.call(this,e)||this;return o.priority=e,o.maximumSize=n,o.step=i,o}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Reducing render target texture size to "+this.maximumSize},t.prototype.apply=function(e,n){for(var i=!0,o=0;othis.maximumSize&&(a.scale(this.step),i=!1)}}return i},t}(pi),Jc=function(r){function t(e,n,i){e===void 0&&(e=0),n===void 0&&(n=2),i===void 0&&(i=.25);var o=r.call(this,e)||this;return o.priority=e,o.maximumScale=n,o.step=i,o._currentScale=-1,o._directionOffset=1,o}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,n){return this._currentScale===-1&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),this._directionOffset===1?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t}(pi),Oa=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,n){return e.shadowsEnabled=n.isInImprovementMode,!0},t}(pi),Ma=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,n){return e.postProcessesEnabled=n.isInImprovementMode,!0},t}(pi),Ia=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,n){return e.lensFlaresEnabled=n.isInImprovementMode,!0},t}(pi),Sf=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,n){return!this.onApply||this.onApply(e,n)},t}(pi),Da=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,n){return e.particlesEnabled=n.isInImprovementMode,!0},t}(pi),$c=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t.prototype.getDescription=function(){return"Turning render targets off"},t.prototype.apply=function(e,n){return e.renderTargetsEnabled=n.isInImprovementMode,!0},t}(pi),La=function(r){function t(){var e=r!==null&&r.apply(this,arguments)||this;return e._canBeMerged=function(n){if(!(n instanceof De.a))return!1;var i=n;return!i.isDisposed()&&!(!i.isVisible||!i.isEnabled())&&!(i.instances.length>0)&&!i.skeleton&&!i.hasLODLevels},e}return Object(c.d)(t,r),Object.defineProperty(t,"UpdateSelectionTree",{get:function(){return t._UpdateSelectionTree},set:function(e){t._UpdateSelectionTree=e},enumerable:!1,configurable:!0}),t.prototype.getDescription=function(){return"Merging similar meshes together"},t.prototype.apply=function(e,n,i){for(var o=e.meshes.slice(0),a=o.length,s=0;s=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var i=!0,o=!0,a=0;a0){o.animationGroups=[];for(var P=0;P0)for(o.reflectionProbes=[],e=0;e0&&setTimeout(function(){n.stopRecording()},1e3*e),this._fileName=t,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(function(i,o){n._resolve=i,n._reject=o})},r.prototype.dispose=function(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null},r.prototype._handleDataAvailable=function(t){t.data.size>0&&this._recordedChunks.push(t.data)},r.prototype._handleError=function(t){if(this.stopRecording(),!this._reject)throw new t.error;this._reject(t.error)},r.prototype._handleStop=function(){this.stopRecording();var t=new Blob(this._recordedChunks);this._resolve&&this._resolve(t),window.URL.createObjectURL(t),this._fileName&&Ye.b.Download(t,this._fileName)},r._defaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3},r}(),Oo=function(){function r(){}return r.CreateScreenshot=function(t,e,n,i,o){o===void 0&&(o="image/png");var a=r._getScreenshotSize(t,e,n),s=a.height,d=a.width;if(s&&d){Ye.b._ScreenshotCanvas||(Ye.b._ScreenshotCanvas=document.createElement("canvas")),Ye.b._ScreenshotCanvas.width=d,Ye.b._ScreenshotCanvas.height=s;var p=Ye.b._ScreenshotCanvas.getContext("2d"),y=t.getRenderWidth()/t.getRenderHeight(),P=d,O=P/y;O>s&&(P=(O=s)*y);var U=Math.max(0,d-P)/2,F=Math.max(0,s-O)/2,z=t.getRenderingCanvas();p&&z&&p.drawImage(z,U,F,P,O),Ye.b.EncodeScreenshotCanvasData(i,o)}else l.a.Error("Invalid 'size' parameter !")},r.CreateScreenshotAsync=function(t,e,n,i){return i===void 0&&(i="image/png"),new Promise(function(o,a){r.CreateScreenshot(t,e,n,function(s){s!==void 0?o(s):a(new Error("Data is undefined"))},i)})},r.CreateScreenshotUsingRenderTarget=function(t,e,n,i,o,a,s,d,p,y){o===void 0&&(o="image/png"),a===void 0&&(a=1),s===void 0&&(s=!1),p===void 0&&(p=!1),y===void 0&&(y=!1);var P=r._getScreenshotSize(t,e,n),O=P.height,U=P.width,F={width:U,height:O};if(O&&U){var z=t.getRenderingCanvas();if(z){var J={width:z.width,height:z.height};t.setSize(U,O);var ie=e.getScene(),se=null,ce=ie.activeCameras;(ie.activeCamera!==e||ie.activeCameras&&ie.activeCameras.length)&&(se=ie.activeCamera,ie.activeCamera=e),ie.render();var ue=new sn("screenShot",F,ie,!1,!1,h.a.TEXTURETYPE_UNSIGNED_INT,!1,we.a.NEAREST_SAMPLINGMODE,void 0,y);ue.renderList=null,ue.samples=a,ue.renderSprites=p,ue.onAfterRenderObservable.add(function(){Ye.b.DumpFramebuffer(U,O,t,i,o,d)});var fe=function(){ie.incrementRenderId(),ie.resetCachedMaterial(),ue.render(!0),ue.dispose(),se&&(ie.activeCamera=se),ie.activeCameras=ce,t.setSize(J.width,J.height),e.getProjectionMatrix(!0)};if(s){var ve=new Ro("antialiasing",1,ie.activeCamera);ue.addPostProcess(ve),ve.getEffect().isReady()?fe():ve.getEffect().onCompiled=function(){fe()}}else fe()}else l.a.Error("No rendering canvas found !")}else l.a.Error("Invalid 'size' parameter !")},r.CreateScreenshotUsingRenderTargetAsync=function(t,e,n,i,o,a,s,d){return i===void 0&&(i="image/png"),o===void 0&&(o=1),a===void 0&&(a=!1),d===void 0&&(d=!1),new Promise(function(p,y){r.CreateScreenshotUsingRenderTarget(t,e,n,function(P){P!==void 0?p(P):y(new Error("Data is undefined"))},i,o,a,s,d)})},r._getScreenshotSize=function(t,e,n){var i=0,o=0;if(typeof n=="object"){var a=n.precision?Math.abs(n.precision):1;n.width&&n.height?(i=n.height*a,o=n.width*a):n.width&&!n.height?(o=n.width*a,i=Math.round(o/t.getAspectRatio(e))):n.height&&!n.width?(i=n.height*a,o=Math.round(i*t.getAspectRatio(e))):(o=Math.round(t.getRenderWidth()*a),i=Math.round(o/t.getAspectRatio(e)))}else isNaN(n)||(i=n,o=n);return o&&(o=Math.floor(o)),i&&(i=Math.floor(i)),{height:0|i,width:0|o}},r}();Ye.b.CreateScreenshot=Oo.CreateScreenshot,Ye.b.CreateScreenshotAsync=Oo.CreateScreenshotAsync,Ye.b.CreateScreenshotUsingRenderTarget=Oo.CreateScreenshotUsingRenderTarget,Ye.b.CreateScreenshotUsingRenderTargetAsync=Oo.CreateScreenshotUsingRenderTargetAsync,function(r){r[r.Checkbox=0]="Checkbox",r[r.Slider=1]="Slider",r[r.Vector3=2]="Vector3",r[r.Quaternion=3]="Quaternion",r[r.Color3=4]="Color3",r[r.String=5]="String"}(Zc||(Zc={}));var Vr,Dv=f(140),Lv=function(){function r(t){this.byteOffset=0,this.buffer=t}return r.prototype.loadAsync=function(t){var e=this;return this.buffer.readAsync(this.byteOffset,t).then(function(n){e._dataView=new DataView(n.buffer,n.byteOffset,n.byteLength),e._dataByteOffset=0})},r.prototype.readUint32=function(){var t=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,t},r.prototype.readUint8Array=function(t){var e=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,t);return this._dataByteOffset+=t,this.byteOffset+=t,e},r.prototype.readString=function(t){return Xn.a.Decode(this.readUint8Array(t))},r.prototype.skipBytes=function(t){this._dataByteOffset+=t,this.byteOffset+=t},r}(),Nv=function(){function r(){}return r._GetStorage=function(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{var t={};return{getItem:function(n){var i=t[n];return i===void 0?null:i},setItem:function(n,i){t[n]=i}}}},r.ReadString=function(t,e){var n=this._Storage.getItem(t);return n!==null?n:e},r.WriteString=function(t,e){this._Storage.setItem(t,e)},r.ReadBoolean=function(t,e){var n=this._Storage.getItem(t);return n!==null?n==="true":e},r.WriteBoolean=function(t,e){this._Storage.setItem(t,e?"true":"false")},r.ReadNumber=function(t,e){var n=this._Storage.getItem(t);return n!==null?parseFloat(n):e},r.WriteNumber=function(t,e){this._Storage.setItem(t,e.toString())},r._Storage=r._GetStorage(),r}(),wv=function(){function r(){this._trackedScene=null}return r.prototype.track=function(t){this._trackedScene=t,this._savedJSON=nl.Serialize(t)},r.prototype.getDelta=function(){if(!this._trackedScene)return null;var t=nl.Serialize(this._trackedScene),e={};for(var n in t)this._compareCollections(n,this._savedJSON[n],t[n],e);return e},r.prototype._compareArray=function(t,e,n,i){if(e.length===0&&n.length===0)return!0;if(e.length&&!isNaN(e[0])||n.length&&!isNaN(n[0])){if(e.length!==n.length)return!1;if(e.length===0)return!0;for(var o=0;on.MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+n.MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=o,this._characters=i.map(function(s){return a._alphabet.getCharacterIdx(s)})}return n.prototype.serialize=function(){return JSON.stringify(this._characters)},n.Deserialize=function(i,o){var a=new n([],o);return a._characters=JSON.parse(i),a},n.prototype.distance=function(i){return n._distance(this,i)},n._distance=function(i,o){var a=i._alphabet;if(a!==o._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");var s=i._characters,d=o._characters,p=s.length,y=d.length,P=n._costMatrix;P[0][0]=0;for(var O=0;O.98)&&(u.e.CrossToRef(r._forwardDir,r._inverseFromVec,r._upDir),r._upDir.normalize(),u.a.LookAtLHToRef(t,e,r._upDir,r._lookMatrix),n.subtractToRef(e,r._fromToVec),r._fromToVec.normalize(),u.e.TransformNormalToRef(r._fromToVec,r._lookMatrix,i),!0)},r._tokenizeSegment=function(t,e){r._bestMatch=0,r._score=u.e.Dot(t,e[0]),r._bestScore=r._score;for(var n=1;nr._bestScore&&(r._bestMatch=n,r._bestScore=r._score);return r._bestMatch},r._forwardDir=new u.e,r._inverseFromVec=new u.e,r._upDir=new u.e,r._fromToVec=new u.e,r._lookMatrix=new u.a,r}(),Pf=function(){function r(t){this.chars=new Array(t)}return r.Generate=function(t,e,n,i,o){t===void 0&&(t=64),e===void 0&&(e=256),n===void 0&&(n=.1),i===void 0&&(i=.001),o===void 0&&(o=[]);for(var a,s,d=new r(t),p=0;p1e-6&&O.scaleAndAddToRef(1/(O.lengthSquared()*s),P)}),P.scaleInPlace(a),d.chars[z].addInPlace(P),d.chars[z].normalize()};for(p=o.length;p4;o=Math.floor(o/2))i.push(t.resampleAtTargetResolution(o).tokenize(e.chars));return i},r.prototype.distance=function(t){for(var e=0,n=0;n0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,r.MIN_AVERAGE_DISTANCE))},r.MIN_AVERAGE_DISTANCE=1,r}(),Bv=function(){function r(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}return r.prototype.serialize=function(){var t={};return t.maximumAllowableMatchCost=this._maximumAllowableMatchCost,t.vector3Alphabet=this._vector3Alphabet.serialize(),t.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),t.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(function(e,n){t.nameToDescribedTrajectory.push(n),t.nameToDescribedTrajectory.push(e.serialize())}),JSON.stringify(t)},r.Deserialize=function(t){var e=JSON.parse(t),n=new r;n._maximumAllowableMatchCost=e.maximumAllowableMatchCost,n._vector3Alphabet=Pf.Deserialize(e.vector3Alphabet),n._levenshteinAlphabet=Vr.Alphabet.Deserialize(e.levenshteinAlphabet);for(var i=0;i0&&this.onFeaturePointsAddedObservable.notifyObservers(a),o.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(o)}}},t.prototype._init=function(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)},t.Name=ii.FEATURE_POINTS,t.Version=1,t}(ri);Yn.AddWebXRFeature(Ga.Name,function(r){return function(){return new Ga(r)}},Ga.Version);var xf=function(){function r(t,e,n,i,o){this.xrController=t,this.trackedMeshes=e,this._handMesh=n,this._rigMapping=i,this._defaultHandMesh=!1,this._transformNodeMapping=[],this.handPartsDefinition=this.generateHandPartsDefinition(t.inputSource.hand),this._scene=e[0].getScene(),this._handMesh&&this._rigMapping?this._defaultHandMesh=!1:o||this._generateDefaultHandMesh(),this.xrController.motionController&&(this.xrController.motionController.rootMesh?this.xrController.motionController.rootMesh.setEnabled(!1):this.xrController.motionController.onModelLoadedObservable.add(function(a){a.rootMesh&&a.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(function(a){a.onModelLoadedObservable.add(function(s){s.rootMesh&&s.rootMesh.setEnabled(!1)}),a.rootMesh&&a.rootMesh.setEnabled(!1)})}return r.prototype.generateHandPartsDefinition=function(t){var e;return(e={}).wrist=[t.WRIST],e.thumb=[t.THUMB_METACARPAL,t.THUMB_PHALANX_PROXIMAL,t.THUMB_PHALANX_DISTAL,t.THUMB_PHALANX_TIP],e.index=[t.INDEX_METACARPAL,t.INDEX_PHALANX_PROXIMAL,t.INDEX_PHALANX_INTERMEDIATE,t.INDEX_PHALANX_DISTAL,t.INDEX_PHALANX_TIP],e.middle=[t.MIDDLE_METACARPAL,t.MIDDLE_PHALANX_PROXIMAL,t.MIDDLE_PHALANX_INTERMEDIATE,t.MIDDLE_PHALANX_DISTAL,t.MIDDLE_PHALANX_TIP],e.ring=[t.RING_METACARPAL,t.RING_PHALANX_PROXIMAL,t.RING_PHALANX_INTERMEDIATE,t.RING_PHALANX_DISTAL,t.RING_PHALANX_TIP],e.little=[t.LITTLE_METACARPAL,t.LITTLE_PHALANX_PROXIMAL,t.LITTLE_PHALANX_INTERMEDIATE,t.LITTLE_PHALANX_DISTAL,t.LITTLE_PHALANX_TIP],e},r.prototype.updateFromXRFrame=function(t,e,n){var i=this;n===void 0&&(n=2);var o=this.xrController.inputSource.hand;o&&this.trackedMeshes.forEach(function(a,s){var d=o[s];if(d){var p=t.getJointPose(d,e);if(!p||!p.transform)return;var y=p.transform.position,P=p.transform.orientation;a.position.set(y.x,y.y,y.z),a.rotationQuaternion.set(P.x,P.y,P.z,P.w);var O=(p.radius||.008)*n;a.scaling.set(O,O,O),i._handMesh&&i._rigMapping&&i._rigMapping[s]&&(i._transformNodeMapping[s]=i._transformNodeMapping[s]||i._scene.getTransformNodeByName(i._rigMapping[s]),i._transformNodeMapping[s]&&(i._transformNodeMapping[s].position.copyFrom(a.position),i._transformNodeMapping[s].rotationQuaternion.copyFrom(a.rotationQuaternion),a.isVisible=!1)),a.getScene().useRightHandedSystem||(a.position.z*=-1,a.rotationQuaternion.z*=-1,a.rotationQuaternion.w*=-1)}})},r.prototype.getHandPartMeshes=function(t){var e=this;return this.handPartsDefinition[t].map(function(n){return e.trackedMeshes[n]})},r.prototype.dispose=function(){this.trackedMeshes.forEach(function(t){return t.dispose()}),this._defaultHandMesh&&this._handMesh&&this._handMesh.dispose()},r.prototype._generateDefaultHandMesh=function(){return Object(c.b)(this,void 0,void 0,function(){var t,e,n,i,o,a,s,d;return Object(c.e)(this,function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),t=this.xrController.inputSource.handedness==="right"?"right":"left",e=(t==="right"?"r":"l")+"_hand_"+(this._scene.useRightHandedSystem?"r":"l")+"hs.glb",[4,Ut.ImportMeshAsync("","https://assets.babylonjs.com/meshes/HandMeshes/",e,this._scene)];case 1:return n=p.sent(),i={base:M.a.FromInts(116,63,203),fresnel:M.a.FromInts(149,102,229),fingerColor:M.a.FromInts(177,130,255),tipFresnel:M.a.FromInts(220,200,255)},[4,(o=new ya("leftHandShader",this._scene,{emitComments:!1})).loadAsync("https://patrickryanms.github.io/BabylonJStextures/Demos/xrHandMesh/handsShader.json")];case 2:if(p.sent(),o.build(!1),o.needDepthPrePass=!0,o.transparencyMode=Ht.a.MATERIAL_ALPHABLEND,o.alphaMode=Ue.a.ALPHA_COMBINE,(a={base:o.getBlockByName("baseColor"),fresnel:o.getBlockByName("fresnelColor"),fingerColor:o.getBlockByName("fingerColor"),tipFresnel:o.getBlockByName("tipFresnelColor")}).base.value=i.base,a.fresnel.value=i.fresnel,a.fingerColor.value=i.fingerColor,a.tipFresnel.value=i.tipFresnel,n.meshes[1].material=o,this._defaultHandMesh=!0,this._handMesh=n.meshes[0],this._rigMapping=["wrist_","thumb_metacarpal_","thumb_proxPhalanx_","thumb_distPhalanx_","thumb_tip_","index_metacarpal_","index_proxPhalanx_","index_intPhalanx_","index_distPhalanx_","index_tip_","middle_metacarpal_","middle_proxPhalanx_","middle_intPhalanx_","middle_distPhalanx_","middle_tip_","ring_metacarpal_","ring_proxPhalanx_","ring_intPhalanx_","ring_distPhalanx_","ring_tip_","little_metacarpal_","little_proxPhalanx_","little_intPhalanx_","little_distPhalanx_","little_tip_"].map(function(y){return y+(t==="right"?"R":"L")}),!(s=this._scene.getTransformNodeByName(this._rigMapping[0])))throw new Error("could not find the wrist node");return s.parent&&s.parent.rotate(ye.a.Y,Math.PI),[3,4];case 3:return d=p.sent(),Ye.b.Error("error loading hand mesh"),console.log(d),[3,4];case 4:return[2]}})})},r}(),za=function(r){function t(e,n){var i=r.call(this,e)||this;return i.options=n,i.onHandAddedObservable=new x.c,i.onHandRemovedObservable=new x.c,i._hands={},i._attachHand=function(o){var a,s,d,p,y,P,O,U,F,z;if(o.inputSource.hand&&!i._hands[o.uniqueId]){var J=o.inputSource.hand,ie=[],se=((a=i.options.jointMeshes)===null||a===void 0?void 0:a.sourceMesh)||Nn.a.CreateSphere("jointParent",{diameter:1});se.isVisible=!!(!((s=i.options.jointMeshes)===null||s===void 0)&&s.keepOriginalVisible);for(var ce=0;ce1){for(N();w!==-1&&b._OperatorPriority[V()]>=b._OperatorPriority[de];)D.push(W());I(de),j++}else ne+=te;j++}for(N();w!==-1;)V()==="("?W():D.push(W());return D},b._OperatorPriority={")":0,"(":1,"||":2,"&&":3},b._Stack=["","","","","","","","","","","","","","","","","","","",""],b}(),m=function(b){function T(D,w){w===void 0&&(w=!1);var N=b.call(this)||this;return N.define=D,N.not=w,N}return Object(u.d)(T,b),T.prototype.isTrue=function(D){var w=D[this.define]!==void 0;return this.not&&(w=!w),w},T}(C),c=function(b){function T(){return b!==null&&b.apply(this,arguments)||this}return Object(u.d)(T,b),T.prototype.isTrue=function(D){return this.leftOperand.isTrue(D)||this.rightOperand.isTrue(D)},T}(C),E=function(b){function T(){return b!==null&&b.apply(this,arguments)||this}return Object(u.d)(T,b),T.prototype.isTrue=function(D){return this.leftOperand.isTrue(D)&&this.rightOperand.isTrue(D)},T}(C),A=function(b){function T(D,w,N){var I=b.call(this)||this;return I.define=D,I.operand=w,I.testValue=N,I}return Object(u.d)(T,b),T.prototype.isTrue=function(D){var w=D[this.define];w===void 0&&(w=this.define);var N=!1,I=parseInt(w),V=parseInt(this.testValue);switch(this.operand){case">":N=I>V;break;case"<":N=I=":N=I>=V;break;case"==":N=I===V}return N},T}(C),S=f(21),g=/defined\s*?\((.+?)\)/g,l=/defined\s*?\[(.+?)\]/g,h=function(){function b(){}return b.Process=function(T,D,w,N){var I=this;this._ProcessIncludes(T,D,function(V){var W=I._ProcessShaderConversion(V,D,N);w(W)})},b._ProcessPrecision=function(T,D){var w=D.shouldUseHighPrecisionShader;return T.indexOf("precision highp float")===-1?T=w?`precision highp float; -`+T:`precision mediump float; -`+T:w||(T=T.replace("precision highp float","precision mediump float")),T},b._ExtractOperation=function(T){var D=/defined\((.+)\)/.exec(T);if(D&&D.length)return new m(D[1].trim(),T[0]==="!");for(var w="",N=0,I=0,V=["==",">=","<=","<",">"];I-1));I++);if(N===-1)return new m(T);var W=T.substring(0,N).trim(),j=T.substring(N+w.length).trim();return new A(W,w,j)},b._BuildSubExpression=function(T){T=T.replace(g,"defined[$1]");for(var D=[],w=0,N=C.infixToPostfix(T);w=2){var V=D[D.length-1],W=D[D.length-2];D.length-=2;var j=I=="&&"?new E:new c;typeof V=="string"&&(V=V.replace(l,"defined($1)")),typeof W=="string"&&(W=W.replace(l,"defined($1)")),j.leftOperand=typeof W=="string"?this._ExtractOperation(W):W,j.rightOperand=typeof V=="string"?this._ExtractOperation(V):V,D.push(j)}}var ne=D[D.length-1];return typeof ne=="string"&&(ne=ne.replace(l,"defined($1)")),typeof ne=="string"?this._ExtractOperation(ne):ne},b._BuildExpression=function(T,D){var w=new R,N=T.substring(0,D),I=T.substring(D);return I=I.substring(0,(I.indexOf("//")+1||I.length+1)-1).trim(),w.testExpression=N==="#ifdef"?new m(I):N==="#ifndef"?new m(I,!0):this._BuildSubExpression(I),w},b._MoveCursorWithinIf=function(T,D,w){for(var N=T.currentLine;this._MoveCursor(T,w);){var I=(N=T.currentLine).substring(0,5).toLowerCase();if(I==="#else"){var V=new _;return D.children.push(V),void this._MoveCursor(T,V)}if(I==="#elif"){var W=this._BuildExpression(N,5);D.children.push(W),w=W}}},b._MoveCursor=function(T,D){for(;T.canRead;){T.lineIndex++;var w=T.currentLine,N=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(w);if(N&&N.length)switch(N[0]){case"#ifdef":var I=new M;D.children.push(I);var V=this._BuildExpression(w,6);I.children.push(V),this._MoveCursorWithinIf(T,I,V);break;case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":I=new M,D.children.push(I),V=this._BuildExpression(w,7),I.children.push(V),this._MoveCursorWithinIf(T,I,V);break;case"#if":I=new M,V=this._BuildExpression(w,3),D.children.push(I),I.children.push(V),this._MoveCursorWithinIf(T,I,V)}else{var W=new _;if(W.line=w,D.children.push(W),w[0]==="#"&&w[1]==="d"){var j=w.replace(";","").split(" ");W.additionalDefineKey=j[1],j.length===3&&(W.additionalDefineValue=j[2])}}}return!1},b._EvaluatePreProcessors=function(T,D,w){var N=new _,I=new x;return I.lineIndex=-1,I.lines=T.split(` -`),this._MoveCursor(I,N),N.process(D,w)},b._PreparePreProcessors=function(T){for(var D={},w=0,N=T.defines;w1?I[1]:""}return D.GL_ES="true",D.__VERSION__=T.version,D[T.platformName]="true",D},b._ProcessShaderConversion=function(T,D,w){var N=this._ProcessPrecision(T,D);if(!D.processor)return N;if(N.indexOf("#version 3")!==-1)return N.replace("#version 300 es","");var I=D.defines,V=this._PreparePreProcessors(D);return D.processor.preProcessor&&(N=D.processor.preProcessor(N,I,D.isFragment)),N=this._EvaluatePreProcessors(N,V,D),D.processor.postProcessor&&(N=D.processor.postProcessor(N,I,D.isFragment,w)),N},b._ProcessIncludes=function(T,D,w){for(var N=this,I=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,V=I.exec(T),W=new String(T),j=!1;V!=null;){var ne=V[1];if(ne.indexOf("__decl__")!==-1&&(ne=ne.replace(/__decl__/,""),D.supportsUniformBuffers&&(ne=(ne=ne.replace(/Vertex/,"Ubo")).replace(/Fragment/,"Ubo")),ne+="Declaration"),!D.includesShadersStore[ne]){var te=D.shadersRepository+"ShadersInclude/"+ne+".fx";return void b._FileToolsLoadFile(te,function(Y){D.includesShadersStore[ne]=Y,N._ProcessIncludes(W,D,w)})}var de=D.includesShadersStore[ne];if(V[2])for(var pe=V[3].split(","),ae=0;ae=0,V=I.exec(T)}j?this._ProcessIncludes(W.toString(),D,w):w(W)},b._FileToolsLoadFile=function(T,D,w,N,I,V){throw S.a.WarnImport("FileTools")},b}()},function(Ae,v,f){f(26).a.prototype._readTexturePixels=function(B,_,x,u,M,R){u===void 0&&(u=-1),M===void 0&&(M=0),R===void 0&&(R=null);var C=this._gl;if(!C)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){var m=C.createFramebuffer();if(!m)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=m}C.bindFramebuffer(C.FRAMEBUFFER,this._dummyFramebuffer),u>-1?C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_CUBE_MAP_POSITIVE_X+u,B._webGLTexture,M):C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_2D,B._webGLTexture,M);var c=B.type!==void 0?this._getWebGLTextureType(B.type):C.UNSIGNED_BYTE;switch(c){case C.UNSIGNED_BYTE:R||(R=new Uint8Array(4*_*x)),c=C.UNSIGNED_BYTE;break;default:R||(R=new Float32Array(4*_*x)),c=C.FLOAT}return C.readPixels(0,0,_,x,C.RGBA,c,R),C.bindFramebuffer(C.FRAMEBUFFER,this._currentFramebuffer),R}},function(Ae,v,f){var B="shadowsFragmentFunctions",_=`#ifdef SHADOWS -#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))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(texture2D(shadowSampler,uv)); -#else -float shadow=texture2D(shadowSampler,uv).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(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))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(texture2D(shadowSampler,uv)); -#else -float shadowMapSample=texture2D(shadowSampler,uv).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(texture2D(shadowSampler,uv)); -#else -float shadowMapSample=texture2D(shadowSampler,uv).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.); -return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff); -} -} -#ifdef WEBGL2 -#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(uvDepth.z,0.,GREATEST_LESS_THAN_ONE); -vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z); -float shadow=texture(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(uvDepth.z,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(uvDepth.z,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)); -float shadow=texture2D(shadowSampler,uvDepth); -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)); -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,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z)); -shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z)); -shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z)); -shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z)); -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)); -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,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z)); -shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z)); -shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z)); -shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z)); -shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z)); -shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z)); -shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z)); -shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z)); -shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z)); -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(uvDepth.z,0.,GREATEST_LESS_THAN_ONE); -vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z); -float blockerDepth=0.0; -float sumBlockerDepth=0.0; -float numBlocker=0.0; -for (int i=0; i1.0 || depthMetric<0.0) { -return 1.0; -} -else -{ -vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w; -vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5)); -float blockerDepth=0.0; -float sumBlockerDepth=0.0; -float numBlocker=0.0; -for (int i=0; icurrRayHeight) -{ -float delta1=currSampledHeight-currRayHeight; -float delta2=(currRayHeight+stepSize)-lastSampledHeight; -float ratio=delta1/(delta1+delta2); -vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset; - -break; -} -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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=`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) -mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV); -#else -mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vDetailUV,vec2(1.,1.)); -#endif -#elif defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#else -mat3 TBN=cotangent_frame(normalW,vPositionW,vMainUV1,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 -normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0); -normalW=normalize(mat3(normalMatrix)*normalW); -#elif !defined(DETAIL) -normalW=perturbNormal(TBN,vBumpUV+uvOffset); -#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`;f(5).a.IncludesShadersStore.bumpFragment=B},function(Ae,v,f){var B="lightFragment",_=`#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 HEMILIGHT{X} -info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); -#elif defined(SS_TRANSLUCENCY) -info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); -#else -info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); -#endif - -#ifdef SPECULARTERM -#ifdef ANISOTROPIC -info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#else -info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#endif - -#ifdef SHEEN -#ifdef SHEEN_LINKWITHALBEDO - -preInfo.roughness=sheenOut.sheenIntensity; -#else -#ifdef HEMILIGHT{X} -preInfo.roughness=sheenOut.sheenRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#endif -info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif - -#ifdef CLEARCOAT - -#ifdef HEMILIGHT{X} -preInfo.roughness=clearcoatOut.clearCoatRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); -#ifdef CLEARCOAT_TINT - -absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity); -info.diffuse*=absorption; -#ifdef SPECULARTERM -info.specular*=absorption; -#endif -#endif - -info.diffuse*=info.clearCoat.w; -#ifdef SPECULARTERM -info.specular*=info.clearCoat.w; -#endif -#ifdef SHEEN -info.sheen*=info.clearCoat.w; -#endif -#endif -#else -#ifdef SPOTLIGHT{X} -info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#elif defined(HEMILIGHT{X}) -info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); -#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) -info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#endif -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); -#endif -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -for (int i=0; i=0.) { -index{X}=i; -break; -} -} -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -if (index{X}>=0) -#endif -{ -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; -#endif -#ifndef SHADOWCSMNOBLEND{X} -float frustumLength=frustumLengths{X}[index{X}]; -float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X}; -if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) -{ -index{X}+=1; -float nextShadow=0.; -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -shadow=mix(nextShadow,shadow,diffRatio); -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); -#endif -} -#endif -} -#elif defined(SHADOWCLOSEESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithCloseESMCube(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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=`#ifdef FOG -float fog=CalcFogFactor(); -color.rgb=fog*color.rgb+(1.0-fog)*vFogColor; -#endif`;f(5).a.IncludesShadersStore.fogFragment=B},function(Ae,v,f){var B="fogVertexDeclaration",_=`#ifdef FOG -varying vec3 vFogDistance; -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="shadowsVertex",_=`#ifdef SHADOWS -#if defined(SHADOWCSM{X}) -vPositionFromCamera{X}=view*worldPos; -for (int i=0; i1)for(var E=0;E=x||M.indexOf("file:")!==-1?-1:Math.pow(2,C)*u}},_}()},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,this.reset()}return Object.defineProperty(_.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"zOffset",{get:function(){return this._zOffset},set:function(x){this._zOffset!==x&&(this._zOffset=x,this._isZOffsetDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"cullFace",{get:function(){return this._cullFace},set:function(x){this._cullFace!==x&&(this._cullFace=x,this._isCullFaceDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"cull",{get:function(){return this._cull},set:function(x){this._cull!==x&&(this._cull=x,this._isCullDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(x){this._depthFunc!==x&&(this._depthFunc=x,this._isDepthFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"depthMask",{get:function(){return this._depthMask},set:function(x){this._depthMask!==x&&(this._depthMask=x,this._isDepthMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"depthTest",{get:function(){return this._depthTest},set:function(x){this._depthTest!==x&&(this._depthTest=x,this._isDepthTestDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"frontFace",{get:function(){return this._frontFace},set:function(x){this._frontFace!==x&&(this._frontFace=x,this._isFrontFaceDirty=!0)},enumerable:!1,configurable:!0}),_.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1},_.prototype.apply=function(x){this.isDirty&&(this._isCullDirty&&(this.cull?x.enable(x.CULL_FACE):x.disable(x.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(x.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(x.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?x.enable(x.DEPTH_TEST):x.disable(x.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(x.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset?(x.enable(x.POLYGON_OFFSET_FILL),x.polygonOffset(this.zOffset,0)):x.disable(x.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(x.frontFace(this.frontFace),this._isFrontFaceDirty=!1))},_}()},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(2),_=function(){function x(){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.reset()}return Object.defineProperty(x.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilFunc",{get:function(){return this._stencilFunc},set:function(u){this._stencilFunc!==u&&(this._stencilFunc=u,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilFuncRef",{get:function(){return this._stencilFuncRef},set:function(u){this._stencilFuncRef!==u&&(this._stencilFuncRef=u,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilFuncMask",{get:function(){return this._stencilFuncMask},set:function(u){this._stencilFuncMask!==u&&(this._stencilFuncMask=u,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilOpStencilFail",{get:function(){return this._stencilOpStencilFail},set:function(u){this._stencilOpStencilFail!==u&&(this._stencilOpStencilFail=u,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilOpDepthFail",{get:function(){return this._stencilOpDepthFail},set:function(u){this._stencilOpDepthFail!==u&&(this._stencilOpDepthFail=u,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilOpStencilDepthPass",{get:function(){return this._stencilOpStencilDepthPass},set:function(u){this._stencilOpStencilDepthPass!==u&&(this._stencilOpStencilDepthPass=u,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilMask",{get:function(){return this._stencilMask},set:function(u){this._stencilMask!==u&&(this._stencilMask=u,this._isStencilMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"stencilTest",{get:function(){return this._stencilTest},set:function(u){this._stencilTest!==u&&(this._stencilTest=u,this._isStencilTestDirty=!0)},enumerable:!1,configurable:!0}),x.prototype.reset=function(){this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=x.ALWAYS,this._stencilFuncRef=1,this._stencilFuncMask=255,this._stencilOpStencilFail=x.KEEP,this._stencilOpDepthFail=x.KEEP,this._stencilOpStencilDepthPass=x.REPLACE,this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},x.prototype.apply=function(u){this.isDirty&&(this._isStencilTestDirty&&(this.stencilTest?u.enable(u.STENCIL_TEST):u.disable(u.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(u.stencilMask(this.stencilMask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(u.stencilFunc(this.stencilFunc,this.stencilFuncRef,this.stencilFuncMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(u.stencilOp(this.stencilOpStencilFail,this.stencilOpDepthFail,this.stencilOpStencilDepthPass),this._isStencilOpDirty=!1))},x.ALWAYS=B.a.ALWAYS,x.KEEP=B.a.KEEP,x.REPLACE=B.a.REPLACE,x}()},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this.reset()}return Object.defineProperty(_.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(x){this._alphaBlend!==x&&(this._alphaBlend=x,this._isAlphaBlendDirty=!0)},enumerable:!1,configurable:!0}),_.prototype.setAlphaBlendConstants=function(x,u,M,R){this._blendConstants[0]===x&&this._blendConstants[1]===u&&this._blendConstants[2]===M&&this._blendConstants[3]===R||(this._blendConstants[0]=x,this._blendConstants[1]=u,this._blendConstants[2]=M,this._blendConstants[3]=R,this._isBlendConstantsDirty=!0)},_.prototype.setAlphaBlendFunctionParameters=function(x,u,M,R){this._blendFunctionParameters[0]===x&&this._blendFunctionParameters[1]===u&&this._blendFunctionParameters[2]===M&&this._blendFunctionParameters[3]===R||(this._blendFunctionParameters[0]=x,this._blendFunctionParameters[1]=u,this._blendFunctionParameters[2]=M,this._blendFunctionParameters[3]=R,this._isBlendFunctionParametersDirty=!0)},_.prototype.setAlphaEquationParameters=function(x,u){this._blendEquationParameters[0]===x&&this._blendEquationParameters[1]===u||(this._blendEquationParameters[0]=x,this._blendEquationParameters[1]=u,this._isBlendEquationParametersDirty=!0)},_.prototype.reset=function(){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},_.prototype.apply=function(x){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?x.enable(x.BLEND):x.disable(x.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(x.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(x.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(x.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))},_}()},function(Ae,v,f){f.d(v,"a",function(){return B});var B=function(){function _(){this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null}return Object.defineProperty(_.prototype,"isAsync",{get:function(){return this.isParallelCompiled},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"isReady",{get:function(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))},enumerable:!1,configurable:!0}),_.prototype._handlesSpectorRebuildCallback=function(x){x&&this.program&&x(this.program)},_.prototype._getVertexShaderCode=function(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null},_.prototype._getFragmentShaderCode=function(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null},_}()},function(Ae,v,f){var B;f.d(v,"a",function(){return u}),function(M){M[M.Pending=0]="Pending",M[M.Fulfilled=1]="Fulfilled",M[M.Rejected=2]="Rejected"}(B||(B={}));var _=function(){this.count=0,this.target=0,this.results=[]},x=function(){function M(R){var C=this;if(this._state=B.Pending,this._children=new Array,this._rejectWasConsumed=!1,R)try{R(function(m){C._resolve(m)},function(m){C._reject(m)})}catch(m){this._reject(m)}}return Object.defineProperty(M.prototype,"_result",{get:function(){return this._resultValue},set:function(R){this._resultValue=R,this._parent&&this._parent._result===void 0&&(this._parent._result=R)},enumerable:!1,configurable:!0}),M.prototype.catch=function(R){return this.then(void 0,R)},M.prototype.then=function(R,C){var m=this,c=new M;return c._onFulfilled=R,c._onRejected=C,this._children.push(c),c._parent=this,this._state!==B.Pending&&setTimeout(function(){if(m._state===B.Fulfilled||m._rejectWasConsumed){var E=c._resolve(m._result);if(E!=null)if(E._state!==void 0){var A=E;c._children.push(A),A._parent=c,c=A}else c._result=E}else c._reject(m._reason)}),c},M.prototype._moveChildren=function(R){var C,m=this;if((C=this._children).push.apply(C,R.splice(0,R.length)),this._children.forEach(function(g){g._parent=m}),this._state===B.Fulfilled)for(var c=0,E=this._children;c"u")&&(window.Promise=x)},M}()},function(Ae,v,f){f.d(v,"a",function(){return _}),f.d(v,"b",function(){return x});var B=f(57),_=function(){function u(M){M===void 0&&(M=30),this._enabled=!0,this._rollingFrameTime=new x(M)}return u.prototype.sampleFrame=function(M){if(M===void 0&&(M=B.a.Now),this._enabled){if(this._lastFrameTimeMs!=null){var R=M-this._lastFrameTimeMs;this._rollingFrameTime.add(R)}this._lastFrameTimeMs=M}},Object.defineProperty(u.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"instantaneousFPS",{get:function(){var M=this._rollingFrameTime.history(0);return M===0?0:1e3/M},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!1,configurable:!0}),u.prototype.enable=function(){this._enabled=!0},u.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(u.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!1,configurable:!0}),u.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},u}(),x=function(){function u(M){this._samples=new Array(M),this.reset()}return u.prototype.add=function(M){var R;if(this.isSaturated()){var C=this._samples[this._pos];R=C-this.average,this.average-=R/(this._sampleCount-1),this._m2-=R*(C-this.average)}else this._sampleCount++;R=M-this.average,this.average+=R/this._sampleCount,this._m2+=R*(M-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=M,this._pos++,this._pos%=this._samples.length},u.prototype.history=function(M){if(M>=this._sampleCount||M>=this._samples.length)return 0;var R=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(R-M)]},u.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},u.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},u.prototype._wrapPosition=function(M){var R=this._samples.length;return(M%R+R)%R},u}()},function(Ae,v,f){f.d(v,"a",function(){return _});var B=f(0),_=function(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new B.e(0,0,0),this._diffPositionForCollisions=new B.e(0,0,0),this._collisionResponse=!0}},function(Ae,v,f){f.d(v,"a",function(){return u});var B=f(33),_=f(0),x=f(2),u=function(){function M(R,C,m,c,E){m===void 0&&(m=null),c===void 0&&(c=null),E===void 0&&(E=null),this.index=R,this._opaqueSubMeshes=new B.a(256),this._transparentSubMeshes=new B.a(256),this._alphaTestSubMeshes=new B.a(256),this._depthOnlySubMeshes=new B.a(256),this._particleSystems=new B.a(256),this._spriteManagers=new B.a(256),this._edgesRenderers=new B.b(16),this._scene=C,this.opaqueSortCompareFn=m,this.alphaTestSortCompareFn=c,this.transparentSortCompareFn=E}return Object.defineProperty(M.prototype,"opaqueSortCompareFn",{set:function(R){this._opaqueSortCompareFn=R,this._renderOpaque=R?this.renderOpaqueSorted:M.renderUnsorted},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"alphaTestSortCompareFn",{set:function(R){this._alphaTestSortCompareFn=R,this._renderAlphaTest=R?this.renderAlphaTestSorted:M.renderUnsorted},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"transparentSortCompareFn",{set:function(R){this._transparentSortCompareFn=R||M.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!1,configurable:!0}),M.prototype.render=function(R,C,m,c){if(R)R(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);else{var E=this._scene.getEngine();this._depthOnlySubMeshes.length!==0&&(E.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),E.setColorWrite(!0)),this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);var A=E.getStencilBuffer();if(E.setStencilBuffer(!1),C&&this._renderSprites(),m&&this._renderParticles(c),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),this._transparentSubMeshes.length!==0&&(E.setStencilBuffer(A),this._renderTransparent(this._transparentSubMeshes),E.setAlphaMode(x.a.ALPHA_DISABLE)),E.setStencilBuffer(!1),this._edgesRenderers.length){for(var S=0;SC._alphaIndex?1:R._alphaIndexC._distanceToCamera?-1:0},M.frontToBackSortCompare=function(R,C){return R._distanceToCameraC._distanceToCamera?1:0},M.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},M.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},M.prototype.dispatch=function(R,C,m){C===void 0&&(C=R.getMesh()),m===void 0&&(m=R.getMaterial()),m!=null&&(m.needAlphaBlendingForMesh(C)?this._transparentSubMeshes.push(R):m.needAlphaTesting()?(m.needDepthPrePass&&this._depthOnlySubMeshes.push(R),this._alphaTestSubMeshes.push(R)):(m.needDepthPrePass&&this._depthOnlySubMeshes.push(R),this._opaqueSubMeshes.push(R)),C._renderingGroup=this,C._edgesRenderer&&C._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(C._edgesRenderer))},M.prototype.dispatchSprites=function(R){this._spriteManagers.push(R)},M.prototype.dispatchParticles=function(R){this._particleSystems.push(R)},M.prototype._renderParticles=function(R){if(this._particleSystems.length!==0){var C=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var m=0;m=0;){var g=C[A];g<0?g=0:g>1&&(g=1),S[A]=255*g}C=S}var l=document.createElement("canvas");l.width=c,l.height=E;var h=l.getContext("2d");if(!h)return null;var b=h.createImageData(c,E);if(b.data.set(C),h.putImageData(b,0,0),R.invertY){var T=document.createElement("canvas");T.width=c,T.height=E;var D=T.getContext("2d");return D?(D.translate(0,E),D.scale(1,-1),D.drawImage(l,0,0),T.toDataURL("image/png")):null}return l.toDataURL("image/png")},_}()},function(Ae,v,f){f.d(v,"a",function(){return A});var B=f(1),_=f(0),x=f(8),u=f(31),M=f(7),R=f(41),C=f(46),m=f(4),c=f(43),E=f(12);M.a._instancedMeshFactory=function(S,g){var l=new A(S,g);if(g.instancedBuffers)for(var h in l.instancedBuffers={},g.instancedBuffers)l.instancedBuffers[h]=g.instancedBuffers[h];return l};var A=function(S){function g(l,h){var b=S.call(this,l,h.getScene())||this;b._indexInSourceMeshInstanceArray=-1,h.addInstance(b),b._sourceMesh=h,b._unIndexed=h._unIndexed,b.position.copyFrom(h.position),b.rotation.copyFrom(h.rotation),b.scaling.copyFrom(h.scaling),h.rotationQuaternion&&(b.rotationQuaternion=h.rotationQuaternion.clone()),b.animations=E.b.Slice(h.animations);for(var T=0,D=h.getAnimationRanges();T0!=this._getWorldMatrixDeterminant()>0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,l),h){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},g.prototype._postActivate=function(){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)},g.prototype.getWorldMatrix=function(){if(this._currentLOD&&this._currentLOD.billboardMode!==C.a.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){var l=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,_.c.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),_.c.Matrix[0].copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(_.c.Vector3[7]),this._currentLOD._masterMesh=l,_.c.Matrix[0]}return S.prototype.getWorldMatrix.call(this)},Object.defineProperty(g.prototype,"isAnInstance",{get:function(){return!0},enumerable:!1,configurable:!0}),g.prototype.getLOD=function(l){if(!l)return this;var h=this.getBoundingInfo();return this._currentLOD=this.sourceMesh.getLOD(l,h.boundingSphere),this._currentLOD===this.sourceMesh?this.sourceMesh:this._currentLOD},g.prototype._preActivateForIntermediateRendering=function(l){return this.sourceMesh._preActivateForIntermediateRendering(l)},g.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var l=0;l=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; -}`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="logDepthFragment",_=`#ifdef LOGARITHMICDEPTH -gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=`#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`;f(5).a.IncludesShadersStore.bumpVertex=B},function(Ae,v,f){var B=`#ifdef FOG -vFogDistance=(view*worldPos).xyz; -#endif`;f(5).a.IncludesShadersStore.fogVertex=B},function(Ae,v,f){var B="logDepthVertex",_=`#ifdef LOGARITHMICDEPTH -vFragmentDepth=1.0+gl_Position.w; -gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v){var f;f=function(){return this}();try{f=f||new Function("return this")()}catch{typeof window=="object"&&(f=window)}Ae.exports=f},function(Ae,v,f){var B="prePassDeclaration",_=`#ifdef PREPASS -#extension GL_EXT_draw_buffers : require -#ifdef WEBGL2 -layout(location=0) out highp vec4 glFragData[{X}]; -highp vec4 gl_FragColor; -#endif -#ifdef PREPASS_DEPTHNORMAL -varying highp vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -varying highp vec4 vCurrentPosition; -varying highp vec4 vPreviousPosition; -#endif -#endif -`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="fresnelFunction",_=`#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`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=`#ifdef DEPTHPREPASS -gl_FragColor=vec4(0.,0.,0.,1.0); -return; -#endif`;f(5).a.IncludesShadersStore.depthPrePass=B},function(Ae,v,f){var B="prePassVertexDeclaration",_=`#ifdef PREPASS -#ifdef PREPASS_DEPTHNORMAL -varying vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -uniform mat4 previousWorld; -uniform mat4 previousViewProjection; -varying vec4 vCurrentPosition; -varying vec4 vPreviousPosition; -#endif -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="bumpVertexDeclaration",_=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#endif -`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B="prePassVertex",_=`#ifdef PREPASS_DEPTHNORMAL -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*previousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*previousWorld*vec4(positionUpdated,1.0); -#endif -#endif`;f(5).a.IncludesShadersStore[B]=_},function(Ae,v,f){var B=f(5),_=(f(115),f(110),"colorPixelShader"),x=`#ifdef VERTEXCOLOR -varying vec4 vColor; -#else -uniform vec4 color; -#endif -#include -void main(void) { -#include -#ifdef VERTEXCOLOR -gl_FragColor=vColor; -#else -gl_FragColor=color; -#endif -}`;B.a.ShadersStore[_]=x},function(Ae,v,f){var B=f(5),_=(f(78),f(117),f(79),f(80),f(81),f(111),"colorVertexShader"),x=` -attribute vec3 position; -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include - -#include -uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif - -#ifdef VERTEXCOLOR -varying vec4 vColor; -#endif -void main(void) { -#include -#include -vec4 worldPos=finalWorld*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR == 0u) { -gl_Position=viewProjection*worldPos; -} else { -gl_Position=viewProjectionR*worldPos; -} -#else -gl_Position=viewProjection*worldPos; -#endif -#include -#ifdef VERTEXCOLOR - -vColor=color; -#endif -}`;B.a.ShadersStore[_]=x},function(Ae,v,f){(function(B){f.d(v,"b",function(){return E}),f.d(v,"a",function(){return A});var _=f(1),x=f(8),u=f(13),M=f(102),R=f(27),C=f(2),m=f(89),c=f(74),E=function(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4},A=function(S){function g(l){l===void 0&&(l=new E);var h=S.call(this,null)||this;u.a.Instances.push(h),l.deterministicLockstep===void 0&&(l.deterministicLockstep=!1),l.lockstepMaxSteps===void 0&&(l.lockstepMaxSteps=4),h._options=l,c.a.SetMatrixPrecision(!!l.useHighPrecisionMatrix),h._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1},x.a.Log("Babylon.js v"+u.a.Version+" - Null engine");var b=typeof self<"u"?self:B!==void 0?B:window;return typeof URL>"u"&&(b.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(b.Blob=function(){}),h}return Object(_.d)(g,S),g.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},g.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},g.prototype.getHardwareScalingLevel=function(){return 1},g.prototype.createVertexBuffer=function(l){var h=new m.a;return h.references=1,h},g.prototype.createIndexBuffer=function(l){var h=new m.a;return h.references=1,h},g.prototype.clear=function(l,h,b,T){},g.prototype.getRenderWidth=function(l){return l===void 0&&(l=!1),!l&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},g.prototype.getRenderHeight=function(l){return l===void 0&&(l=!1),!l&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},g.prototype.setViewport=function(l,h,b){this._cachedViewport=l},g.prototype.createShaderProgram=function(l,h,b,T,D){return{__SPECTOR_rebuildProgram:null}},g.prototype.getUniforms=function(l,h){return[]},g.prototype.getAttributes=function(l,h){return[]},g.prototype.bindSamplers=function(l){this._currentEffect=null},g.prototype.enableEffect=function(l){this._currentEffect=l,l.onBind&&l.onBind(l),l._onBindObservable&&l._onBindObservable.notifyObservers(l)},g.prototype.setState=function(l,h,b,T){},g.prototype.setIntArray=function(l,h){return!0},g.prototype.setIntArray2=function(l,h){return!0},g.prototype.setIntArray3=function(l,h){return!0},g.prototype.setIntArray4=function(l,h){return!0},g.prototype.setFloatArray=function(l,h){return!0},g.prototype.setFloatArray2=function(l,h){return!0},g.prototype.setFloatArray3=function(l,h){return!0},g.prototype.setFloatArray4=function(l,h){return!0},g.prototype.setArray=function(l,h){return!0},g.prototype.setArray2=function(l,h){return!0},g.prototype.setArray3=function(l,h){return!0},g.prototype.setArray4=function(l,h){return!0},g.prototype.setMatrices=function(l,h){return!0},g.prototype.setMatrix3x3=function(l,h){return!0},g.prototype.setMatrix2x2=function(l,h){return!0},g.prototype.setFloat=function(l,h){return!0},g.prototype.setFloat2=function(l,h,b){return!0},g.prototype.setFloat3=function(l,h,b,T){return!0},g.prototype.setBool=function(l,h){return!0},g.prototype.setFloat4=function(l,h,b,T,D){return!0},g.prototype.setAlphaMode=function(l,h){h===void 0&&(h=!1),this._alphaMode!==l&&(this.alphaState.alphaBlend=l!==C.a.ALPHA_DISABLE,h||this.setDepthWrite(l===C.a.ALPHA_DISABLE),this._alphaMode=l)},g.prototype.bindBuffers=function(l,h,b){},g.prototype.wipeCaches=function(l){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,l&&(this._currentProgram=null,this.stencilState.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},g.prototype.draw=function(l,h,b,T){},g.prototype.drawElementsType=function(l,h,b,T){},g.prototype.drawArraysType=function(l,h,b,T){},g.prototype._createTexture=function(){return{}},g.prototype._releaseTexture=function(l){},g.prototype.createTexture=function(l,h,b,T,D,w,N,I,V,W,j,ne){D===void 0&&(D=C.a.TEXTURE_TRILINEAR_SAMPLINGMODE),w===void 0&&(w=null),W===void 0&&(W=null);var te=new R.a(this,R.b.Url),de=String(l);return te.url=de,te.generateMipMaps=!h,te.samplingMode=D,te.invertY=b,te.baseWidth=this._options.textureSize,te.baseHeight=this._options.textureSize,te.width=this._options.textureSize,te.height=this._options.textureSize,W&&(te.format=W),te.isReady=!0,w&&w(),this._internalTexturesCache.push(te),te},g.prototype.createRenderTargetTexture=function(l,h){var b=new M.a;h!==void 0&&typeof h=="object"?(b.generateMipMaps=h.generateMipMaps,b.generateDepthBuffer=h.generateDepthBuffer===void 0||h.generateDepthBuffer,b.generateStencilBuffer=b.generateDepthBuffer&&h.generateStencilBuffer,b.type=h.type===void 0?C.a.TEXTURETYPE_UNSIGNED_INT:h.type,b.samplingMode=h.samplingMode===void 0?C.a.TEXTURE_TRILINEAR_SAMPLINGMODE:h.samplingMode):(b.generateMipMaps=h,b.generateDepthBuffer=!0,b.generateStencilBuffer=!1,b.type=C.a.TEXTURETYPE_UNSIGNED_INT,b.samplingMode=C.a.TEXTURE_TRILINEAR_SAMPLINGMODE);var T=new R.a(this,R.b.RenderTarget),D=l.width||l,w=l.height||l;return T._depthStencilBuffer={},T._framebuffer={},T.baseWidth=D,T.baseHeight=w,T.width=D,T.height=w,T.isReady=!0,T.samples=1,T.generateMipMaps=!!b.generateMipMaps,T.samplingMode=b.samplingMode,T.type=b.type,T._generateDepthBuffer=b.generateDepthBuffer,T._generateStencilBuffer=!!b.generateStencilBuffer,this._internalTexturesCache.push(T),T},g.prototype.updateTextureSamplingMode=function(l,h){h.samplingMode=l},g.prototype.bindFramebuffer=function(l,h,b,T,D){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=l,this._currentFramebuffer=l._MSAAFramebuffer?l._MSAAFramebuffer:l._framebuffer,this._cachedViewport&&!D&&this.setViewport(this._cachedViewport,b,T)},g.prototype.unBindFramebuffer=function(l,h,b){this._currentRenderTarget=null,b&&(l._MSAAFramebuffer&&(this._currentFramebuffer=l._framebuffer),b()),this._currentFramebuffer=null},g.prototype.createDynamicVertexBuffer=function(l){var h=new m.a;return h.references=1,h.capacity=1,h},g.prototype.updateDynamicTexture=function(l,h,b,T,D){},g.prototype.areAllEffectsReady=function(){return!0},g.prototype.getError=function(){return 0},g.prototype._getUnpackAlignement=function(){return 1},g.prototype._unpackFlipY=function(l){},g.prototype.updateDynamicIndexBuffer=function(l,h,b){},g.prototype.updateDynamicVertexBuffer=function(l,h,b,T){},g.prototype._bindTextureDirectly=function(l,h){return this._boundTexturesCache[this._activeChannel]!==h&&(this._boundTexturesCache[this._activeChannel]=h,!0)},g.prototype._bindTexture=function(l,h){l<0||this._bindTextureDirectly(0,h)},g.prototype._deleteBuffer=function(l){},g.prototype.releaseEffects=function(){},g.prototype.displayLoadingUI=function(){},g.prototype.hideLoadingUI=function(){},g.prototype._uploadCompressedDataToTextureDirectly=function(l,h,b,T,D,w,N){},g.prototype._uploadDataToTextureDirectly=function(l,h,b,T){},g.prototype._uploadArrayBufferViewToTexture=function(l,h,b,T){},g.prototype._uploadImageToTexture=function(l,h,b,T){},g}(u.a)}).call(this,f(159))},function(Ae,v,f){f.r(v),function(B){f.d(v,"Debug",function(){return m});var _=f(127),x=f(99);f.d(v,"AbstractScene",function(){return _.AbstractScene}),f.d(v,"AbstractActionManager",function(){return _.AbstractActionManager}),f.d(v,"Action",function(){return _.Action}),f.d(v,"ActionEvent",function(){return _.ActionEvent}),f.d(v,"ActionManager",function(){return _.ActionManager}),f.d(v,"Condition",function(){return _.Condition}),f.d(v,"ValueCondition",function(){return _.ValueCondition}),f.d(v,"PredicateCondition",function(){return _.PredicateCondition}),f.d(v,"StateCondition",function(){return _.StateCondition}),f.d(v,"SwitchBooleanAction",function(){return _.SwitchBooleanAction}),f.d(v,"SetStateAction",function(){return _.SetStateAction}),f.d(v,"SetValueAction",function(){return _.SetValueAction}),f.d(v,"IncrementValueAction",function(){return _.IncrementValueAction}),f.d(v,"PlayAnimationAction",function(){return _.PlayAnimationAction}),f.d(v,"StopAnimationAction",function(){return _.StopAnimationAction}),f.d(v,"DoNothingAction",function(){return _.DoNothingAction}),f.d(v,"CombineAction",function(){return _.CombineAction}),f.d(v,"ExecuteCodeAction",function(){return _.ExecuteCodeAction}),f.d(v,"SetParentAction",function(){return _.SetParentAction}),f.d(v,"PlaySoundAction",function(){return _.PlaySoundAction}),f.d(v,"StopSoundAction",function(){return _.StopSoundAction}),f.d(v,"InterpolateValueAction",function(){return _.InterpolateValueAction}),f.d(v,"Animatable",function(){return _.Animatable}),f.d(v,"_IAnimationState",function(){return _._IAnimationState}),f.d(v,"Animation",function(){return _.Animation}),f.d(v,"TargetedAnimation",function(){return _.TargetedAnimation}),f.d(v,"AnimationGroup",function(){return _.AnimationGroup}),f.d(v,"AnimationPropertiesOverride",function(){return _.AnimationPropertiesOverride}),f.d(v,"EasingFunction",function(){return _.EasingFunction}),f.d(v,"CircleEase",function(){return _.CircleEase}),f.d(v,"BackEase",function(){return _.BackEase}),f.d(v,"BounceEase",function(){return _.BounceEase}),f.d(v,"CubicEase",function(){return _.CubicEase}),f.d(v,"ElasticEase",function(){return _.ElasticEase}),f.d(v,"ExponentialEase",function(){return _.ExponentialEase}),f.d(v,"PowerEase",function(){return _.PowerEase}),f.d(v,"QuadraticEase",function(){return _.QuadraticEase}),f.d(v,"QuarticEase",function(){return _.QuarticEase}),f.d(v,"QuinticEase",function(){return _.QuinticEase}),f.d(v,"SineEase",function(){return _.SineEase}),f.d(v,"BezierCurveEase",function(){return _.BezierCurveEase}),f.d(v,"RuntimeAnimation",function(){return _.RuntimeAnimation}),f.d(v,"AnimationEvent",function(){return _.AnimationEvent}),f.d(v,"AnimationKeyInterpolation",function(){return _.AnimationKeyInterpolation}),f.d(v,"AnimationRange",function(){return _.AnimationRange}),f.d(v,"KeepAssets",function(){return _.KeepAssets}),f.d(v,"InstantiatedEntries",function(){return _.InstantiatedEntries}),f.d(v,"AssetContainer",function(){return _.AssetContainer}),f.d(v,"Analyser",function(){return _.Analyser}),f.d(v,"AudioEngine",function(){return _.AudioEngine}),f.d(v,"AudioSceneComponent",function(){return _.AudioSceneComponent}),f.d(v,"Sound",function(){return _.Sound}),f.d(v,"SoundTrack",function(){return _.SoundTrack}),f.d(v,"WeightedSound",function(){return _.WeightedSound}),f.d(v,"AutoRotationBehavior",function(){return _.AutoRotationBehavior}),f.d(v,"BouncingBehavior",function(){return _.BouncingBehavior}),f.d(v,"FramingBehavior",function(){return _.FramingBehavior}),f.d(v,"AttachToBoxBehavior",function(){return _.AttachToBoxBehavior}),f.d(v,"FadeInOutBehavior",function(){return _.FadeInOutBehavior}),f.d(v,"MultiPointerScaleBehavior",function(){return _.MultiPointerScaleBehavior}),f.d(v,"PointerDragBehavior",function(){return _.PointerDragBehavior}),f.d(v,"SixDofDragBehavior",function(){return _.SixDofDragBehavior}),f.d(v,"Bone",function(){return _.Bone}),f.d(v,"BoneIKController",function(){return _.BoneIKController}),f.d(v,"BoneLookController",function(){return _.BoneLookController}),f.d(v,"Skeleton",function(){return _.Skeleton}),f.d(v,"ArcRotateCameraGamepadInput",function(){return _.ArcRotateCameraGamepadInput}),f.d(v,"ArcRotateCameraKeyboardMoveInput",function(){return _.ArcRotateCameraKeyboardMoveInput}),f.d(v,"ArcRotateCameraMouseWheelInput",function(){return _.ArcRotateCameraMouseWheelInput}),f.d(v,"ArcRotateCameraPointersInput",function(){return _.ArcRotateCameraPointersInput}),f.d(v,"ArcRotateCameraVRDeviceOrientationInput",function(){return _.ArcRotateCameraVRDeviceOrientationInput}),f.d(v,"FlyCameraKeyboardInput",function(){return _.FlyCameraKeyboardInput}),f.d(v,"FlyCameraMouseInput",function(){return _.FlyCameraMouseInput}),f.d(v,"FollowCameraKeyboardMoveInput",function(){return _.FollowCameraKeyboardMoveInput}),f.d(v,"FollowCameraMouseWheelInput",function(){return _.FollowCameraMouseWheelInput}),f.d(v,"FollowCameraPointersInput",function(){return _.FollowCameraPointersInput}),f.d(v,"FreeCameraDeviceOrientationInput",function(){return _.FreeCameraDeviceOrientationInput}),f.d(v,"FreeCameraGamepadInput",function(){return _.FreeCameraGamepadInput}),f.d(v,"FreeCameraKeyboardMoveInput",function(){return _.FreeCameraKeyboardMoveInput}),f.d(v,"FreeCameraMouseInput",function(){return _.FreeCameraMouseInput}),f.d(v,"FreeCameraMouseWheelInput",function(){return _.FreeCameraMouseWheelInput}),f.d(v,"FreeCameraTouchInput",function(){return _.FreeCameraTouchInput}),f.d(v,"FreeCameraVirtualJoystickInput",function(){return _.FreeCameraVirtualJoystickInput}),f.d(v,"CameraInputTypes",function(){return _.CameraInputTypes}),f.d(v,"CameraInputsManager",function(){return _.CameraInputsManager}),f.d(v,"Camera",function(){return _.Camera}),f.d(v,"TargetCamera",function(){return _.TargetCamera}),f.d(v,"FreeCamera",function(){return _.FreeCamera}),f.d(v,"FreeCameraInputsManager",function(){return _.FreeCameraInputsManager}),f.d(v,"TouchCamera",function(){return _.TouchCamera}),f.d(v,"ArcRotateCamera",function(){return _.ArcRotateCamera}),f.d(v,"ArcRotateCameraInputsManager",function(){return _.ArcRotateCameraInputsManager}),f.d(v,"DeviceOrientationCamera",function(){return _.DeviceOrientationCamera}),f.d(v,"FlyCamera",function(){return _.FlyCamera}),f.d(v,"FlyCameraInputsManager",function(){return _.FlyCameraInputsManager}),f.d(v,"FollowCamera",function(){return _.FollowCamera}),f.d(v,"ArcFollowCamera",function(){return _.ArcFollowCamera}),f.d(v,"FollowCameraInputsManager",function(){return _.FollowCameraInputsManager}),f.d(v,"GamepadCamera",function(){return _.GamepadCamera}),f.d(v,"AnaglyphArcRotateCamera",function(){return _.AnaglyphArcRotateCamera}),f.d(v,"AnaglyphFreeCamera",function(){return _.AnaglyphFreeCamera}),f.d(v,"AnaglyphGamepadCamera",function(){return _.AnaglyphGamepadCamera}),f.d(v,"AnaglyphUniversalCamera",function(){return _.AnaglyphUniversalCamera}),f.d(v,"StereoscopicArcRotateCamera",function(){return _.StereoscopicArcRotateCamera}),f.d(v,"StereoscopicFreeCamera",function(){return _.StereoscopicFreeCamera}),f.d(v,"StereoscopicGamepadCamera",function(){return _.StereoscopicGamepadCamera}),f.d(v,"StereoscopicUniversalCamera",function(){return _.StereoscopicUniversalCamera}),f.d(v,"UniversalCamera",function(){return _.UniversalCamera}),f.d(v,"VirtualJoysticksCamera",function(){return _.VirtualJoysticksCamera}),f.d(v,"VRCameraMetrics",function(){return _.VRCameraMetrics}),f.d(v,"VRDeviceOrientationArcRotateCamera",function(){return _.VRDeviceOrientationArcRotateCamera}),f.d(v,"VRDeviceOrientationFreeCamera",function(){return _.VRDeviceOrientationFreeCamera}),f.d(v,"VRDeviceOrientationGamepadCamera",function(){return _.VRDeviceOrientationGamepadCamera}),f.d(v,"OnAfterEnteringVRObservableEvent",function(){return _.OnAfterEnteringVRObservableEvent}),f.d(v,"VRExperienceHelper",function(){return _.VRExperienceHelper}),f.d(v,"WebVRFreeCamera",function(){return _.WebVRFreeCamera}),f.d(v,"Collider",function(){return _.Collider}),f.d(v,"DefaultCollisionCoordinator",function(){return _.DefaultCollisionCoordinator}),f.d(v,"PickingInfo",function(){return _.PickingInfo}),f.d(v,"IntersectionInfo",function(){return _.IntersectionInfo}),f.d(v,"_MeshCollisionData",function(){return _._MeshCollisionData}),f.d(v,"BoundingBox",function(){return _.BoundingBox}),f.d(v,"BoundingInfo",function(){return _.BoundingInfo}),f.d(v,"BoundingSphere",function(){return _.BoundingSphere}),f.d(v,"Octree",function(){return _.Octree}),f.d(v,"OctreeBlock",function(){return _.OctreeBlock}),f.d(v,"OctreeSceneComponent",function(){return _.OctreeSceneComponent}),f.d(v,"Ray",function(){return _.Ray}),f.d(v,"AxesViewer",function(){return _.AxesViewer}),f.d(v,"BoneAxesViewer",function(){return _.BoneAxesViewer}),f.d(v,"DebugLayerTab",function(){return _.DebugLayerTab}),f.d(v,"DebugLayer",function(){return _.DebugLayer}),f.d(v,"PhysicsViewer",function(){return _.PhysicsViewer}),f.d(v,"RayHelper",function(){return _.RayHelper}),f.d(v,"SkeletonViewer",function(){return _.SkeletonViewer}),f.d(v,"DeviceInputSystem",function(){return _.DeviceInputSystem}),f.d(v,"DeviceType",function(){return _.DeviceType}),f.d(v,"PointerInput",function(){return _.PointerInput}),f.d(v,"DualShockInput",function(){return _.DualShockInput}),f.d(v,"XboxInput",function(){return _.XboxInput}),f.d(v,"SwitchInput",function(){return _.SwitchInput}),f.d(v,"DeviceSource",function(){return _.DeviceSource}),f.d(v,"DeviceSourceManager",function(){return _.DeviceSourceManager}),f.d(v,"Constants",function(){return _.Constants}),f.d(v,"ThinEngine",function(){return _.ThinEngine}),f.d(v,"Engine",function(){return _.Engine}),f.d(v,"EngineStore",function(){return _.EngineStore}),f.d(v,"NullEngineOptions",function(){return _.NullEngineOptions}),f.d(v,"NullEngine",function(){return _.NullEngine}),f.d(v,"_OcclusionDataStorage",function(){return _._OcclusionDataStorage}),f.d(v,"_forceTransformFeedbackToBundle",function(){return _._forceTransformFeedbackToBundle}),f.d(v,"EngineView",function(){return _.EngineView}),f.d(v,"WebGLPipelineContext",function(){return _.WebGLPipelineContext}),f.d(v,"WebGL2ShaderProcessor",function(){return _.WebGL2ShaderProcessor}),f.d(v,"NativeEngine",function(){return _.NativeEngine}),f.d(v,"ShaderCodeInliner",function(){return _.ShaderCodeInliner}),f.d(v,"PerformanceConfigurator",function(){return _.PerformanceConfigurator}),f.d(v,"KeyboardEventTypes",function(){return _.KeyboardEventTypes}),f.d(v,"KeyboardInfo",function(){return _.KeyboardInfo}),f.d(v,"KeyboardInfoPre",function(){return _.KeyboardInfoPre}),f.d(v,"PointerEventTypes",function(){return _.PointerEventTypes}),f.d(v,"PointerInfoBase",function(){return _.PointerInfoBase}),f.d(v,"PointerInfoPre",function(){return _.PointerInfoPre}),f.d(v,"PointerInfo",function(){return _.PointerInfo}),f.d(v,"ClipboardEventTypes",function(){return _.ClipboardEventTypes}),f.d(v,"ClipboardInfo",function(){return _.ClipboardInfo}),f.d(v,"DaydreamController",function(){return _.DaydreamController}),f.d(v,"GearVRController",function(){return _.GearVRController}),f.d(v,"GenericController",function(){return _.GenericController}),f.d(v,"OculusTouchController",function(){return _.OculusTouchController}),f.d(v,"PoseEnabledControllerType",function(){return _.PoseEnabledControllerType}),f.d(v,"PoseEnabledControllerHelper",function(){return _.PoseEnabledControllerHelper}),f.d(v,"PoseEnabledController",function(){return _.PoseEnabledController}),f.d(v,"ViveController",function(){return _.ViveController}),f.d(v,"WebVRController",function(){return _.WebVRController}),f.d(v,"WindowsMotionController",function(){return _.WindowsMotionController}),f.d(v,"XRWindowsMotionController",function(){return _.XRWindowsMotionController}),f.d(v,"StickValues",function(){return _.StickValues}),f.d(v,"Gamepad",function(){return _.Gamepad}),f.d(v,"GenericPad",function(){return _.GenericPad}),f.d(v,"GamepadManager",function(){return _.GamepadManager}),f.d(v,"GamepadSystemSceneComponent",function(){return _.GamepadSystemSceneComponent}),f.d(v,"Xbox360Button",function(){return _.Xbox360Button}),f.d(v,"Xbox360Dpad",function(){return _.Xbox360Dpad}),f.d(v,"Xbox360Pad",function(){return _.Xbox360Pad}),f.d(v,"DualShockButton",function(){return _.DualShockButton}),f.d(v,"DualShockDpad",function(){return _.DualShockDpad}),f.d(v,"DualShockPad",function(){return _.DualShockPad}),f.d(v,"AxisDragGizmo",function(){return _.AxisDragGizmo}),f.d(v,"AxisScaleGizmo",function(){return _.AxisScaleGizmo}),f.d(v,"BoundingBoxGizmo",function(){return _.BoundingBoxGizmo}),f.d(v,"Gizmo",function(){return _.Gizmo}),f.d(v,"GizmoManager",function(){return _.GizmoManager}),f.d(v,"PlaneRotationGizmo",function(){return _.PlaneRotationGizmo}),f.d(v,"PositionGizmo",function(){return _.PositionGizmo}),f.d(v,"RotationGizmo",function(){return _.RotationGizmo}),f.d(v,"ScaleGizmo",function(){return _.ScaleGizmo}),f.d(v,"LightGizmo",function(){return _.LightGizmo}),f.d(v,"CameraGizmo",function(){return _.CameraGizmo}),f.d(v,"PlaneDragGizmo",function(){return _.PlaneDragGizmo}),f.d(v,"EnvironmentHelper",function(){return _.EnvironmentHelper}),f.d(v,"PhotoDome",function(){return _.PhotoDome}),f.d(v,"_forceSceneHelpersToBundle",function(){return _._forceSceneHelpersToBundle}),f.d(v,"VideoDome",function(){return _.VideoDome}),f.d(v,"EngineInstrumentation",function(){return _.EngineInstrumentation}),f.d(v,"SceneInstrumentation",function(){return _.SceneInstrumentation}),f.d(v,"_TimeToken",function(){return _._TimeToken}),f.d(v,"EffectLayer",function(){return _.EffectLayer}),f.d(v,"EffectLayerSceneComponent",function(){return _.EffectLayerSceneComponent}),f.d(v,"GlowLayer",function(){return _.GlowLayer}),f.d(v,"HighlightLayer",function(){return _.HighlightLayer}),f.d(v,"Layer",function(){return _.Layer}),f.d(v,"LayerSceneComponent",function(){return _.LayerSceneComponent}),f.d(v,"LensFlare",function(){return _.LensFlare}),f.d(v,"LensFlareSystem",function(){return _.LensFlareSystem}),f.d(v,"LensFlareSystemSceneComponent",function(){return _.LensFlareSystemSceneComponent}),f.d(v,"Light",function(){return _.Light}),f.d(v,"ShadowLight",function(){return _.ShadowLight}),f.d(v,"ShadowGenerator",function(){return _.ShadowGenerator}),f.d(v,"CascadedShadowGenerator",function(){return _.CascadedShadowGenerator}),f.d(v,"ShadowGeneratorSceneComponent",function(){return _.ShadowGeneratorSceneComponent}),f.d(v,"DirectionalLight",function(){return _.DirectionalLight}),f.d(v,"HemisphericLight",function(){return _.HemisphericLight}),f.d(v,"PointLight",function(){return _.PointLight}),f.d(v,"SpotLight",function(){return _.SpotLight}),f.d(v,"DefaultLoadingScreen",function(){return _.DefaultLoadingScreen}),f.d(v,"_BabylonLoaderRegistered",function(){return _._BabylonLoaderRegistered}),f.d(v,"BabylonFileLoaderConfiguration",function(){return _.BabylonFileLoaderConfiguration}),f.d(v,"SceneLoaderAnimationGroupLoadingMode",function(){return _.SceneLoaderAnimationGroupLoadingMode}),f.d(v,"SceneLoader",function(){return _.SceneLoader}),f.d(v,"SceneLoaderFlags",function(){return _.SceneLoaderFlags}),f.d(v,"BackgroundMaterial",function(){return _.BackgroundMaterial}),f.d(v,"ColorCurves",function(){return _.ColorCurves}),f.d(v,"EffectFallbacks",function(){return _.EffectFallbacks}),f.d(v,"Effect",function(){return _.Effect}),f.d(v,"FresnelParameters",function(){return _.FresnelParameters}),f.d(v,"ImageProcessingConfigurationDefines",function(){return _.ImageProcessingConfigurationDefines}),f.d(v,"ImageProcessingConfiguration",function(){return _.ImageProcessingConfiguration}),f.d(v,"Material",function(){return _.Material}),f.d(v,"MaterialDefines",function(){return _.MaterialDefines}),f.d(v,"ThinMaterialHelper",function(){return _.ThinMaterialHelper}),f.d(v,"MaterialHelper",function(){return _.MaterialHelper}),f.d(v,"MultiMaterial",function(){return _.MultiMaterial}),f.d(v,"PBRMaterialDefines",function(){return _.PBRMaterialDefines}),f.d(v,"PBRBaseMaterial",function(){return _.PBRBaseMaterial}),f.d(v,"PBRBaseSimpleMaterial",function(){return _.PBRBaseSimpleMaterial}),f.d(v,"PBRMaterial",function(){return _.PBRMaterial}),f.d(v,"PBRMetallicRoughnessMaterial",function(){return _.PBRMetallicRoughnessMaterial}),f.d(v,"PBRSpecularGlossinessMaterial",function(){return _.PBRSpecularGlossinessMaterial}),f.d(v,"PushMaterial",function(){return _.PushMaterial}),f.d(v,"ShaderMaterial",function(){return _.ShaderMaterial}),f.d(v,"StandardMaterialDefines",function(){return _.StandardMaterialDefines}),f.d(v,"StandardMaterial",function(){return _.StandardMaterial}),f.d(v,"BaseTexture",function(){return _.BaseTexture}),f.d(v,"ColorGradingTexture",function(){return _.ColorGradingTexture}),f.d(v,"CubeTexture",function(){return _.CubeTexture}),f.d(v,"DynamicTexture",function(){return _.DynamicTexture}),f.d(v,"EquiRectangularCubeTexture",function(){return _.EquiRectangularCubeTexture}),f.d(v,"HDRFiltering",function(){return _.HDRFiltering}),f.d(v,"HDRCubeTexture",function(){return _.HDRCubeTexture}),f.d(v,"HtmlElementTexture",function(){return _.HtmlElementTexture}),f.d(v,"InternalTextureSource",function(){return _.InternalTextureSource}),f.d(v,"InternalTexture",function(){return _.InternalTexture}),f.d(v,"_DDSTextureLoader",function(){return _._DDSTextureLoader}),f.d(v,"_ENVTextureLoader",function(){return _._ENVTextureLoader}),f.d(v,"_KTXTextureLoader",function(){return _._KTXTextureLoader}),f.d(v,"_TGATextureLoader",function(){return _._TGATextureLoader}),f.d(v,"_BasisTextureLoader",function(){return _._BasisTextureLoader}),f.d(v,"MirrorTexture",function(){return _.MirrorTexture}),f.d(v,"MultiRenderTarget",function(){return _.MultiRenderTarget}),f.d(v,"TexturePacker",function(){return _.TexturePacker}),f.d(v,"TexturePackerFrame",function(){return _.TexturePackerFrame}),f.d(v,"CustomProceduralTexture",function(){return _.CustomProceduralTexture}),f.d(v,"NoiseProceduralTexture",function(){return _.NoiseProceduralTexture}),f.d(v,"ProceduralTexture",function(){return _.ProceduralTexture}),f.d(v,"ProceduralTextureSceneComponent",function(){return _.ProceduralTextureSceneComponent}),f.d(v,"RawCubeTexture",function(){return _.RawCubeTexture}),f.d(v,"RawTexture",function(){return _.RawTexture}),f.d(v,"RawTexture2DArray",function(){return _.RawTexture2DArray}),f.d(v,"RawTexture3D",function(){return _.RawTexture3D}),f.d(v,"RefractionTexture",function(){return _.RefractionTexture}),f.d(v,"RenderTargetTexture",function(){return _.RenderTargetTexture}),f.d(v,"Texture",function(){return _.Texture}),f.d(v,"VideoTexture",function(){return _.VideoTexture}),f.d(v,"UniformBuffer",function(){return _.UniformBuffer}),f.d(v,"MaterialFlags",function(){return _.MaterialFlags}),f.d(v,"NodeMaterialBlockTargets",function(){return _.NodeMaterialBlockTargets}),f.d(v,"NodeMaterialBlockConnectionPointTypes",function(){return _.NodeMaterialBlockConnectionPointTypes}),f.d(v,"NodeMaterialBlockConnectionPointMode",function(){return _.NodeMaterialBlockConnectionPointMode}),f.d(v,"NodeMaterialSystemValues",function(){return _.NodeMaterialSystemValues}),f.d(v,"NodeMaterialModes",function(){return _.NodeMaterialModes}),f.d(v,"NodeMaterialConnectionPointCompatibilityStates",function(){return _.NodeMaterialConnectionPointCompatibilityStates}),f.d(v,"NodeMaterialConnectionPointDirection",function(){return _.NodeMaterialConnectionPointDirection}),f.d(v,"NodeMaterialConnectionPoint",function(){return _.NodeMaterialConnectionPoint}),f.d(v,"NodeMaterialBlock",function(){return _.NodeMaterialBlock}),f.d(v,"NodeMaterialDefines",function(){return _.NodeMaterialDefines}),f.d(v,"NodeMaterial",function(){return _.NodeMaterial}),f.d(v,"VertexOutputBlock",function(){return _.VertexOutputBlock}),f.d(v,"BonesBlock",function(){return _.BonesBlock}),f.d(v,"InstancesBlock",function(){return _.InstancesBlock}),f.d(v,"MorphTargetsBlock",function(){return _.MorphTargetsBlock}),f.d(v,"LightInformationBlock",function(){return _.LightInformationBlock}),f.d(v,"FragmentOutputBlock",function(){return _.FragmentOutputBlock}),f.d(v,"ImageProcessingBlock",function(){return _.ImageProcessingBlock}),f.d(v,"PerturbNormalBlock",function(){return _.PerturbNormalBlock}),f.d(v,"DiscardBlock",function(){return _.DiscardBlock}),f.d(v,"FrontFacingBlock",function(){return _.FrontFacingBlock}),f.d(v,"DerivativeBlock",function(){return _.DerivativeBlock}),f.d(v,"FragCoordBlock",function(){return _.FragCoordBlock}),f.d(v,"ScreenSizeBlock",function(){return _.ScreenSizeBlock}),f.d(v,"FogBlock",function(){return _.FogBlock}),f.d(v,"LightBlock",function(){return _.LightBlock}),f.d(v,"TextureBlock",function(){return _.TextureBlock}),f.d(v,"ReflectionTextureBlock",function(){return _.ReflectionTextureBlock}),f.d(v,"CurrentScreenBlock",function(){return _.CurrentScreenBlock}),f.d(v,"InputBlock",function(){return _.InputBlock}),f.d(v,"AnimatedInputBlockTypes",function(){return _.AnimatedInputBlockTypes}),f.d(v,"MultiplyBlock",function(){return _.MultiplyBlock}),f.d(v,"AddBlock",function(){return _.AddBlock}),f.d(v,"ScaleBlock",function(){return _.ScaleBlock}),f.d(v,"ClampBlock",function(){return _.ClampBlock}),f.d(v,"CrossBlock",function(){return _.CrossBlock}),f.d(v,"DotBlock",function(){return _.DotBlock}),f.d(v,"TransformBlock",function(){return _.TransformBlock}),f.d(v,"RemapBlock",function(){return _.RemapBlock}),f.d(v,"NormalizeBlock",function(){return _.NormalizeBlock}),f.d(v,"TrigonometryBlockOperations",function(){return _.TrigonometryBlockOperations}),f.d(v,"TrigonometryBlock",function(){return _.TrigonometryBlock}),f.d(v,"ColorMergerBlock",function(){return _.ColorMergerBlock}),f.d(v,"VectorMergerBlock",function(){return _.VectorMergerBlock}),f.d(v,"ColorSplitterBlock",function(){return _.ColorSplitterBlock}),f.d(v,"VectorSplitterBlock",function(){return _.VectorSplitterBlock}),f.d(v,"LerpBlock",function(){return _.LerpBlock}),f.d(v,"DivideBlock",function(){return _.DivideBlock}),f.d(v,"SubtractBlock",function(){return _.SubtractBlock}),f.d(v,"StepBlock",function(){return _.StepBlock}),f.d(v,"OneMinusBlock",function(){return _.OneMinusBlock}),f.d(v,"ViewDirectionBlock",function(){return _.ViewDirectionBlock}),f.d(v,"FresnelBlock",function(){return _.FresnelBlock}),f.d(v,"MaxBlock",function(){return _.MaxBlock}),f.d(v,"MinBlock",function(){return _.MinBlock}),f.d(v,"DistanceBlock",function(){return _.DistanceBlock}),f.d(v,"LengthBlock",function(){return _.LengthBlock}),f.d(v,"NegateBlock",function(){return _.NegateBlock}),f.d(v,"PowBlock",function(){return _.PowBlock}),f.d(v,"RandomNumberBlock",function(){return _.RandomNumberBlock}),f.d(v,"ArcTan2Block",function(){return _.ArcTan2Block}),f.d(v,"SmoothStepBlock",function(){return _.SmoothStepBlock}),f.d(v,"ReciprocalBlock",function(){return _.ReciprocalBlock}),f.d(v,"ReplaceColorBlock",function(){return _.ReplaceColorBlock}),f.d(v,"PosterizeBlock",function(){return _.PosterizeBlock}),f.d(v,"WaveBlockKind",function(){return _.WaveBlockKind}),f.d(v,"WaveBlock",function(){return _.WaveBlock}),f.d(v,"GradientBlockColorStep",function(){return _.GradientBlockColorStep}),f.d(v,"GradientBlock",function(){return _.GradientBlock}),f.d(v,"NLerpBlock",function(){return _.NLerpBlock}),f.d(v,"WorleyNoise3DBlock",function(){return _.WorleyNoise3DBlock}),f.d(v,"SimplexPerlin3DBlock",function(){return _.SimplexPerlin3DBlock}),f.d(v,"NormalBlendBlock",function(){return _.NormalBlendBlock}),f.d(v,"Rotate2dBlock",function(){return _.Rotate2dBlock}),f.d(v,"ReflectBlock",function(){return _.ReflectBlock}),f.d(v,"RefractBlock",function(){return _.RefractBlock}),f.d(v,"DesaturateBlock",function(){return _.DesaturateBlock}),f.d(v,"PBRMetallicRoughnessBlock",function(){return _.PBRMetallicRoughnessBlock}),f.d(v,"SheenBlock",function(){return _.SheenBlock}),f.d(v,"AnisotropyBlock",function(){return _.AnisotropyBlock}),f.d(v,"ReflectionBlock",function(){return _.ReflectionBlock}),f.d(v,"ClearCoatBlock",function(){return _.ClearCoatBlock}),f.d(v,"RefractionBlock",function(){return _.RefractionBlock}),f.d(v,"SubSurfaceBlock",function(){return _.SubSurfaceBlock}),f.d(v,"ParticleTextureBlock",function(){return _.ParticleTextureBlock}),f.d(v,"ParticleRampGradientBlock",function(){return _.ParticleRampGradientBlock}),f.d(v,"ParticleBlendMultiplyBlock",function(){return _.ParticleBlendMultiplyBlock}),f.d(v,"ModBlock",function(){return _.ModBlock}),f.d(v,"NodeMaterialOptimizer",function(){return _.NodeMaterialOptimizer}),f.d(v,"PropertyTypeForEdition",function(){return _.PropertyTypeForEdition}),f.d(v,"editableInPropertyPage",function(){return _.editableInPropertyPage}),f.d(v,"EffectRenderer",function(){return _.EffectRenderer}),f.d(v,"EffectWrapper",function(){return _.EffectWrapper}),f.d(v,"ShadowDepthWrapper",function(){return _.ShadowDepthWrapper}),f.d(v,"Scalar",function(){return _.Scalar}),f.d(v,"extractMinAndMaxIndexed",function(){return _.extractMinAndMaxIndexed}),f.d(v,"extractMinAndMax",function(){return _.extractMinAndMax}),f.d(v,"Space",function(){return _.Space}),f.d(v,"Axis",function(){return _.Axis}),f.d(v,"Coordinate",function(){return _.Coordinate}),f.d(v,"Color3",function(){return _.Color3}),f.d(v,"Color4",function(){return _.Color4}),f.d(v,"TmpColors",function(){return _.TmpColors}),f.d(v,"ToGammaSpace",function(){return _.ToGammaSpace}),f.d(v,"ToLinearSpace",function(){return _.ToLinearSpace}),f.d(v,"Epsilon",function(){return _.Epsilon}),f.d(v,"Frustum",function(){return _.Frustum}),f.d(v,"Orientation",function(){return _.Orientation}),f.d(v,"BezierCurve",function(){return _.BezierCurve}),f.d(v,"Angle",function(){return _.Angle}),f.d(v,"Arc2",function(){return _.Arc2}),f.d(v,"Path2",function(){return _.Path2}),f.d(v,"Path3D",function(){return _.Path3D}),f.d(v,"Curve3",function(){return _.Curve3}),f.d(v,"Plane",function(){return _.Plane}),f.d(v,"Size",function(){return _.Size}),f.d(v,"Vector2",function(){return _.Vector2}),f.d(v,"Vector3",function(){return _.Vector3}),f.d(v,"Vector4",function(){return _.Vector4}),f.d(v,"Quaternion",function(){return _.Quaternion}),f.d(v,"Matrix",function(){return _.Matrix}),f.d(v,"TmpVectors",function(){return _.TmpVectors}),f.d(v,"PositionNormalVertex",function(){return _.PositionNormalVertex}),f.d(v,"PositionNormalTextureVertex",function(){return _.PositionNormalTextureVertex}),f.d(v,"Viewport",function(){return _.Viewport}),f.d(v,"SphericalHarmonics",function(){return _.SphericalHarmonics}),f.d(v,"SphericalPolynomial",function(){return _.SphericalPolynomial}),f.d(v,"AbstractMesh",function(){return _.AbstractMesh}),f.d(v,"Buffer",function(){return _.Buffer}),f.d(v,"VertexBuffer",function(){return _.VertexBuffer}),f.d(v,"DracoCompression",function(){return _.DracoCompression}),f.d(v,"CSG",function(){return _.CSG}),f.d(v,"Geometry",function(){return _.Geometry}),f.d(v,"GroundMesh",function(){return _.GroundMesh}),f.d(v,"TrailMesh",function(){return _.TrailMesh}),f.d(v,"InstancedMesh",function(){return _.InstancedMesh}),f.d(v,"LinesMesh",function(){return _.LinesMesh}),f.d(v,"InstancedLinesMesh",function(){return _.InstancedLinesMesh}),f.d(v,"_CreationDataStorage",function(){return _._CreationDataStorage}),f.d(v,"_InstancesBatch",function(){return _._InstancesBatch}),f.d(v,"Mesh",function(){return _.Mesh}),f.d(v,"VertexData",function(){return _.VertexData}),f.d(v,"MeshBuilder",function(){return _.MeshBuilder}),f.d(v,"SimplificationSettings",function(){return _.SimplificationSettings}),f.d(v,"SimplificationQueue",function(){return _.SimplificationQueue}),f.d(v,"SimplificationType",function(){return _.SimplificationType}),f.d(v,"QuadraticErrorSimplification",function(){return _.QuadraticErrorSimplification}),f.d(v,"SimplicationQueueSceneComponent",function(){return _.SimplicationQueueSceneComponent}),f.d(v,"Polygon",function(){return _.Polygon}),f.d(v,"PolygonMeshBuilder",function(){return _.PolygonMeshBuilder}),f.d(v,"SubMesh",function(){return _.SubMesh}),f.d(v,"MeshLODLevel",function(){return _.MeshLODLevel}),f.d(v,"TransformNode",function(){return _.TransformNode}),f.d(v,"BoxBuilder",function(){return _.BoxBuilder}),f.d(v,"TiledBoxBuilder",function(){return _.TiledBoxBuilder}),f.d(v,"DiscBuilder",function(){return _.DiscBuilder}),f.d(v,"RibbonBuilder",function(){return _.RibbonBuilder}),f.d(v,"SphereBuilder",function(){return _.SphereBuilder}),f.d(v,"HemisphereBuilder",function(){return _.HemisphereBuilder}),f.d(v,"CylinderBuilder",function(){return _.CylinderBuilder}),f.d(v,"TorusBuilder",function(){return _.TorusBuilder}),f.d(v,"TorusKnotBuilder",function(){return _.TorusKnotBuilder}),f.d(v,"LinesBuilder",function(){return _.LinesBuilder}),f.d(v,"PolygonBuilder",function(){return _.PolygonBuilder}),f.d(v,"ShapeBuilder",function(){return _.ShapeBuilder}),f.d(v,"LatheBuilder",function(){return _.LatheBuilder}),f.d(v,"PlaneBuilder",function(){return _.PlaneBuilder}),f.d(v,"TiledPlaneBuilder",function(){return _.TiledPlaneBuilder}),f.d(v,"GroundBuilder",function(){return _.GroundBuilder}),f.d(v,"TubeBuilder",function(){return _.TubeBuilder}),f.d(v,"PolyhedronBuilder",function(){return _.PolyhedronBuilder}),f.d(v,"IcoSphereBuilder",function(){return _.IcoSphereBuilder}),f.d(v,"DecalBuilder",function(){return _.DecalBuilder}),f.d(v,"CapsuleBuilder",function(){return _.CapsuleBuilder}),f.d(v,"DataBuffer",function(){return _.DataBuffer}),f.d(v,"WebGLDataBuffer",function(){return _.WebGLDataBuffer}),f.d(v,"MorphTarget",function(){return _.MorphTarget}),f.d(v,"MorphTargetManager",function(){return _.MorphTargetManager}),f.d(v,"RecastJSPlugin",function(){return _.RecastJSPlugin}),f.d(v,"RecastJSCrowd",function(){return _.RecastJSCrowd}),f.d(v,"Node",function(){return _.Node}),f.d(v,"Database",function(){return _.Database}),f.d(v,"BaseParticleSystem",function(){return _.BaseParticleSystem}),f.d(v,"BoxParticleEmitter",function(){return _.BoxParticleEmitter}),f.d(v,"ConeParticleEmitter",function(){return _.ConeParticleEmitter}),f.d(v,"CylinderParticleEmitter",function(){return _.CylinderParticleEmitter}),f.d(v,"CylinderDirectedParticleEmitter",function(){return _.CylinderDirectedParticleEmitter}),f.d(v,"HemisphericParticleEmitter",function(){return _.HemisphericParticleEmitter}),f.d(v,"PointParticleEmitter",function(){return _.PointParticleEmitter}),f.d(v,"SphereParticleEmitter",function(){return _.SphereParticleEmitter}),f.d(v,"SphereDirectedParticleEmitter",function(){return _.SphereDirectedParticleEmitter}),f.d(v,"CustomParticleEmitter",function(){return _.CustomParticleEmitter}),f.d(v,"MeshParticleEmitter",function(){return _.MeshParticleEmitter}),f.d(v,"GPUParticleSystem",function(){return _.GPUParticleSystem}),f.d(v,"Particle",function(){return _.Particle}),f.d(v,"ParticleHelper",function(){return _.ParticleHelper}),f.d(v,"ParticleSystem",function(){return _.ParticleSystem}),f.d(v,"ParticleSystemSet",function(){return _.ParticleSystemSet}),f.d(v,"SolidParticle",function(){return _.SolidParticle}),f.d(v,"ModelShape",function(){return _.ModelShape}),f.d(v,"DepthSortedParticle",function(){return _.DepthSortedParticle}),f.d(v,"SolidParticleVertex",function(){return _.SolidParticleVertex}),f.d(v,"SolidParticleSystem",function(){return _.SolidParticleSystem}),f.d(v,"CloudPoint",function(){return _.CloudPoint}),f.d(v,"PointsGroup",function(){return _.PointsGroup}),f.d(v,"PointColor",function(){return _.PointColor}),f.d(v,"PointsCloudSystem",function(){return _.PointsCloudSystem}),f.d(v,"SubEmitterType",function(){return _.SubEmitterType}),f.d(v,"SubEmitter",function(){return _.SubEmitter}),f.d(v,"PhysicsEngine",function(){return _.PhysicsEngine}),f.d(v,"PhysicsEngineSceneComponent",function(){return _.PhysicsEngineSceneComponent}),f.d(v,"PhysicsHelper",function(){return _.PhysicsHelper}),f.d(v,"PhysicsRadialExplosionEventOptions",function(){return _.PhysicsRadialExplosionEventOptions}),f.d(v,"PhysicsUpdraftEventOptions",function(){return _.PhysicsUpdraftEventOptions}),f.d(v,"PhysicsVortexEventOptions",function(){return _.PhysicsVortexEventOptions}),f.d(v,"PhysicsRadialImpulseFalloff",function(){return _.PhysicsRadialImpulseFalloff}),f.d(v,"PhysicsUpdraftMode",function(){return _.PhysicsUpdraftMode}),f.d(v,"PhysicsImpostor",function(){return _.PhysicsImpostor}),f.d(v,"PhysicsJoint",function(){return _.PhysicsJoint}),f.d(v,"DistanceJoint",function(){return _.DistanceJoint}),f.d(v,"MotorEnabledJoint",function(){return _.MotorEnabledJoint}),f.d(v,"HingeJoint",function(){return _.HingeJoint}),f.d(v,"Hinge2Joint",function(){return _.Hinge2Joint}),f.d(v,"CannonJSPlugin",function(){return _.CannonJSPlugin}),f.d(v,"AmmoJSPlugin",function(){return _.AmmoJSPlugin}),f.d(v,"OimoJSPlugin",function(){return _.OimoJSPlugin}),f.d(v,"AnaglyphPostProcess",function(){return _.AnaglyphPostProcess}),f.d(v,"BlackAndWhitePostProcess",function(){return _.BlackAndWhitePostProcess}),f.d(v,"BloomEffect",function(){return _.BloomEffect}),f.d(v,"BloomMergePostProcess",function(){return _.BloomMergePostProcess}),f.d(v,"BlurPostProcess",function(){return _.BlurPostProcess}),f.d(v,"ChromaticAberrationPostProcess",function(){return _.ChromaticAberrationPostProcess}),f.d(v,"CircleOfConfusionPostProcess",function(){return _.CircleOfConfusionPostProcess}),f.d(v,"ColorCorrectionPostProcess",function(){return _.ColorCorrectionPostProcess}),f.d(v,"ConvolutionPostProcess",function(){return _.ConvolutionPostProcess}),f.d(v,"DepthOfFieldBlurPostProcess",function(){return _.DepthOfFieldBlurPostProcess}),f.d(v,"DepthOfFieldEffectBlurLevel",function(){return _.DepthOfFieldEffectBlurLevel}),f.d(v,"DepthOfFieldEffect",function(){return _.DepthOfFieldEffect}),f.d(v,"DepthOfFieldMergePostProcessOptions",function(){return _.DepthOfFieldMergePostProcessOptions}),f.d(v,"DepthOfFieldMergePostProcess",function(){return _.DepthOfFieldMergePostProcess}),f.d(v,"DisplayPassPostProcess",function(){return _.DisplayPassPostProcess}),f.d(v,"ExtractHighlightsPostProcess",function(){return _.ExtractHighlightsPostProcess}),f.d(v,"FilterPostProcess",function(){return _.FilterPostProcess}),f.d(v,"FxaaPostProcess",function(){return _.FxaaPostProcess}),f.d(v,"GrainPostProcess",function(){return _.GrainPostProcess}),f.d(v,"HighlightsPostProcess",function(){return _.HighlightsPostProcess}),f.d(v,"ImageProcessingPostProcess",function(){return _.ImageProcessingPostProcess}),f.d(v,"MotionBlurPostProcess",function(){return _.MotionBlurPostProcess}),f.d(v,"PassPostProcess",function(){return _.PassPostProcess}),f.d(v,"PassCubePostProcess",function(){return _.PassCubePostProcess}),f.d(v,"PostProcess",function(){return _.PostProcess}),f.d(v,"PostProcessManager",function(){return _.PostProcessManager}),f.d(v,"RefractionPostProcess",function(){return _.RefractionPostProcess}),f.d(v,"DefaultRenderingPipeline",function(){return _.DefaultRenderingPipeline}),f.d(v,"LensRenderingPipeline",function(){return _.LensRenderingPipeline}),f.d(v,"SSAO2RenderingPipeline",function(){return _.SSAO2RenderingPipeline}),f.d(v,"SSAORenderingPipeline",function(){return _.SSAORenderingPipeline}),f.d(v,"StandardRenderingPipeline",function(){return _.StandardRenderingPipeline}),f.d(v,"PostProcessRenderEffect",function(){return _.PostProcessRenderEffect}),f.d(v,"PostProcessRenderPipeline",function(){return _.PostProcessRenderPipeline}),f.d(v,"PostProcessRenderPipelineManager",function(){return _.PostProcessRenderPipelineManager}),f.d(v,"PostProcessRenderPipelineManagerSceneComponent",function(){return _.PostProcessRenderPipelineManagerSceneComponent}),f.d(v,"SharpenPostProcess",function(){return _.SharpenPostProcess}),f.d(v,"StereoscopicInterlacePostProcessI",function(){return _.StereoscopicInterlacePostProcessI}),f.d(v,"StereoscopicInterlacePostProcess",function(){return _.StereoscopicInterlacePostProcess}),f.d(v,"TonemappingOperator",function(){return _.TonemappingOperator}),f.d(v,"TonemapPostProcess",function(){return _.TonemapPostProcess}),f.d(v,"VolumetricLightScatteringPostProcess",function(){return _.VolumetricLightScatteringPostProcess}),f.d(v,"VRDistortionCorrectionPostProcess",function(){return _.VRDistortionCorrectionPostProcess}),f.d(v,"VRMultiviewToSingleviewPostProcess",function(){return _.VRMultiviewToSingleviewPostProcess}),f.d(v,"ScreenSpaceReflectionPostProcess",function(){return _.ScreenSpaceReflectionPostProcess}),f.d(v,"ScreenSpaceCurvaturePostProcess",function(){return _.ScreenSpaceCurvaturePostProcess}),f.d(v,"ReflectionProbe",function(){return _.ReflectionProbe}),f.d(v,"BoundingBoxRenderer",function(){return _.BoundingBoxRenderer}),f.d(v,"DepthRenderer",function(){return _.DepthRenderer}),f.d(v,"DepthRendererSceneComponent",function(){return _.DepthRendererSceneComponent}),f.d(v,"EdgesRenderer",function(){return _.EdgesRenderer}),f.d(v,"LineEdgesRenderer",function(){return _.LineEdgesRenderer}),f.d(v,"GeometryBufferRenderer",function(){return _.GeometryBufferRenderer}),f.d(v,"GeometryBufferRendererSceneComponent",function(){return _.GeometryBufferRendererSceneComponent}),f.d(v,"PrePassRenderer",function(){return _.PrePassRenderer}),f.d(v,"PrePassRendererSceneComponent",function(){return _.PrePassRendererSceneComponent}),f.d(v,"SubSurfaceSceneComponent",function(){return _.SubSurfaceSceneComponent}),f.d(v,"OutlineRenderer",function(){return _.OutlineRenderer}),f.d(v,"RenderingGroup",function(){return _.RenderingGroup}),f.d(v,"RenderingGroupInfo",function(){return _.RenderingGroupInfo}),f.d(v,"RenderingManager",function(){return _.RenderingManager}),f.d(v,"UtilityLayerRenderer",function(){return _.UtilityLayerRenderer}),f.d(v,"Scene",function(){return _.Scene}),f.d(v,"SceneComponentConstants",function(){return _.SceneComponentConstants}),f.d(v,"Stage",function(){return _.Stage}),f.d(v,"Sprite",function(){return _.Sprite}),f.d(v,"SpriteManager",function(){return _.SpriteManager}),f.d(v,"SpriteMap",function(){return _.SpriteMap}),f.d(v,"SpritePackedManager",function(){return _.SpritePackedManager}),f.d(v,"SpriteSceneComponent",function(){return _.SpriteSceneComponent}),f.d(v,"AlphaState",function(){return _.AlphaState}),f.d(v,"DepthCullingState",function(){return _.DepthCullingState}),f.d(v,"StencilState",function(){return _.StencilState}),f.d(v,"AndOrNotEvaluator",function(){return _.AndOrNotEvaluator}),f.d(v,"AssetTaskState",function(){return _.AssetTaskState}),f.d(v,"AbstractAssetTask",function(){return _.AbstractAssetTask}),f.d(v,"AssetsProgressEvent",function(){return _.AssetsProgressEvent}),f.d(v,"ContainerAssetTask",function(){return _.ContainerAssetTask}),f.d(v,"MeshAssetTask",function(){return _.MeshAssetTask}),f.d(v,"TextFileAssetTask",function(){return _.TextFileAssetTask}),f.d(v,"BinaryFileAssetTask",function(){return _.BinaryFileAssetTask}),f.d(v,"ImageAssetTask",function(){return _.ImageAssetTask}),f.d(v,"TextureAssetTask",function(){return _.TextureAssetTask}),f.d(v,"CubeTextureAssetTask",function(){return _.CubeTextureAssetTask}),f.d(v,"HDRCubeTextureAssetTask",function(){return _.HDRCubeTextureAssetTask}),f.d(v,"EquiRectangularCubeTextureAssetTask",function(){return _.EquiRectangularCubeTextureAssetTask}),f.d(v,"AssetsManager",function(){return _.AssetsManager}),f.d(v,"BasisTranscodeConfiguration",function(){return _.BasisTranscodeConfiguration}),f.d(v,"BasisTools",function(){return _.BasisTools}),f.d(v,"DDSTools",function(){return _.DDSTools}),f.d(v,"expandToProperty",function(){return _.expandToProperty}),f.d(v,"serialize",function(){return _.serialize}),f.d(v,"serializeAsTexture",function(){return _.serializeAsTexture}),f.d(v,"serializeAsColor3",function(){return _.serializeAsColor3}),f.d(v,"serializeAsFresnelParameters",function(){return _.serializeAsFresnelParameters}),f.d(v,"serializeAsVector2",function(){return _.serializeAsVector2}),f.d(v,"serializeAsVector3",function(){return _.serializeAsVector3}),f.d(v,"serializeAsMeshReference",function(){return _.serializeAsMeshReference}),f.d(v,"serializeAsColorCurves",function(){return _.serializeAsColorCurves}),f.d(v,"serializeAsColor4",function(){return _.serializeAsColor4}),f.d(v,"serializeAsImageProcessingConfiguration",function(){return _.serializeAsImageProcessingConfiguration}),f.d(v,"serializeAsQuaternion",function(){return _.serializeAsQuaternion}),f.d(v,"serializeAsMatrix",function(){return _.serializeAsMatrix}),f.d(v,"serializeAsCameraReference",function(){return _.serializeAsCameraReference}),f.d(v,"SerializationHelper",function(){return _.SerializationHelper}),f.d(v,"Deferred",function(){return _.Deferred}),f.d(v,"EnvironmentTextureTools",function(){return _.EnvironmentTextureTools}),f.d(v,"MeshExploder",function(){return _.MeshExploder}),f.d(v,"FilesInput",function(){return _.FilesInput}),f.d(v,"CubeMapToSphericalPolynomialTools",function(){return _.CubeMapToSphericalPolynomialTools}),f.d(v,"HDRTools",function(){return _.HDRTools}),f.d(v,"PanoramaToCubeMapTools",function(){return _.PanoramaToCubeMapTools}),f.d(v,"KhronosTextureContainer",function(){return _.KhronosTextureContainer}),f.d(v,"EventState",function(){return _.EventState}),f.d(v,"Observer",function(){return _.Observer}),f.d(v,"MultiObserver",function(){return _.MultiObserver}),f.d(v,"Observable",function(){return _.Observable}),f.d(v,"PerformanceMonitor",function(){return _.PerformanceMonitor}),f.d(v,"RollingAverage",function(){return _.RollingAverage}),f.d(v,"PromisePolyfill",function(){return _.PromisePolyfill}),f.d(v,"SceneOptimization",function(){return _.SceneOptimization}),f.d(v,"TextureOptimization",function(){return _.TextureOptimization}),f.d(v,"HardwareScalingOptimization",function(){return _.HardwareScalingOptimization}),f.d(v,"ShadowsOptimization",function(){return _.ShadowsOptimization}),f.d(v,"PostProcessesOptimization",function(){return _.PostProcessesOptimization}),f.d(v,"LensFlaresOptimization",function(){return _.LensFlaresOptimization}),f.d(v,"CustomOptimization",function(){return _.CustomOptimization}),f.d(v,"ParticlesOptimization",function(){return _.ParticlesOptimization}),f.d(v,"RenderTargetsOptimization",function(){return _.RenderTargetsOptimization}),f.d(v,"MergeMeshesOptimization",function(){return _.MergeMeshesOptimization}),f.d(v,"SceneOptimizerOptions",function(){return _.SceneOptimizerOptions}),f.d(v,"SceneOptimizer",function(){return _.SceneOptimizer}),f.d(v,"SceneSerializer",function(){return _.SceneSerializer}),f.d(v,"SmartArray",function(){return _.SmartArray}),f.d(v,"SmartArrayNoDuplicate",function(){return _.SmartArrayNoDuplicate}),f.d(v,"StringDictionary",function(){return _.StringDictionary}),f.d(v,"Tags",function(){return _.Tags}),f.d(v,"TextureTools",function(){return _.TextureTools}),f.d(v,"TGATools",function(){return _.TGATools}),f.d(v,"Tools",function(){return _.Tools}),f.d(v,"className",function(){return _.className}),f.d(v,"AsyncLoop",function(){return _.AsyncLoop}),f.d(v,"VideoRecorder",function(){return _.VideoRecorder}),f.d(v,"JoystickAxis",function(){return _.JoystickAxis}),f.d(v,"VirtualJoystick",function(){return _.VirtualJoystick}),f.d(v,"WorkerPool",function(){return _.WorkerPool}),f.d(v,"Logger",function(){return _.Logger}),f.d(v,"_TypeStore",function(){return _._TypeStore}),f.d(v,"FilesInputStore",function(){return _.FilesInputStore}),f.d(v,"DeepCopier",function(){return _.DeepCopier}),f.d(v,"PivotTools",function(){return _.PivotTools}),f.d(v,"PrecisionDate",function(){return _.PrecisionDate}),f.d(v,"ScreenshotTools",function(){return _.ScreenshotTools}),f.d(v,"WebRequest",function(){return _.WebRequest}),f.d(v,"InspectableType",function(){return _.InspectableType}),f.d(v,"BRDFTextureTools",function(){return _.BRDFTextureTools}),f.d(v,"RGBDTextureTools",function(){return _.RGBDTextureTools}),f.d(v,"ColorGradient",function(){return _.ColorGradient}),f.d(v,"Color3Gradient",function(){return _.Color3Gradient}),f.d(v,"FactorGradient",function(){return _.FactorGradient}),f.d(v,"GradientHelper",function(){return _.GradientHelper}),f.d(v,"PerfCounter",function(){return _.PerfCounter}),f.d(v,"RetryStrategy",function(){return _.RetryStrategy}),f.d(v,"CanvasGenerator",function(){return _.CanvasGenerator}),f.d(v,"LoadFileError",function(){return _.LoadFileError}),f.d(v,"RequestFileError",function(){return _.RequestFileError}),f.d(v,"ReadFileError",function(){return _.ReadFileError}),f.d(v,"FileTools",function(){return _.FileTools}),f.d(v,"StringTools",function(){return _.StringTools}),f.d(v,"DataReader",function(){return _.DataReader}),f.d(v,"MinMaxReducer",function(){return _.MinMaxReducer}),f.d(v,"DepthReducer",function(){return _.DepthReducer}),f.d(v,"DataStorage",function(){return _.DataStorage}),f.d(v,"SceneRecorder",function(){return _.SceneRecorder}),f.d(v,"KhronosTextureContainer2",function(){return _.KhronosTextureContainer2}),f.d(v,"Trajectory",function(){return _.Trajectory}),f.d(v,"TrajectoryClassifier",function(){return _.TrajectoryClassifier}),f.d(v,"TimerState",function(){return _.TimerState}),f.d(v,"setAndStartTimer",function(){return _.setAndStartTimer}),f.d(v,"AdvancedTimer",function(){return _.AdvancedTimer}),f.d(v,"CopyTools",function(){return _.CopyTools}),f.d(v,"WebXRCamera",function(){return _.WebXRCamera}),f.d(v,"WebXREnterExitUIButton",function(){return _.WebXREnterExitUIButton}),f.d(v,"WebXREnterExitUIOptions",function(){return _.WebXREnterExitUIOptions}),f.d(v,"WebXREnterExitUI",function(){return _.WebXREnterExitUI}),f.d(v,"WebXRExperienceHelper",function(){return _.WebXRExperienceHelper}),f.d(v,"WebXRInput",function(){return _.WebXRInput}),f.d(v,"WebXRInputSource",function(){return _.WebXRInputSource}),f.d(v,"WebXRManagedOutputCanvasOptions",function(){return _.WebXRManagedOutputCanvasOptions}),f.d(v,"WebXRManagedOutputCanvas",function(){return _.WebXRManagedOutputCanvas}),f.d(v,"WebXRState",function(){return _.WebXRState}),f.d(v,"WebXRTrackingState",function(){return _.WebXRTrackingState}),f.d(v,"WebXRSessionManager",function(){return _.WebXRSessionManager}),f.d(v,"WebXRDefaultExperienceOptions",function(){return _.WebXRDefaultExperienceOptions}),f.d(v,"WebXRDefaultExperience",function(){return _.WebXRDefaultExperience}),f.d(v,"WebXRFeatureName",function(){return _.WebXRFeatureName}),f.d(v,"WebXRFeaturesManager",function(){return _.WebXRFeaturesManager}),f.d(v,"WebXRAbstractFeature",function(){return _.WebXRAbstractFeature}),f.d(v,"WebXRHitTestLegacy",function(){return _.WebXRHitTestLegacy}),f.d(v,"WebXRAnchorSystem",function(){return _.WebXRAnchorSystem}),f.d(v,"WebXRPlaneDetector",function(){return _.WebXRPlaneDetector}),f.d(v,"WebXRBackgroundRemover",function(){return _.WebXRBackgroundRemover}),f.d(v,"WebXRMotionControllerTeleportation",function(){return _.WebXRMotionControllerTeleportation}),f.d(v,"WebXRControllerPointerSelection",function(){return _.WebXRControllerPointerSelection}),f.d(v,"IWebXRControllerPhysicsOptions",function(){return _.IWebXRControllerPhysicsOptions}),f.d(v,"WebXRControllerPhysics",function(){return _.WebXRControllerPhysics}),f.d(v,"WebXRHitTest",function(){return _.WebXRHitTest}),f.d(v,"WebXRFeaturePointSystem",function(){return _.WebXRFeaturePointSystem}),f.d(v,"WebXRHand",function(){return _.WebXRHand}),f.d(v,"WebXRHandTracking",function(){return _.WebXRHandTracking}),f.d(v,"WebXRAbstractMotionController",function(){return _.WebXRAbstractMotionController}),f.d(v,"WebXRControllerComponent",function(){return _.WebXRControllerComponent}),f.d(v,"WebXRGenericTriggerMotionController",function(){return _.WebXRGenericTriggerMotionController}),f.d(v,"WebXRMicrosoftMixedRealityController",function(){return _.WebXRMicrosoftMixedRealityController}),f.d(v,"WebXRMotionControllerManager",function(){return _.WebXRMotionControllerManager}),f.d(v,"WebXROculusTouchMotionController",function(){return _.WebXROculusTouchMotionController}),f.d(v,"WebXRHTCViveMotionController",function(){return _.WebXRHTCViveMotionController}),f.d(v,"WebXRProfiledMotionController",function(){return _.WebXRProfiledMotionController});var u=B!==void 0?B:typeof window<"u"?window:void 0;if(u!==void 0){u.BABYLON=M,u.BABYLON=u.BABYLON||{};var M=u.BABYLON;M.Debug=M.Debug||{};var R=[];for(var C in x)M.Debug[C]=x[C],R.push(C);for(var C in _)M[C]=_[C]}var m={AxesViewer:x.AxesViewer,BoneAxesViewer:x.BoneAxesViewer,PhysicsViewer:x.PhysicsViewer,SkeletonViewer:x.SkeletonViewer}}.call(this,f(159))}])})})(kf);var _i=kf.exports;const Gf=(Qe,ke,Ae)=>{Qe.createDefaultCamera(!0,!0,!0);var v=Qe.activeCamera;ke[0]!==null&&(v.alpha=_i.Tools.ToRadians(ke[0])),ke[1]!==null&&(v.beta=_i.Tools.ToRadians(ke[1])),ke[2]!==null&&(v.radius=ke[2]),v.panningSensibility=0,v.attachControl(!1,!1,-1),v.pinchToPanMaxDistance=0,v.wheelPrecision=2500/Ae},zf=(Qe,ke,Ae,v,f,B,_)=>{if(ke&&!ke.isDisposed&&Ae&&(ke.dispose(),Ae.dispose()),Ae=new _i.Engine(Qe,!0),ke=new _i.Scene(Ae),ke.createDefaultCameraOrLight(),ke.clearColor=ke.clearColor=new _i.Color4(...f),Ae.runRenderLoop(()=>{ke.render()}),window.addEventListener("resize",()=>{Ae.resize()}),!v)return ke;let x;return x=v.url,_i.SceneLoader.ShowLoadingScreen=!1,_i.SceneLoader.Append(x,"",ke,()=>Gf(ke,B,_),void 0,void 0,"."+v.path.split(".")[1]),ke},jf=(Qe,ke,Ae)=>{Qe.removeCamera(Qe.activeCamera),Gf(Qe,ke,Ae)};var Hf={exports:{}};(function(Qe,ke){(function(Ae,v){Qe.exports=v(_i)})(typeof self<"u"?self:typeof Qr<"u"?Qr:Qr,function(Ae){return function(v){var f={};function B(_){if(f[_])return f[_].exports;var x=f[_]={i:_,l:!1,exports:{}};return v[_].call(x.exports,x,x.exports,B),x.l=!0,x.exports}return B.m=v,B.c=f,B.d=function(_,x,u){B.o(_,x)||Object.defineProperty(_,x,{enumerable:!0,get:u})},B.r=function(_){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(_,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(_,"__esModule",{value:!0})},B.t=function(_,x){if(1&x&&(_=B(_)),8&x||4&x&&typeof _=="object"&&_&&_.__esModule)return _;var u=Object.create(null);if(B.r(u),Object.defineProperty(u,"default",{enumerable:!0,value:_}),2&x&&typeof _!="string")for(var M in _)B.d(u,M,function(R){return _[R]}.bind(null,M));return u},B.n=function(_){var x=_&&_.__esModule?function(){return _.default}:function(){return _};return B.d(x,"a",x),x},B.o=function(_,x){return Object.prototype.hasOwnProperty.call(_,x)},B.p="",B(B.s=20)}([function(v,f){v.exports=Ae},function(v,f,B){B.d(f,"a",function(){return u}),B.d(f,"b",function(){return M});var _=B(0),x=B(2),u=function(){function R(){}return R.Get=function(C,m,c){if(!m||c==null||!m[c])throw new Error(C+": Failed to find index ("+c+")");return m[c]},R.Assign=function(C){if(C)for(var m=0;m "+x.GLTFLoaderState[x.GLTFLoaderState.READY],A=x.GLTFLoaderState[x.GLTFLoaderState.LOADING]+" => "+x.GLTFLoaderState[x.GLTFLoaderState.COMPLETE];c._parent._startPerformanceCounter(E),c._parent._startPerformanceCounter(A),c._setState(x.GLTFLoaderState.LOADING),c._extensionsOnLoading();var S=new Array,g=c._babylonScene.blockMaterialDirtyMechanism;if(c._babylonScene.blockMaterialDirtyMechanism=!0,C)S.push(c.loadSceneAsync("/nodes",{nodes:C,index:-1}));else if(c._gltf.scene!=null||c._gltf.scenes&&c._gltf.scenes[0]){var l=u.Get("/scene",c._gltf.scenes,c._gltf.scene||0);S.push(c.loadSceneAsync("/scenes/"+l.index,l))}if(c.parent.loadAllMaterials&&c._gltf.materials)for(var h=0;hC.bin.byteLength)&&_.Logger.Warn("Binary buffer length ("+c.byteLength+") from JSON does not match chunk length ("+C.bin.byteLength+")"),this._bin=C.bin}else _.Logger.Warn("Unexpected BIN chunk")}},R.prototype._setupData=function(){if(u.Assign(this._gltf.accessors),u.Assign(this._gltf.animations),u.Assign(this._gltf.buffers),u.Assign(this._gltf.bufferViews),u.Assign(this._gltf.cameras),u.Assign(this._gltf.images),u.Assign(this._gltf.materials),u.Assign(this._gltf.meshes),u.Assign(this._gltf.nodes),u.Assign(this._gltf.samplers),u.Assign(this._gltf.scenes),u.Assign(this._gltf.skins),u.Assign(this._gltf.textures),this._gltf.nodes){for(var C={},m=0,c=this._gltf.nodes;m=2)throw new Error(C+"/texCoord: Invalid value ("+m.texCoord+")");var S=u.Get(C+"/index",this._gltf.textures,m.index);S._textureInfo=m;var g=this._loadTextureAsync("/textures/"+m.index,S,function(l){l.coordinatesIndex=m.texCoord||0,R.AddPointerMetadata(l,C),E._parent.onTextureLoadedObservable.notifyObservers(l),c(l)});return this.logClose(),g},R.prototype._loadTextureAsync=function(C,m,c){c===void 0&&(c=function(){});var E=this._extensionsLoadTextureAsync(C,m,c);if(E)return E;this.logOpen(C+" "+(m.name||""));var A=m.sampler==null?R.DefaultSampler:u.Get(C+"/sampler",this._gltf.samplers,m.sampler),S=u.Get(C+"/source",this._gltf.images,m.source),g=this._createTextureAsync(C,A,S,c);return this.logClose(),g},R.prototype._createTextureAsync=function(C,m,c,E,A){var S=this;E===void 0&&(E=function(){});var g=this._loadSampler("/samplers/"+m.index,m),l=new Array,h=new _.Deferred;this._babylonScene._blockEntityCollection=this._forAssetContainer;var b=new _.Texture(null,this._babylonScene,g.noMipMaps,!1,g.samplingMode,function(){S._disposed||h.resolve()},function(T,D){S._disposed||h.reject(new Error(C+": "+(D&&D.message?D.message:T||"Failed to load texture")))},void 0,void 0,void 0,c.mimeType,A);return this._babylonScene._blockEntityCollection=!1,l.push(h.promise),l.push(this.loadImageAsync("/images/"+c.index,c).then(function(T){var D=c.uri||S._fileName+"#image"+c.index,w="data:"+S._uniqueRootUrl+D;b.updateURL(w,T)})),b.wrapU=g.wrapU,b.wrapV=g.wrapV,E(b),Promise.all(l).then(function(){return b})},R.prototype._loadSampler=function(C,m){return m._data||(m._data={noMipMaps:m.minFilter===9728||m.minFilter===9729,samplingMode:R._GetTextureSamplingMode(C,m),wrapU:R._GetTextureWrapMode(C+"/wrapS",m.wrapS),wrapV:R._GetTextureWrapMode(C+"/wrapT",m.wrapT)}),m._data},R.prototype.loadImageAsync=function(C,m){if(!m._data){if(this.logOpen(C+" "+(m.name||"")),m.uri)m._data=this.loadUriAsync(C+"/uri",m,m.uri);else{var c=u.Get(C+"/bufferView",this._gltf.bufferViews,m.bufferView);m._data=this.loadBufferViewAsync("/bufferViews/"+c.index,c)}this.logClose()}return m._data},R.prototype.loadUriAsync=function(C,m,c){var E=this,A=this._extensionsLoadUriAsync(C,m,c);if(A)return A;if(!R._ValidateUri(c))throw new Error(C+": '"+c+"' is invalid");if(_.Tools.IsBase64(c)){var S=new Uint8Array(_.Tools.DecodeBase64(c));return this.log("Decoded "+c.substr(0,64)+"... ("+S.length+" bytes)"),Promise.resolve(S)}return this.log("Loading "+c),this._parent.preprocessUrlAsync(this._rootUrl+c).then(function(g){return new Promise(function(l,h){E._parent._loadFile(g,E._babylonScene,function(b){E._disposed||(E.log("Loaded "+c+" ("+b.byteLength+" bytes)"),l(new Uint8Array(b)))},!0,function(b){h(new _.LoadFileError(C+": Failed to load '"+c+"'"+(b?": "+b.status+" "+b.statusText:""),b))})})})},R.AddPointerMetadata=function(C,m){var c=C.metadata=C.metadata||{},E=c.gltf=c.gltf||{};(E.pointers=E.pointers||[]).push(m)},R._GetTextureWrapMode=function(C,m){switch(m=m??10497){case 33071:return _.Texture.CLAMP_ADDRESSMODE;case 33648:return _.Texture.MIRROR_ADDRESSMODE;case 10497:return _.Texture.WRAP_ADDRESSMODE;default:return _.Logger.Warn(C+": Invalid value ("+m+")"),_.Texture.WRAP_ADDRESSMODE}},R._GetTextureSamplingMode=function(C,m){var c=m.magFilter==null?9729:m.magFilter,E=m.minFilter==null?9987:m.minFilter;if(c===9729)switch(E){case 9728:return _.Texture.LINEAR_NEAREST;case 9729:return _.Texture.LINEAR_LINEAR;case 9984:return _.Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return _.Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return _.Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return _.Texture.LINEAR_LINEAR_MIPLINEAR;default:return _.Logger.Warn(C+"/minFilter: Invalid value ("+E+")"),_.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(c!==9728&&_.Logger.Warn(C+"/magFilter: Invalid value ("+c+")"),E){case 9728:return _.Texture.NEAREST_NEAREST;case 9729:return _.Texture.NEAREST_LINEAR;case 9984:return _.Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return _.Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return _.Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return _.Texture.NEAREST_LINEAR_MIPLINEAR;default:return _.Logger.Warn(C+"/minFilter: Invalid value ("+E+")"),_.Texture.NEAREST_NEAREST_MIPNEAREST}},R._GetTypedArrayConstructor=function(C,m){switch(m){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(C+": Invalid component type "+m)}},R._GetTypedArray=function(C,m,c,E,A){var S=c.buffer;E=c.byteOffset+(E||0);var g=R._GetTypedArrayConstructor(C+"/componentType",m);try{return new g(S,E,A)}catch(l){throw new Error(C+": "+l)}},R._GetNumComponents=function(C,m){switch(m){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(C+": Invalid type ("+m+")")},R._ValidateUri=function(C){return _.Tools.IsBase64(C)||C.indexOf("..")===-1},R._GetDrawMode=function(C,m){switch(m==null&&(m=4),m){case 0:return _.Material.PointListDrawMode;case 1:return _.Material.LineListDrawMode;case 2:return _.Material.LineLoopDrawMode;case 3:return _.Material.LineStripDrawMode;case 4:return _.Material.TriangleFillMode;case 5:return _.Material.TriangleStripDrawMode;case 6:return _.Material.TriangleFanDrawMode}throw new Error(C+": Invalid mesh primitive mode ("+m+")")},R.prototype._compileMaterialsAsync=function(){var C=this;this._parent._startPerformanceCounter("Compile materials");var m=new Array;if(this._gltf.materials)for(var c=0,E=this._gltf.materials;c-1&&h.materials.splice(N,1),(N=b.indexOf(w))>-1&&b.splice(N,1)})});var T=[];l.onTextureLoadedObservable.add(function(w){T.push(w),w.onDisposeObservable.addOnce(function(){var N=h.textures.indexOf(w);N>-1&&h.textures.splice(N,1),(N=T.indexOf(w))>-1&&T.splice(N,1)})});var D=[];return l.onCameraLoadedObservable.add(function(w){D.push(w)}),l._loader.importMeshAsync(null,c,!0,E,A,S,g).then(function(w){return Array.prototype.push.apply(h.geometries,w.geometries),Array.prototype.push.apply(h.meshes,w.meshes),Array.prototype.push.apply(h.particleSystems,w.particleSystems),Array.prototype.push.apply(h.skeletons,w.skeletons),Array.prototype.push.apply(h.animationGroups,w.animationGroups),Array.prototype.push.apply(h.materials,b),Array.prototype.push.apply(h.textures,T),Array.prototype.push.apply(h.lights,w.lights),Array.prototype.push.apply(h.transformNodes,w.transformNodes),Array.prototype.push.apply(h.cameras,D),h})})},m.prototype.canDirectLoad=function(c){return c.indexOf("asset")!==-1&&c.indexOf("version")!==-1||M.StringTools.StartsWith(c,"data:base64,"+m.magicBase64Encoded)||M.StringTools.StartsWith(c,"data:application/octet-stream;base64,"+m.magicBase64Encoded)||M.StringTools.StartsWith(c,"data:model/gltf-binary;base64,"+m.magicBase64Encoded)},m.prototype.directLoad=function(c,E){if(M.StringTools.StartsWith(E,"base64,"+m.magicBase64Encoded)||M.StringTools.StartsWith(E,"application/octet-stream;base64,"+m.magicBase64Encoded)||M.StringTools.StartsWith(E,"model/gltf-binary;base64,"+m.magicBase64Encoded)){var A=M.Tools.DecodeBase64(E);return this._validate(c,A),this._unpackBinaryAsync(new M.DataReader({readAsync:function(S,g){return Promise.resolve(new Uint8Array(A,S,g))},byteLength:A.byteLength}))}return this._validate(c,E),Promise.resolve({json:this._parseJson(E)})},m.prototype.createPlugin=function(){return new m},Object.defineProperty(m.prototype,"loaderState",{get:function(){return this._loader?this._loader.state:null},enumerable:!1,configurable:!0}),m.prototype.whenCompleteAsync=function(){var c=this;return new Promise(function(E,A){c.onCompleteObservable.addOnce(function(){E()}),c.onErrorObservable.addOnce(function(S){A(S)})})},m.prototype._loadFile=function(c,E,A,S,g){var l=this,h=E._loadFile(c,A,function(b){l._onProgress(b,h)},void 0,S,g);return h.onCompleteObservable.add(function(b){l._requests.splice(l._requests.indexOf(b),1)}),this._requests.push(h),h},m.prototype._requestFile=function(c,E,A,S,g,l){var h=this,b=E._requestFile(c,A,function(T){h._onProgress(T,b)},void 0,S,g,l);return b.onCompleteObservable.add(function(T){h._requests.splice(h._requests.indexOf(T),1)}),this._requests.push(b),b},m.prototype._onProgress=function(c,E){if(this._progressCallback){E._lengthComputable=c.lengthComputable,E._loaded=c.loaded,E._total=c.total;for(var A=!0,S=0,g=0,l=0,h=this._requests;l0)throw new Error("Incompatible minimum version: "+E.minVersion)}var g={1:m._CreateGLTF1Loader,2:m._CreateGLTF2Loader}[A.major];if(!g)throw new Error("Unsupported version: "+E.version);return g(this)},m.prototype._parseJson=function(c){this._startPerformanceCounter("Parse JSON"),this._log("JSON length: "+c.length);var E=JSON.parse(c);return this._endPerformanceCounter("Parse JSON"),E},m.prototype._unpackBinaryAsync=function(c){var E=this;return this._startPerformanceCounter("Unpack Binary"),c.loadAsync(20).then(function(){var A=c.readUint32();if(A!==1179937895)throw new Error("Unexpected magic: "+A);var S=c.readUint32();E.loggingEnabled&&E._log("Binary version: "+S);var g,l=c.readUint32();if(c.buffer.byteLength!==0&&l!==c.buffer.byteLength)throw new Error("Length in header does not match actual data length: "+l+" != "+c.buffer.byteLength);switch(S){case 1:g=E._unpackBinaryV1Async(c,l);break;case 2:g=E._unpackBinaryV2Async(c,l);break;default:throw new Error("Unsupported version: "+S)}return E._endPerformanceCounter("Unpack Binary"),g})},m.prototype._unpackBinaryV1Async=function(c,E){var A=c.readUint32(),S=c.readUint32();if(S!==0)throw new Error("Unexpected content format: "+S);var g=E-c.byteOffset,l={json:this._parseJson(c.readString(A)),bin:null};if(g!==0){var h=c.byteOffset;l.bin={readAsync:function(b,T){return c.buffer.readAsync(h+b,T)},byteLength:g}}return Promise.resolve(l)},m.prototype._unpackBinaryV2Async=function(c,E){var A=this,S=1313821514,g=5130562,l=c.readUint32();if(c.readUint32()!==S)throw new Error("First chunk format is not JSON");return c.byteOffset+l===E?c.loadAsync(l).then(function(){return{json:A._parseJson(c.readString(l)),bin:null}}):c.loadAsync(l+8).then(function(){var h={json:A._parseJson(c.readString(l)),bin:null},b=function(){var T=c.readUint32();switch(c.readUint32()){case S:throw new Error("Unexpected JSON chunk");case g:var D=c.byteOffset;h.bin={readAsync:function(w,N){return c.buffer.readAsync(D+w,N)},byteLength:T},c.skipBytes(T);break;default:c.skipBytes(T)}return c.byteOffset!==E?c.loadAsync(8).then(b):Promise.resolve(h)};return b()})},m._parseVersion=function(c){if(c==="1.0"||c==="1.0.1")return{major:1,minor:0};var E=(c+"").match(/^(\d+)\.(\d+)/);return E?{major:parseInt(E[1]),minor:parseInt(E[2])}:null},m._compareVersion=function(c,E){return c.major>E.major?1:c.majorE.minor?1:c.minor=0&&re.renderTargetTextures.splice(G,1)}if(this._opaqueRenderTarget&&(K=this._scene.customRenderTargets.indexOf(this._opaqueRenderTarget),this._opaqueRenderTarget.dispose()),this._opaqueRenderTarget=new _.RenderTargetTexture("opaqueSceneTexture",this._options.renderSize,this._scene,!0),this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.gammaSpace=!0,this._opaqueRenderTarget.lodGenerationScale=1,this._opaqueRenderTarget.lodGenerationOffset=-4,K>=0?this._scene.customRenderTargets.splice(K,0,this._opaqueRenderTarget):(K=this._scene.customRenderTargets.length,this._scene.customRenderTargets.push(this._opaqueRenderTarget)),this._scene.layers&&this._opaqueRenderTarget)for(var Q=0,oe=this._scene.layers;Q=0;Q--)if(G.push(x.a.Get(ee+"/ids/"+L[Q],$,L[Q])),G.length===this.maxLODsToLoad)return G;return G.push(K),G},ae.prototype._disposeTransformNode=function(ee){var K=this,$=new Array,L=ee.material;L&&$.push(L);for(var G=0,Q=ee.getChildMeshes();G0){var $=ee.metadata=ee.metadata||{};($.gltf=$.gltf||{}).extras=K.extras}},ae.prototype.dispose=function(){this._loader=null},ae.prototype.loadNodeAsync=function(ee,K,$){var L=this;return this._loader.loadNodeAsync(ee,K,function(G){L._assignExtras(G,K),$(G)})},ae.prototype.loadCameraAsync=function(ee,K,$){var L=this;return this._loader.loadCameraAsync(ee,K,function(G){L._assignExtras(G,K),$(G)})},ae.prototype.createMaterial=function(ee,K,$){var L=this._loader.createMaterial(ee,K,$);return this._assignExtras(L,K),L},ae}();x.b.RegisterExtension("ExtrasAsMetadata",function(ae){return new pe(ae)})},function(v,f,B){B.r(f),B.d(f,"GLTFBinaryExtension",function(){return H}),B.d(f,"GLTFLoaderBase",function(){return re}),B.d(f,"GLTFLoader",function(){return Y}),B.d(f,"GLTFLoaderExtension",function(){return k}),B.d(f,"EComponentType",function(){return _}),B.d(f,"EShaderType",function(){return x}),B.d(f,"EParameterType",function(){return u}),B.d(f,"ETextureWrapMode",function(){return M}),B.d(f,"ETextureFilterType",function(){return R}),B.d(f,"ETextureFormat",function(){return C}),B.d(f,"ECullingType",function(){return m}),B.d(f,"EBlendingFunction",function(){return c}),B.d(f,"GLTFUtils",function(){return g}),B.d(f,"GLTFMaterialsCommonExtension",function(){return Z});var _,x,u,M,R,C,m,c,E=B(4);(function(X){X[X.BYTE=5120]="BYTE",X[X.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",X[X.SHORT=5122]="SHORT",X[X.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",X[X.FLOAT=5126]="FLOAT"})(_||(_={})),function(X){X[X.FRAGMENT=35632]="FRAGMENT",X[X.VERTEX=35633]="VERTEX"}(x||(x={})),function(X){X[X.BYTE=5120]="BYTE",X[X.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",X[X.SHORT=5122]="SHORT",X[X.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",X[X.INT=5124]="INT",X[X.UNSIGNED_INT=5125]="UNSIGNED_INT",X[X.FLOAT=5126]="FLOAT",X[X.FLOAT_VEC2=35664]="FLOAT_VEC2",X[X.FLOAT_VEC3=35665]="FLOAT_VEC3",X[X.FLOAT_VEC4=35666]="FLOAT_VEC4",X[X.INT_VEC2=35667]="INT_VEC2",X[X.INT_VEC3=35668]="INT_VEC3",X[X.INT_VEC4=35669]="INT_VEC4",X[X.BOOL=35670]="BOOL",X[X.BOOL_VEC2=35671]="BOOL_VEC2",X[X.BOOL_VEC3=35672]="BOOL_VEC3",X[X.BOOL_VEC4=35673]="BOOL_VEC4",X[X.FLOAT_MAT2=35674]="FLOAT_MAT2",X[X.FLOAT_MAT3=35675]="FLOAT_MAT3",X[X.FLOAT_MAT4=35676]="FLOAT_MAT4",X[X.SAMPLER_2D=35678]="SAMPLER_2D"}(u||(u={})),function(X){X[X.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",X[X.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",X[X.REPEAT=10497]="REPEAT"}(M||(M={})),function(X){X[X.NEAREST=9728]="NEAREST",X[X.LINEAR=9728]="LINEAR",X[X.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",X[X.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",X[X.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",X[X.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"}(R||(R={})),function(X){X[X.ALPHA=6406]="ALPHA",X[X.RGB=6407]="RGB",X[X.RGBA=6408]="RGBA",X[X.LUMINANCE=6409]="LUMINANCE",X[X.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"}(C||(C={})),function(X){X[X.FRONT=1028]="FRONT",X[X.BACK=1029]="BACK",X[X.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(m||(m={})),function(X){X[X.ZERO=0]="ZERO",X[X.ONE=1]="ONE",X[X.SRC_COLOR=768]="SRC_COLOR",X[X.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",X[X.DST_COLOR=774]="DST_COLOR",X[X.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",X[X.SRC_ALPHA=770]="SRC_ALPHA",X[X.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",X[X.DST_ALPHA=772]="DST_ALPHA",X[X.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",X[X.CONSTANT_COLOR=32769]="CONSTANT_COLOR",X[X.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",X[X.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",X[X.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",X[X.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"}(c||(c={}));var A,S=B(0),g=function(){function X(){}return X.SetMatrix=function(q,he,ge,me,_e){var be=null;if(ge.semantic==="MODEL"?be=he.getWorldMatrix():ge.semantic==="PROJECTION"?be=q.getProjectionMatrix():ge.semantic==="VIEW"?be=q.getViewMatrix():ge.semantic==="MODELVIEWINVERSETRANSPOSE"?be=S.Matrix.Transpose(he.getWorldMatrix().multiply(q.getViewMatrix()).invert()):ge.semantic==="MODELVIEW"?be=he.getWorldMatrix().multiply(q.getViewMatrix()):ge.semantic==="MODELVIEWPROJECTION"?be=he.getWorldMatrix().multiply(q.getTransformMatrix()):ge.semantic==="MODELINVERSE"?be=he.getWorldMatrix().invert():ge.semantic==="VIEWINVERSE"?be=q.getViewMatrix().invert():ge.semantic==="PROJECTIONINVERSE"?be=q.getProjectionMatrix().invert():ge.semantic==="MODELVIEWINVERSE"?be=he.getWorldMatrix().multiply(q.getViewMatrix()).invert():ge.semantic==="MODELVIEWPROJECTIONINVERSE"?be=he.getWorldMatrix().multiply(q.getTransformMatrix()).invert():ge.semantic==="MODELINVERSETRANSPOSE"&&(be=S.Matrix.Transpose(he.getWorldMatrix().invert())),be)switch(ge.type){case u.FLOAT_MAT2:_e.setMatrix2x2(me,S.Matrix.GetAsMatrix2x2(be));break;case u.FLOAT_MAT3:_e.setMatrix3x3(me,S.Matrix.GetAsMatrix3x3(be));break;case u.FLOAT_MAT4:_e.setMatrix(me,be)}},X.SetUniform=function(q,he,ge,me){switch(me){case u.FLOAT:return q.setFloat(he,ge),!0;case u.FLOAT_VEC2:return q.setVector2(he,S.Vector2.FromArray(ge)),!0;case u.FLOAT_VEC3:return q.setVector3(he,S.Vector3.FromArray(ge)),!0;case u.FLOAT_VEC4:return q.setVector4(he,S.Vector4.FromArray(ge)),!0;default:return!1}},X.GetWrapMode=function(q){switch(q){case M.CLAMP_TO_EDGE:return S.Texture.CLAMP_ADDRESSMODE;case M.MIRRORED_REPEAT:return S.Texture.MIRROR_ADDRESSMODE;case M.REPEAT:default:return S.Texture.WRAP_ADDRESSMODE}},X.GetByteStrideFromType=function(q){switch(q.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}},X.GetTextureFilterMode=function(q){switch(q){case R.LINEAR:case R.LINEAR_MIPMAP_NEAREST:case R.LINEAR_MIPMAP_LINEAR:return S.Texture.TRILINEAR_SAMPLINGMODE;case R.NEAREST:case R.NEAREST_MIPMAP_NEAREST:return S.Texture.NEAREST_SAMPLINGMODE;default:return S.Texture.BILINEAR_SAMPLINGMODE}},X.GetBufferFromBufferView=function(q,he,ge,me,_e){ge=he.byteOffset+ge;var be=q.loadedBufferViews[he.buffer];if(ge+me>be.byteLength)throw new Error("Buffer access is out of range");var Ce=be.buffer;switch(ge+=be.byteOffset,_e){case _.BYTE:return new Int8Array(Ce,ge,me);case _.UNSIGNED_BYTE:return new Uint8Array(Ce,ge,me);case _.SHORT:return new Int16Array(Ce,ge,me);case _.UNSIGNED_SHORT:return new Uint16Array(Ce,ge,me);default:return new Float32Array(Ce,ge,me)}},X.GetBufferFromAccessor=function(q,he){var ge=q.bufferViews[he.bufferView],me=he.count*X.GetByteStrideFromType(he);return X.GetBufferFromBufferView(q,ge,he.byteOffset,me,he.componentType)},X.DecodeBufferToText=function(q){for(var he="",ge=q.byteLength,me=0;me=this._maxPos},X}(),b=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],T=["world","view","projection","worldView","worldViewProjection","mBones"],D=["translation","rotation","scale"],w=["position","rotationQuaternion","scaling"],N=function(X,q,he){for(var ge in X){var me=X[ge];he[q][ge]=me}},I=function(X){if(X)for(var q=0;q0&&(Xe=ne(_e,me))&&be.indexOf(Xe)===-1&&be.push(Xe),new S.Bone(ye.jointName||"",ge,Xe,et).id=me}}else S.Tools.Warn("Joint named "+q.jointNames[Ce]+" does not exist")}var lt=ge.bones;for(ge.bones=[],Ce=0;Ce1?(_e=new S.MultiMaterial("multimat"+ge,X.scene)).subMaterials=be:_e=new S.StandardMaterial("multimat"+ge,X.scene),be.length===1&&(_e=be[0]),me.material||(me.material=_e),new S.Geometry(ge,X.scene,Ce,!1,me),me.computeWorldMatrix(!0),X.scene._blockEntityCollection=!1,me.subMeshes=[];var Zt=0;for(He=0;He0&&X.importMeshesNames.indexOf(q.name||"")===-1)return null;if(q.skin){if(q.meshes){var _e=X.skins[q.skin];(be=ae(X,q,q.meshes,he,q.babylonNode)).skeleton=X.scene.getLastSkeletonByID(q.skin),be.skeleton===null&&(be.skeleton=pe(X,_e,0,_e.babylonSkeleton,q.skin),_e.babylonSkeleton||(_e.babylonSkeleton=be.skeleton)),me=be}}else if(q.meshes){var be;me=be=ae(X,q,q.mesh?[q.mesh]:q.meshes,he,q.babylonNode)}else if(!q.light||q.babylonNode||X.importOnlyMeshes){if(q.camera&&!q.babylonNode&&!X.importOnlyMeshes){var Ce=X.cameras[q.camera];if(Ce){if(X.scene._blockEntityCollection=X.forAssetContainer,Ce.type==="orthographic"){var ye=new S.FreeCamera(q.camera,S.Vector3.Zero(),X.scene,!1);ye.name=q.name||"",ye.mode=S.Camera.ORTHOGRAPHIC_CAMERA,ye.attachControl(),me=ye}else if(Ce.type==="perspective"){var Be=Ce[Ce.type],Ge=new S.FreeCamera(q.camera,S.Vector3.Zero(),X.scene,!1);Ge.name=q.name||"",Ge.attachControl(),Be.aspectRatio||(Be.aspectRatio=X.scene.getEngine().getRenderWidth()/X.scene.getEngine().getRenderHeight()),Be.znear&&Be.zfar&&(Ge.maxZ=Be.zfar,Ge.minZ=Be.znear),me=Ge}X.scene._blockEntityCollection=!1}}}else{var Xe=X.lights[q.light];if(Xe){if(Xe.type==="ambient"){var He=Xe[Xe.type],We=new S.HemisphericLight(q.light,S.Vector3.Zero(),X.scene);We.name=q.name||"",He.color&&(We.diffuse=S.Color3.FromArray(He.color)),me=We}else if(Xe.type==="directional"){var Ze=Xe[Xe.type],ze=new S.DirectionalLight(q.light,S.Vector3.Zero(),X.scene);ze.name=q.name||"",Ze.color&&(ze.diffuse=S.Color3.FromArray(Ze.color)),me=ze}else if(Xe.type==="point"){var it=Xe[Xe.type],et=new S.PointLight(q.light,S.Vector3.Zero(),X.scene);et.name=q.name||"",it.color&&(et.diffuse=S.Color3.FromArray(it.color)),me=et}else if(Xe.type==="spot"){var lt=Xe[Xe.type],ct=new S.SpotLight(q.light,S.Vector3.Zero(),S.Vector3.Zero(),0,0,X.scene);ct.name=q.name||"",lt.color&&(ct.diffuse=S.Color3.FromArray(lt.color)),lt.fallOfAngle&&(ct.angle=lt.fallOfAngle),lt.fallOffExponent&&(ct.exponent=lt.fallOffExponent),me=ct}}}if(!q.jointName){if(q.babylonNode)return q.babylonNode;if(me===null){X.scene._blockEntityCollection=X.forAssetContainer;var mt=new S.Mesh(q.name||"",X.scene);X.scene._blockEntityCollection=!1,q.babylonNode=mt,me=mt}}if(me!==null){if(q.matrix&&me instanceof S.Mesh)(function(Pt,Ot,on){if(Ot.matrix){var Zt=new S.Vector3(0,0,0),tn=new S.Quaternion,De=new S.Vector3(0,0,0);S.Matrix.FromArray(Ot.matrix).decompose(De,tn,Zt),ee(Pt,Zt,tn,De)}else Ot.translation&&Ot.rotation&&Ot.scale&&ee(Pt,S.Vector3.FromArray(Ot.translation),S.Quaternion.FromArray(Ot.rotation),S.Vector3.FromArray(Ot.scale));Pt.computeWorldMatrix(!0)})(me,q);else{var St=q.translation||[0,0,0],wt=q.rotation||[0,0,0,1],It=q.scale||[1,1,1];ee(me,S.Vector3.FromArray(St),S.Quaternion.FromArray(wt),S.Vector3.FromArray(It))}me.updateCache(!0),q.babylonNode=me}return me},$=function(X,q,he,ge){ge===void 0&&(ge=!1);var me=X.nodes[q],_e=null;if(ge=!(X.importOnlyMeshes&&!ge&&X.importMeshesNames)||X.importMeshesNames.indexOf(me.name||"")!==-1||X.importMeshesNames.length===0,!me.jointName&&ge&&(_e=K(X,me,q))!==null&&(_e.id=q,_e.parent=he),me.children)for(var be=0;be=0?h.substring(0,b):h;T=T.toLowerCase();var D=b>=0?h.substring(b+1).trim():"";T==="newmtl"?(g&&this.materials.push(g),R._blockEntityCollection=c,g=new _.StandardMaterial(D,R),R._blockEntityCollection=!1):T==="kd"&&g?(E=D.split(S,3).map(parseFloat),g.diffuseColor=_.Color3.FromArray(E)):T==="ka"&&g?(E=D.split(S,3).map(parseFloat),g.ambientColor=_.Color3.FromArray(E)):T==="ks"&&g?(E=D.split(S,3).map(parseFloat),g.specularColor=_.Color3.FromArray(E)):T==="ke"&&g?(E=D.split(S,3).map(parseFloat),g.emissiveColor=_.Color3.FromArray(E)):T==="ns"&&g?g.specularPower=parseFloat(D):T==="d"&&g?g.alpha=parseFloat(D):T==="map_ka"&&g?g.ambientTexture=M._getTexture(m,D,R):T==="map_kd"&&g?g.diffuseTexture=M._getTexture(m,D,R):T==="map_ks"&&g?g.specularTexture=M._getTexture(m,D,R):T==="map_ns"||(T==="map_bump"&&g?g.bumpTexture=M._getTexture(m,D,R):T==="map_d"&&g&&(g.opacityTexture=M._getTexture(m,D,R)))}}g&&this.materials.push(g)}},M._getTexture=function(R,C,m){if(!C)return null;var c=R;if(R==="file:"){var E=C.lastIndexOf("\\");E===-1&&(E=C.lastIndexOf("/")),c+=E>-1?C.substr(E+1):C}else c+=C;return new _.Texture(c,m,!1,M.INVERT_TEXTURE_Y)},M.INVERT_TEXTURE_Y=!0,M}(),u=function(){function M(R){this.name="obj",this.extensions=".obj",this.obj=/^o/,this.group=/^g/,this.mtllib=/^mtllib /,this.usemtl=/^usemtl /,this.smooth=/^s /,this.vertexPattern=/v(\s+[\d|\.|\+|\-|e|E]+){3,7}/,this.normalPattern=/vn(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.uvPattern=/vt(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.facePattern1=/f\s+(([\d]{1,}[\s]?){3,})+/,this.facePattern2=/f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern3=/f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern4=/f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,this.facePattern5=/f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,this._forAssetContainer=!1,this._meshLoadOptions=R||M.currentMeshLoadOptions}return Object.defineProperty(M,"INVERT_TEXTURE_Y",{get:function(){return x.INVERT_TEXTURE_Y},set:function(R){x.INVERT_TEXTURE_Y=R},enumerable:!1,configurable:!0}),Object.defineProperty(M,"currentMeshLoadOptions",{get:function(){return{ComputeNormals:M.COMPUTE_NORMALS,ImportVertexColors:M.IMPORT_VERTEX_COLORS,InvertY:M.INVERT_Y,InvertTextureY:M.INVERT_TEXTURE_Y,UVScaling:M.UV_SCALING,MaterialLoadingFailsSilently:M.MATERIAL_LOADING_FAILS_SILENTLY,OptimizeWithUV:M.OPTIMIZE_WITH_UV,SkipMaterials:M.SKIP_MATERIALS}},enumerable:!1,configurable:!0}),M.prototype._loadMTL=function(R,C,m,c){var E=_.Tools.BaseUrl+C+R;_.Tools.LoadFile(E,m,void 0,void 0,!1,function(A,S){c(E,S)})},M.prototype.createPlugin=function(){return new M(M.currentMeshLoadOptions)},M.prototype.canDirectLoad=function(R){return!1},M.prototype.importMeshAsync=function(R,C,m,c,E,A){return this._parseSolid(R,C,m,c).then(function(S){return{meshes:S,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[]}})},M.prototype.loadAsync=function(R,C,m,c,E){return this.importMeshAsync(null,R,C,m,c).then(function(){})},M.prototype.loadAssetContainerAsync=function(R,C,m,c,E){var A=this;return this._forAssetContainer=!0,this.importMeshAsync(null,R,C,m).then(function(S){var g=new _.AssetContainer(R);return S.meshes.forEach(function(l){return g.meshes.push(l)}),S.meshes.forEach(function(l){var h=l.material;h&&g.materials.indexOf(h)==-1&&(g.materials.push(h),h.getActiveTextures().forEach(function(b){g.textures.indexOf(b)==-1&&g.textures.push(b)}))}),A._forAssetContainer=!1,g}).catch(function(S){throw A._forAssetContainer=!1,S})},M.prototype._parseSolid=function(R,C,m,c){for(var E,A=this,S=[],g=[],l=[],h=[],b=[],T=[],D=[],w=[],N=[],I=[],V=[],W=0,j=!1,ne=[],te=[],de=[],pe=[],ae=[],ee="",K="",$=new x,L=1,G=!0,Q=new _.Color4(.5,.5,.5,1),oe=function(ze,it,et,lt,ct,mt,St){var wt;(wt=A._meshLoadOptions.OptimizeWithUV?function(It,Pt){It[Pt[0]]||(It[Pt[0]]={normals:[],idx:[],uv:[]});var Ot=It[Pt[0]].normals.indexOf(Pt[1]);return Ot!=1&&Pt[2]===It[Pt[0]].uv[Ot]?It[Pt[0]].idx[Ot]:-1}(V,[ze,et,it]):function(It,Pt){It[Pt[0]]||(It[Pt[0]]={normals:[],idx:[]});var Ot=It[Pt[0]].normals.indexOf(Pt[1]);return Ot===-1?-1:It[Pt[0]].idx[Ot]}(V,[ze,et]))===-1?(T.push(D.length),D.push(lt),w.push(ct),I.push(mt),St!==void 0&&N.push(St),V[ze].normals.push(et),V[ze].idx.push(W++),A._meshLoadOptions.OptimizeWithUV&&V[ze].uv.push(it)):T.push(wt)},re=function(){for(var ze=0;ze0&&(E=b[b.length-1],re(),T.reverse(),E.indices=T.slice(),E.positions=ne.slice(),E.normals=de.slice(),E.uvs=pe.slice(),A._meshLoadOptions.ImportVertexColors===!0&&(E.colors=te.slice()),T=[],ne=[],te=[],de=[],pe=[])},ge=m.split(` -`),me=0;me=7?h.push(new _.Color4(parseFloat(_e[4]),parseFloat(_e[5]),parseFloat(_e[6]),_e.length===7||_e[7]===void 0?1:parseFloat(_e[7]))):h.push(Q));else if((_e=this.normalPattern.exec(be))!==null)g.push(new _.Vector3(parseFloat(_e[1]),parseFloat(_e[2]),parseFloat(_e[3])));else if((_e=this.uvPattern.exec(be))!==null)l.push(new _.Vector2(parseFloat(_e[1])*M.UV_SCALING.x,parseFloat(_e[2])*M.UV_SCALING.y));else if((_e=this.facePattern3.exec(be))!==null)Z(_e[1].trim().split(" "),1);else if((_e=this.facePattern4.exec(be))!==null)X(_e[1].trim().split(" "),1);else if((_e=this.facePattern5.exec(be))!==null)q(_e[1].trim().split(" "),1);else if((_e=this.facePattern2.exec(be))!==null)H(_e[1].trim().split(" "),1);else if((_e=this.facePattern1.exec(be))!==null)k(_e[1].trim().split(" "),1);else if(this.group.test(be)||this.obj.test(be)){var Ce={name:be.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:""};he(),b.push(Ce),j=!0,G=!0,L=1}else this.usemtl.test(be)?(ee=be.substring(7).trim(),(!G||!j)&&(he(),Ce={name:"mesh_mm"+L.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:ee},L++,b.push(Ce),j=!0),j&&G&&(b[b.length-1].materialName=ee,G=!1)):this.mtllib.test(be)?K=be.substring(7).trim():this.smooth.test(be)||console.log("Unhandled expression at line : "+be)}j&&(E=b[b.length-1],T.reverse(),re(),E.indices=T,E.positions=ne,E.normals=de,E.uvs=pe,this._meshLoadOptions.ImportVertexColors===!0&&(E.colors=te)),j||(T.reverse(),re(),b.push({name:_.Geometry.RandomId(),indices:T,positions:ne,colors:te,normals:de,uvs:pe,materialName:ee}));for(var ye=[],Be=new Array,Ge=0;Ge-1;)St.push(ct),mt=ct+1;if(ct===-1&&St.length===0)$.materials[lt].dispose();else for(var wt=0;wt127)return!0;return!1},u.prototype._parseBinary=function(M,R){for(var C=new DataView(R),m=C.getUint32(80,!0),c=0,E=new Float32Array(3*m*3),A=new Float32Array(3*m*3),S=new Uint32Array(3*m),g=0,l=0;l-1||(C.GLTF2[c]=M[c])}}).call(this,B(5))},function(v,f,B){B.r(f),function(_){var x=B(10);B.d(f,"MTLFileLoader",function(){return x.MTLFileLoader}),B.d(f,"OBJFileLoader",function(){return x.OBJFileLoader});var u=_!==void 0?_:typeof window<"u"?window:void 0;if(u!==void 0)for(var M in x)u.BABYLON[M]=x[M]}.call(this,B(5))},function(v,f,B){B.r(f),function(_){var x=B(11);B.d(f,"STLFileLoader",function(){return x.STLFileLoader});var u=_!==void 0?_:typeof window<"u"?window:void 0;if(u!==void 0)for(var M in x)u.BABYLON[M]=x[M]}.call(this,B(5))},,,,function(v,f,B){B.r(f),B.d(f,"GLTFLoaderCoordinateSystemMode",function(){return _.c}),B.d(f,"GLTFLoaderAnimationStartMode",function(){return _.b}),B.d(f,"GLTFLoaderState",function(){return _.d}),B.d(f,"GLTFFileLoader",function(){return _.a}),B.d(f,"GLTFValidation",function(){return _.e}),B.d(f,"GLTF1",function(){return x.a}),B.d(f,"GLTF2",function(){return u.a}),B.d(f,"MTLFileLoader",function(){return M.MTLFileLoader}),B.d(f,"OBJFileLoader",function(){return M.OBJFileLoader}),B.d(f,"STLFileLoader",function(){return R.STLFileLoader}),B(2),B(3),B(8),B(9),B(10),B(11);var _=B(12),x=B(13),u=B(14),M=B(15),R=B(16)}])})})(Hf);var Qi=Hf.exports;const ob=Jv(Qi),Xa=rb({__proto__:null,default:ob},[Qi]);const{SvelteComponent:ab,append:Do,attr:Ki,binding_callbacks:sb,check_outros:cb,create_component:ll,destroy_component:ul,detach:hl,element:Wa,empty:lb,group_outros:ub,init:hb,insert:dl,mount_component:fl,safe_not_equal:db,space:pl,transition_in:Kr,transition_out:Lo}=window.__gradio__svelte__internal,{onMount:fb}=window.__gradio__svelte__internal;function Lf(Qe){let ke,Ae,v,f,B,_,x,u,M,R,C;return v=new Df({props:{Icon:$v,label:"Undo"}}),v.$on("click",Qe[12]),_=new Df({props:{Icon:Zv,label:Qe[3]("common.download")}}),{c(){ke=Wa("div"),Ae=Wa("div"),ll(v.$$.fragment),f=pl(),B=Wa("a"),ll(_.$$.fragment),M=pl(),R=Wa("canvas"),Ki(B,"href",x=Qe[0].path),Ki(B,"target",window.__is_colab__?"_blank":null),Ki(B,"download",u=window.__is_colab__?null:Qe[0].orig_name||Qe[0].path),Ki(Ae,"class","buttons svelte-xz066x"),Ki(R,"class","svelte-xz066x"),Ki(ke,"class","model3D svelte-xz066x")},m(m,c){dl(m,ke,c),Do(ke,Ae),fl(v,Ae,null),Do(Ae,f),Do(Ae,B),fl(_,B,null),Do(ke,M),Do(ke,R),Qe[13](R),C=!0},p(m,c){const E={};c&8&&(E.label=m[3]("common.download")),_.$set(E),(!C||c&1&&x!==(x=m[0].path))&&Ki(B,"href",x),(!C||c&1&&u!==(u=window.__is_colab__?null:m[0].orig_name||m[0].path))&&Ki(B,"download",u)},i(m){C||(Kr(v.$$.fragment,m),Kr(_.$$.fragment,m),C=!0)},o(m){Lo(v.$$.fragment,m),Lo(_.$$.fragment,m),C=!1},d(m){m&&hl(ke),ul(v),ul(_),Qe[13](null)}}}function pb(Qe){let ke,Ae,v,f;ke=new gl({props:{show_label:Qe[2],Icon:Ya,label:Qe[1]||Qe[3]("3D_model.3d_model")}});let B=Qe[0]&&Lf(Qe);return{c(){ll(ke.$$.fragment),Ae=pl(),B&&B.c(),v=lb()},m(_,x){fl(ke,_,x),dl(_,Ae,x),B&&B.m(_,x),dl(_,v,x),f=!0},p(_,[x]){const u={};x&4&&(u.show_label=_[2]),x&10&&(u.label=_[1]||_[3]("3D_model.3d_model")),ke.$set(u),_[0]?B?(B.p(_,x),x&1&&Kr(B,1)):(B=Lf(_),B.c(),Kr(B,1),B.m(v.parentNode,v)):B&&(ub(),Lo(B,1,1,()=>{B=null}),cb())},i(_){f||(Kr(ke.$$.fragment,_),Kr(B),f=!0)},o(_){Lo(ke.$$.fragment,_),Lo(B),f=!1},d(_){_&&(hl(Ae),hl(v)),ul(ke,_),B&&B.d(_)}}}function _b(Qe,ke,Ae){let v,{value:f}=ke,{clear_color:B=[0,0,0,0]}=ke,{label:_=""}=ke,{show_label:x}=ke,{i18n:u}=ke,{zoom_speed:M=1}=ke,{camera_position:R=[null,null,null]}=ke,C,m,c,E=!1;fb(()=>{c=new _i.Engine(C,!0),window.addEventListener("resize",()=>{c?.resize()}),Ae(10,E=!0)});function A(){m&&!m.isDisposed&&(m.dispose(),c?.stopRenderLoop(),c?.dispose(),c=null,c=new _i.Engine(C,!0),window.addEventListener("resize",()=>{c?.resize()})),c!==null&&(m=zf(C,m,c,f,B,R,M))}function S(){jf(m,R,M)}const g=()=>S();function l(h){sb[h?"unshift":"push"](()=>{C=h,Ae(4,C)})}return Qe.$$set=h=>{"value"in h&&Ae(0,f=h.value),"clear_color"in h&&Ae(6,B=h.clear_color),"label"in h&&Ae(1,_=h.label),"show_label"in h&&Ae(2,x=h.show_label),"i18n"in h&&Ae(3,u=h.i18n),"zoom_speed"in h&&Ae(7,M=h.zoom_speed),"camera_position"in h&&Ae(8,R=h.camera_position)},Qe.$$.update=()=>{Qe.$$.dirty&512&&Qi.OBJFileLoader!=null&&!Qi.OBJFileLoader.IMPORT_VERTEX_COLORS&&Ae(9,Qi.OBJFileLoader.IMPORT_VERTEX_COLORS=!0,Xa),Qe.$$.dirty&1&&Ae(11,{path:v}=f||{path:void 0},v),Qe.$$.dirty&3088&&C&&E&&v&&A()},[f,_,x,u,C,S,B,M,R,Xa,E,v,g,l]}class mb extends ab{constructor(ke){super(),hb(this,ke,_b,pb,db,{value:0,clear_color:6,label:1,show_label:2,i18n:3,zoom_speed:7,camera_position:8})}}const gb=mb;const{SvelteComponent:vb,add_flush_callback:bb,append:Nf,attr:wf,bind:yb,binding_callbacks:Wf,check_outros:Tb,create_component:vl,create_slot:Eb,destroy_component:bl,detach:_l,element:Ff,empty:Sb,get_all_dirty_from_scope:Ab,get_slot_changes:Pb,group_outros:Cb,init:xb,insert:ml,mount_component:yl,safe_not_equal:Rb,space:Xf,transition_in:qr,transition_out:Zr,update_slot_base:Ob}=window.__gradio__svelte__internal,{createEventDispatcher:Mb,tick:Bf,onMount:Ib}=window.__gradio__svelte__internal;function Db(Qe){let ke,Ae,v,f,B;return Ae=new eb({props:{undoable:!0,i18n:Qe[4],absolute:!0}}),Ae.$on("clear",Qe[8]),Ae.$on("undo",Qe[9]),{c(){ke=Ff("div"),vl(Ae.$$.fragment),v=Xf(),f=Ff("canvas"),wf(f,"class","svelte-15mfcnc"),wf(ke,"class","input-model svelte-15mfcnc")},m(_,x){ml(_,ke,x),yl(Ae,ke,null),Nf(ke,v),Nf(ke,f),Qe[18](f),B=!0},p(_,x){const u={};x&16&&(u.i18n=_[4]),Ae.$set(u)},i(_){B||(qr(Ae.$$.fragment,_),B=!0)},o(_){Zr(Ae.$$.fragment,_),B=!1},d(_){_&&_l(ke),bl(Ae),Qe[18](null)}}}function Lb(Qe){let ke,Ae,v;function f(_){Qe[17](_)}let B={root:Qe[3],filetype:".obj, .gltf, .glb",$$slots:{default:[Nb]},$$scope:{ctx:Qe}};return Qe[6]!==void 0&&(B.dragging=Qe[6]),ke=new tb({props:B}),Wf.push(()=>yb(ke,"dragging",f)),ke.$on("load",Qe[7]),{c(){vl(ke.$$.fragment)},m(_,x){yl(ke,_,x),v=!0},p(_,x){const u={};x&8&&(u.root=_[3]),x&524288&&(u.$$scope={dirty:x,ctx:_}),!Ae&&x&64&&(Ae=!0,u.dragging=_[6],bb(()=>Ae=!1)),ke.$set(u)},i(_){v||(qr(ke.$$.fragment,_),v=!0)},o(_){Zr(ke.$$.fragment,_),v=!1},d(_){bl(ke,_)}}}function Nb(Qe){let ke;const Ae=Qe[16].default,v=Eb(Ae,Qe,Qe[19],null);return{c(){v&&v.c()},m(f,B){v&&v.m(f,B),ke=!0},p(f,B){v&&v.p&&(!ke||B&524288)&&Ob(v,Ae,f,f[19],ke?Pb(Ae,f[19],B,null):Ab(f[19]),null)},i(f){ke||(qr(v,f),ke=!0)},o(f){Zr(v,f),ke=!1},d(f){v&&v.d(f)}}}function wb(Qe){let ke,Ae,v,f,B,_;ke=new gl({props:{show_label:Qe[2],Icon:Ya,label:Qe[1]||"3D Model"}});const x=[Lb,Db],u=[];function M(R,C){return R[0]===null?0:1}return v=M(Qe),f=u[v]=x[v](Qe),{c(){vl(ke.$$.fragment),Ae=Xf(),f.c(),B=Sb()},m(R,C){yl(ke,R,C),ml(R,Ae,C),u[v].m(R,C),ml(R,B,C),_=!0},p(R,[C]){const m={};C&4&&(m.show_label=R[2]),C&2&&(m.label=R[1]||"3D Model"),ke.$set(m);let c=v;v=M(R),v===c?u[v].p(R,C):(Cb(),Zr(u[c],1,1,()=>{u[c]=null}),Tb(),f=u[v],f?f.p(R,C):(f=u[v]=x[v](R),f.c()),qr(f,1),f.m(B.parentNode,B))},i(R){_||(qr(ke.$$.fragment,R),qr(f),_=!0)},o(R){Zr(ke.$$.fragment,R),Zr(f),_=!1},d(R){R&&(_l(Ae),_l(B)),bl(ke,R),u[v].d(R)}}}function Fb(Qe,ke,Ae){let v,{$$slots:f={},$$scope:B}=ke,{value:_}=ke,{clear_color:x=[0,0,0,0]}=ke,{label:u=""}=ke,{show_label:M}=ke,{root:R}=ke,{i18n:C}=ke,{zoom_speed:m=1}=ke,{camera_position:c=[null,null,null]}=ke,E=!1,A,S,g;function l(){S=zf(A,S,g,_,x,c,m)}Ib(()=>{_!=null&&l(),Ae(13,E=!0)});async function h({detail:V}){Ae(0,_=V),await Bf(),l(),D("change",_)}async function b(){S&&g&&(S.dispose(),g.dispose()),Ae(0,_=null),await Bf(),D("clear")}async function T(){jf(S,c,m)}const D=Mb();let w=!1;function N(V){w=V,Ae(6,w)}function I(V){Wf[V?"unshift":"push"](()=>{A=V,Ae(5,A)})}return Qe.$$set=V=>{"value"in V&&Ae(0,_=V.value),"clear_color"in V&&Ae(10,x=V.clear_color),"label"in V&&Ae(1,u=V.label),"show_label"in V&&Ae(2,M=V.show_label),"root"in V&&Ae(3,R=V.root),"i18n"in V&&Ae(4,C=V.i18n),"zoom_speed"in V&&Ae(11,m=V.zoom_speed),"camera_position"in V&&Ae(12,c=V.camera_position),"$$scope"in V&&Ae(19,B=V.$$scope)},Qe.$$.update=()=>{Qe.$$.dirty&1&&Ae(15,{path:v}=_||{path:void 0},v),Qe.$$.dirty&40992&&A&&E&&v!=null&&l(),Qe.$$.dirty&16384&&Qi.OBJFileLoader!=null&&!Qi.OBJFileLoader.IMPORT_VERTEX_COLORS&&Ae(14,Qi.OBJFileLoader.IMPORT_VERTEX_COLORS=!0,Xa),Qe.$$.dirty&64&&D("drag",w)},[_,u,M,R,C,A,w,h,b,T,x,m,c,E,Xa,v,f,N,I,B]}class Bb extends vb{constructor(ke){super(),xb(this,ke,Fb,wb,Rb,{value:0,clear_color:10,label:1,show_label:2,root:3,i18n:4,zoom_speed:11,camera_position:12})}}const Ub=Bb,{SvelteComponent:Vb,assign:Yf,check_outros:Kf,create_component:mi,destroy_component:gi,detach:No,empty:Qf,get_spread_object:qf,get_spread_update:Zf,group_outros:Jf,init:kb,insert:wo,mount_component:vi,safe_not_equal:Gb,space:Tl,transition_in:Un,transition_out:Vn}=window.__gradio__svelte__internal;function zb(Qe){let ke,Ae;return ke=new Uf({props:{visible:Qe[3],variant:Qe[0]===null?"dashed":"solid",border_mode:Qe[18]?"focus":"base",padding:!1,elem_id:Qe[1],elem_classes:Qe[2],container:Qe[9],scale:Qe[10],min_width:Qe[11],height:Qe[13],$$slots:{default:[Wb]},$$scope:{ctx:Qe}}}),{c(){mi(ke.$$.fragment)},m(v,f){vi(ke,v,f),Ae=!0},p(v,f){const B={};f&8&&(B.visible=v[3]),f&1&&(B.variant=v[0]===null?"dashed":"solid"),f&262144&&(B.border_mode=v[18]?"focus":"base"),f&2&&(B.elem_id=v[1]),f&4&&(B.elem_classes=v[2]),f&512&&(B.container=v[9]),f&1024&&(B.scale=v[10]),f&2048&&(B.min_width=v[11]),f&8192&&(B.height=v[13]),f&17224177&&(B.$$scope={dirty:f,ctx:v}),ke.$set(B)},i(v){Ae||(Un(ke.$$.fragment,v),Ae=!0)},o(v){Vn(ke.$$.fragment,v),Ae=!1},d(v){gi(ke,v)}}}function jb(Qe){let ke,Ae;return ke=new Uf({props:{visible:Qe[3],variant:Qe[0]===null?"dashed":"solid",border_mode:Qe[18]?"focus":"base",padding:!1,elem_id:Qe[1],elem_classes:Qe[2],container:Qe[9],scale:Qe[10],min_width:Qe[11],height:Qe[13],$$slots:{default:[Qb]},$$scope:{ctx:Qe}}}),{c(){mi(ke.$$.fragment)},m(v,f){vi(ke,v,f),Ae=!0},p(v,f){const B={};f&8&&(B.visible=v[3]),f&1&&(B.variant=v[0]===null?"dashed":"solid"),f&262144&&(B.border_mode=v[18]?"focus":"base"),f&2&&(B.elem_id=v[1]),f&4&&(B.elem_classes=v[2]),f&512&&(B.container=v[9]),f&1024&&(B.scale=v[10]),f&2048&&(B.min_width=v[11]),f&8192&&(B.height=v[13]),f&16962017&&(B.$$scope={dirty:f,ctx:v}),ke.$set(B)},i(v){Ae||(Un(ke.$$.fragment,v),Ae=!0)},o(v){Vn(ke.$$.fragment,v),Ae=!1},d(v){gi(ke,v)}}}function Hb(Qe){let ke,Ae;return ke=new ib({props:{i18n:Qe[12].i18n,type:"file"}}),{c(){mi(ke.$$.fragment)},m(v,f){vi(ke,v,f),Ae=!0},p(v,f){const B={};f&4096&&(B.i18n=v[12].i18n),ke.$set(B)},i(v){Ae||(Un(ke.$$.fragment,v),Ae=!0)},o(v){Vn(ke.$$.fragment,v),Ae=!1},d(v){gi(ke,v)}}}function Wb(Qe){let ke,Ae,v,f;const B=[{autoscroll:Qe[12].autoscroll},{i18n:Qe[12].i18n},Qe[6]];let _={};for(let x=0;x{R[A]=null}),Kf(),f=R[v],f?f.p(m,c):(f=R[v]=M[v](m),f.c()),Un(f,1),f.m(B.parentNode,B))},i(m){_||(Un(ke.$$.fragment,m),Un(f),_=!0)},o(m){Vn(ke.$$.fragment,m),Vn(f),_=!1},d(m){m&&(No(Ae),No(B)),gi(ke,m),R[v].d(m)}}}function qb(Qe){let ke,Ae,v,f;const B=[jb,zb],_=[];function x(u,M){return u[16]?1:0}return ke=x(Qe),Ae=_[ke]=B[ke](Qe),{c(){Ae.c(),v=Qf()},m(u,M){_[ke].m(u,M),wo(u,v,M),f=!0},p(u,[M]){let R=ke;ke=x(u),ke===R?_[ke].p(u,M):(Jf(),Vn(_[R],1,1,()=>{_[R]=null}),Kf(),Ae=_[ke],Ae?Ae.p(u,M):(Ae=_[ke]=B[ke](u),Ae.c()),Un(Ae,1),Ae.m(v.parentNode,v))},i(u){f||(Un(Ae),f=!0)},o(u){Vn(Ae),f=!1},d(u){u&&No(v),_[ke].d(u)}}}function Zb(Qe,ke,Ae){let{elem_id:v=""}=ke,{elem_classes:f=[]}=ke,{visible:B=!0}=ke,{value:_=null}=ke,{root:x}=ke,{proxy_url:u}=ke,{clear_color:M}=ke,{loading_status:R}=ke,{label:C}=ke,{show_label:m}=ke,{container:c=!0}=ke,{scale:E=null}=ke,{min_width:A=void 0}=ke,{gradio:S}=ke,{height:g=void 0}=ke,{zoom_speed:l=1}=ke,{camera_position:h=[null,null,null]}=ke,{interactive:b}=ke,T,D=!1;const w=({detail:W})=>Ae(0,_=W),N=({detail:W})=>Ae(18,D=W),I=({detail:W})=>S.dispatch("change",W),V=()=>S.dispatch("clear");return Qe.$$set=W=>{"elem_id"in W&&Ae(1,v=W.elem_id),"elem_classes"in W&&Ae(2,f=W.elem_classes),"visible"in W&&Ae(3,B=W.visible),"value"in W&&Ae(0,_=W.value),"root"in W&&Ae(4,x=W.root),"proxy_url"in W&&Ae(19,u=W.proxy_url),"clear_color"in W&&Ae(5,M=W.clear_color),"loading_status"in W&&Ae(6,R=W.loading_status),"label"in W&&Ae(7,C=W.label),"show_label"in W&&Ae(8,m=W.show_label),"container"in W&&Ae(9,c=W.container),"scale"in W&&Ae(10,E=W.scale),"min_width"in W&&Ae(11,A=W.min_width),"gradio"in W&&Ae(12,S=W.gradio),"height"in W&&Ae(13,g=W.height),"zoom_speed"in W&&Ae(14,l=W.zoom_speed),"camera_position"in W&&Ae(15,h=W.camera_position),"interactive"in W&&Ae(16,b=W.interactive)},Qe.$$.update=()=>{Qe.$$.dirty&524305&&Ae(17,T=qv(_,x,u))},[_,v,f,B,x,M,R,C,m,c,E,A,S,g,l,h,b,T,D,u,w,N,I,V]}class dy extends Vb{constructor(ke){super(),kb(this,ke,Zb,qb,Gb,{elem_id:1,elem_classes:2,visible:3,value:0,root:4,proxy_url:19,clear_color:5,loading_status:6,label:7,show_label:8,container:9,scale:10,min_width:11,gradio:12,height:13,zoom_speed:14,camera_position:15,interactive:16})}}export{_y as BaseExample,gb as BaseModel3D,Ub as BaseModel3DUpload,dy as default}; -//# sourceMappingURL=Index-c702b95a.js.map diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/httpcore/_synchronization.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/httpcore/_synchronization.py deleted file mode 100644 index bae27c1b11255891997ae21c0f1c240f547a65a5..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/httpcore/_synchronization.py +++ /dev/null @@ -1,279 +0,0 @@ -import threading -from types import TracebackType -from typing import Optional, Type - -import sniffio - -from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions - -# Our async synchronization primatives use either 'anyio' or 'trio' depending -# on if they're running under asyncio or trio. - -try: - import trio -except ImportError: # pragma: nocover - trio = None # type: ignore - -try: - import anyio -except ImportError: # pragma: nocover - anyio = None # type: ignore - - -class AsyncLock: - def __init__(self) -> None: - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a lock with the correct implementation. - """ - self._backend = sniffio.current_async_library() - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio, requires the 'trio' package to be installed." - ) - self._trio_lock = trio.Lock() - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - self._anyio_lock = anyio.Lock() - - async def __aenter__(self) -> "AsyncLock": - if not self._backend: - self.setup() - - if self._backend == "trio": - await self._trio_lock.acquire() - else: - await self._anyio_lock.acquire() - - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - if self._backend == "trio": - self._trio_lock.release() - else: - self._anyio_lock.release() - - -class AsyncEvent: - def __init__(self) -> None: - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a lock with the correct implementation. - """ - self._backend = sniffio.current_async_library() - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - self._trio_event = trio.Event() - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - self._anyio_event = anyio.Event() - - def set(self) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - self._trio_event.set() - else: - self._anyio_event.set() - - async def wait(self, timeout: Optional[float] = None) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - - trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} - timeout_or_inf = float("inf") if timeout is None else timeout - with map_exceptions(trio_exc_map): - with trio.fail_after(timeout_or_inf): - await self._trio_event.wait() - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - - anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} - with map_exceptions(anyio_exc_map): - with anyio.fail_after(timeout): - await self._anyio_event.wait() - - -class AsyncSemaphore: - def __init__(self, bound: int) -> None: - self._bound = bound - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a semaphore with the correct implementation. - """ - self._backend = sniffio.current_async_library() - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - - self._trio_semaphore = trio.Semaphore( - initial_value=self._bound, max_value=self._bound - ) - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - - self._anyio_semaphore = anyio.Semaphore( - initial_value=self._bound, max_value=self._bound - ) - - async def acquire(self) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - await self._trio_semaphore.acquire() - else: - await self._anyio_semaphore.acquire() - - async def release(self) -> None: - if self._backend == "trio": - self._trio_semaphore.release() - else: - self._anyio_semaphore.release() - - -class AsyncShieldCancellation: - # For certain portions of our codebase where we're dealing with - # closing connections during exception handling we want to shield - # the operation from being cancelled. - # - # with AsyncShieldCancellation(): - # ... # clean-up operations, shielded from cancellation. - - def __init__(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a shielded scope with the correct implementation. - """ - self._backend = sniffio.current_async_library() - - if self._backend == "trio": - if trio is None: # pragma: nocover - raise RuntimeError( - "Running under trio requires the 'trio' package to be installed." - ) - - self._trio_shield = trio.CancelScope(shield=True) - else: - if anyio is None: # pragma: nocover - raise RuntimeError( - "Running under asyncio requires the 'anyio' package to be installed." - ) - - self._anyio_shield = anyio.CancelScope(shield=True) - - def __enter__(self) -> "AsyncShieldCancellation": - if self._backend == "trio": - self._trio_shield.__enter__() - else: - self._anyio_shield.__enter__() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - if self._backend == "trio": - self._trio_shield.__exit__(exc_type, exc_value, traceback) - else: - self._anyio_shield.__exit__(exc_type, exc_value, traceback) - - -# Our thread-based synchronization primitives... - - -class Lock: - def __init__(self) -> None: - self._lock = threading.Lock() - - def __enter__(self) -> "Lock": - self._lock.acquire() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - self._lock.release() - - -class Event: - def __init__(self) -> None: - self._event = threading.Event() - - def set(self) -> None: - self._event.set() - - def wait(self, timeout: Optional[float] = None) -> None: - if not self._event.wait(timeout=timeout): - raise PoolTimeout() # pragma: nocover - - -class Semaphore: - def __init__(self, bound: int) -> None: - self._semaphore = threading.Semaphore(value=bound) - - def acquire(self) -> None: - self._semaphore.acquire() - - def release(self) -> None: - self._semaphore.release() - - -class ShieldCancellation: - # Thread-synchronous codebases don't support cancellation semantics. - # We have this class because we need to mirror the async and sync - # cases within our package, but it's just a no-op. - def __enter__(self) -> "ShieldCancellation": - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - traceback: Optional[TracebackType] = None, - ) -> None: - pass diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jinja2/bccache.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jinja2/bccache.py deleted file mode 100644 index d0ddf56ef62b03cba6b6c5f9b94d819393f09d38..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jinja2/bccache.py +++ /dev/null @@ -1,406 +0,0 @@ -"""The optional bytecode cache system. This is useful if you have very -complex template situations and the compilation of all those templates -slows down your application too much. - -Situations where this is useful are often forking web applications that -are initialized on the first request. -""" -import errno -import fnmatch -import marshal -import os -import pickle -import stat -import sys -import tempfile -import typing as t -from hashlib import sha1 -from io import BytesIO -from types import CodeType - -if t.TYPE_CHECKING: - import typing_extensions as te - from .environment import Environment - - class _MemcachedClient(te.Protocol): - def get(self, key: str) -> bytes: - ... - - def set(self, key: str, value: bytes, timeout: t.Optional[int] = None) -> None: - ... - - -bc_version = 5 -# Magic bytes to identify Jinja bytecode cache files. Contains the -# Python major and minor version to avoid loading incompatible bytecode -# if a project upgrades its Python version. -bc_magic = ( - b"j2" - + pickle.dumps(bc_version, 2) - + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2) -) - - -class Bucket: - """Buckets are used to store the bytecode for one template. It's created - and initialized by the bytecode cache and passed to the loading functions. - - The buckets get an internal checksum from the cache assigned and use this - to automatically reject outdated cache material. Individual bytecode - cache subclasses don't have to care about cache invalidation. - """ - - def __init__(self, environment: "Environment", key: str, checksum: str) -> None: - self.environment = environment - self.key = key - self.checksum = checksum - self.reset() - - def reset(self) -> None: - """Resets the bucket (unloads the bytecode).""" - self.code: t.Optional[CodeType] = None - - def load_bytecode(self, f: t.BinaryIO) -> None: - """Loads bytecode from a file or file like object.""" - # make sure the magic header is correct - magic = f.read(len(bc_magic)) - if magic != bc_magic: - self.reset() - return - # the source code of the file changed, we need to reload - checksum = pickle.load(f) - if self.checksum != checksum: - self.reset() - return - # if marshal_load fails then we need to reload - try: - self.code = marshal.load(f) - except (EOFError, ValueError, TypeError): - self.reset() - return - - def write_bytecode(self, f: t.IO[bytes]) -> None: - """Dump the bytecode into the file or file like object passed.""" - if self.code is None: - raise TypeError("can't write empty bucket") - f.write(bc_magic) - pickle.dump(self.checksum, f, 2) - marshal.dump(self.code, f) - - def bytecode_from_string(self, string: bytes) -> None: - """Load bytecode from bytes.""" - self.load_bytecode(BytesIO(string)) - - def bytecode_to_string(self) -> bytes: - """Return the bytecode as bytes.""" - out = BytesIO() - self.write_bytecode(out) - return out.getvalue() - - -class BytecodeCache: - """To implement your own bytecode cache you have to subclass this class - and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of - these methods are passed a :class:`~jinja2.bccache.Bucket`. - - A very basic bytecode cache that saves the bytecode on the file system:: - - from os import path - - class MyCache(BytecodeCache): - - def __init__(self, directory): - self.directory = directory - - def load_bytecode(self, bucket): - filename = path.join(self.directory, bucket.key) - if path.exists(filename): - with open(filename, 'rb') as f: - bucket.load_bytecode(f) - - def dump_bytecode(self, bucket): - filename = path.join(self.directory, bucket.key) - with open(filename, 'wb') as f: - bucket.write_bytecode(f) - - A more advanced version of a filesystem based bytecode cache is part of - Jinja. - """ - - def load_bytecode(self, bucket: Bucket) -> None: - """Subclasses have to override this method to load bytecode into a - bucket. If they are not able to find code in the cache for the - bucket, it must not do anything. - """ - raise NotImplementedError() - - def dump_bytecode(self, bucket: Bucket) -> None: - """Subclasses have to override this method to write the bytecode - from a bucket back to the cache. If it unable to do so it must not - fail silently but raise an exception. - """ - raise NotImplementedError() - - def clear(self) -> None: - """Clears the cache. This method is not used by Jinja but should be - implemented to allow applications to clear the bytecode cache used - by a particular environment. - """ - - def get_cache_key( - self, name: str, filename: t.Optional[t.Union[str]] = None - ) -> str: - """Returns the unique hash key for this template name.""" - hash = sha1(name.encode("utf-8")) - - if filename is not None: - hash.update(f"|{filename}".encode()) - - return hash.hexdigest() - - def get_source_checksum(self, source: str) -> str: - """Returns a checksum for the source.""" - return sha1(source.encode("utf-8")).hexdigest() - - def get_bucket( - self, - environment: "Environment", - name: str, - filename: t.Optional[str], - source: str, - ) -> Bucket: - """Return a cache bucket for the given template. All arguments are - mandatory but filename may be `None`. - """ - key = self.get_cache_key(name, filename) - checksum = self.get_source_checksum(source) - bucket = Bucket(environment, key, checksum) - self.load_bytecode(bucket) - return bucket - - def set_bucket(self, bucket: Bucket) -> None: - """Put the bucket into the cache.""" - self.dump_bytecode(bucket) - - -class FileSystemBytecodeCache(BytecodeCache): - """A bytecode cache that stores bytecode on the filesystem. It accepts - two arguments: The directory where the cache items are stored and a - pattern string that is used to build the filename. - - If no directory is specified a default cache directory is selected. On - Windows the user's temp directory is used, on UNIX systems a directory - is created for the user in the system temp directory. - - The pattern can be used to have multiple separate caches operate on the - same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s`` - is replaced with the cache key. - - >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') - - This bytecode cache supports clearing of the cache using the clear method. - """ - - def __init__( - self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache" - ) -> None: - if directory is None: - directory = self._get_default_cache_dir() - self.directory = directory - self.pattern = pattern - - def _get_default_cache_dir(self) -> str: - def _unsafe_dir() -> "te.NoReturn": - raise RuntimeError( - "Cannot determine safe temp directory. You " - "need to explicitly provide one." - ) - - tmpdir = tempfile.gettempdir() - - # On windows the temporary directory is used specific unless - # explicitly forced otherwise. We can just use that. - if os.name == "nt": - return tmpdir - if not hasattr(os, "getuid"): - _unsafe_dir() - - dirname = f"_jinja2-cache-{os.getuid()}" - actual_dir = os.path.join(tmpdir, dirname) - - try: - os.mkdir(actual_dir, stat.S_IRWXU) - except OSError as e: - if e.errno != errno.EEXIST: - raise - try: - os.chmod(actual_dir, stat.S_IRWXU) - actual_dir_stat = os.lstat(actual_dir) - if ( - actual_dir_stat.st_uid != os.getuid() - or not stat.S_ISDIR(actual_dir_stat.st_mode) - or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU - ): - _unsafe_dir() - except OSError as e: - if e.errno != errno.EEXIST: - raise - - actual_dir_stat = os.lstat(actual_dir) - if ( - actual_dir_stat.st_uid != os.getuid() - or not stat.S_ISDIR(actual_dir_stat.st_mode) - or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU - ): - _unsafe_dir() - - return actual_dir - - def _get_cache_filename(self, bucket: Bucket) -> str: - return os.path.join(self.directory, self.pattern % (bucket.key,)) - - def load_bytecode(self, bucket: Bucket) -> None: - filename = self._get_cache_filename(bucket) - - # Don't test for existence before opening the file, since the - # file could disappear after the test before the open. - try: - f = open(filename, "rb") - except (FileNotFoundError, IsADirectoryError, PermissionError): - # PermissionError can occur on Windows when an operation is - # in progress, such as calling clear(). - return - - with f: - bucket.load_bytecode(f) - - def dump_bytecode(self, bucket: Bucket) -> None: - # Write to a temporary file, then rename to the real name after - # writing. This avoids another process reading the file before - # it is fully written. - name = self._get_cache_filename(bucket) - f = tempfile.NamedTemporaryFile( - mode="wb", - dir=os.path.dirname(name), - prefix=os.path.basename(name), - suffix=".tmp", - delete=False, - ) - - def remove_silent() -> None: - try: - os.remove(f.name) - except OSError: - # Another process may have called clear(). On Windows, - # another program may be holding the file open. - pass - - try: - with f: - bucket.write_bytecode(f) - except BaseException: - remove_silent() - raise - - try: - os.replace(f.name, name) - except OSError: - # Another process may have called clear(). On Windows, - # another program may be holding the file open. - remove_silent() - except BaseException: - remove_silent() - raise - - def clear(self) -> None: - # imported lazily here because google app-engine doesn't support - # write access on the file system and the function does not exist - # normally. - from os import remove - - files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",)) - for filename in files: - try: - remove(os.path.join(self.directory, filename)) - except OSError: - pass - - -class MemcachedBytecodeCache(BytecodeCache): - """This class implements a bytecode cache that uses a memcache cache for - storing the information. It does not enforce a specific memcache library - (tummy's memcache or cmemcache) but will accept any class that provides - the minimal interface required. - - Libraries compatible with this class: - - - `cachelib `_ - - `python-memcached `_ - - (Unfortunately the django cache interface is not compatible because it - does not support storing binary data, only text. You can however pass - the underlying cache client to the bytecode cache which is available - as `django.core.cache.cache._client`.) - - The minimal interface for the client passed to the constructor is this: - - .. class:: MinimalClientInterface - - .. method:: set(key, value[, timeout]) - - Stores the bytecode in the cache. `value` is a string and - `timeout` the timeout of the key. If timeout is not provided - a default timeout or no timeout should be assumed, if it's - provided it's an integer with the number of seconds the cache - item should exist. - - .. method:: get(key) - - Returns the value for the cache key. If the item does not - exist in the cache the return value must be `None`. - - The other arguments to the constructor are the prefix for all keys that - is added before the actual cache key and the timeout for the bytecode in - the cache system. We recommend a high (or no) timeout. - - This bytecode cache does not support clearing of used items in the cache. - The clear method is a no-operation function. - - .. versionadded:: 2.7 - Added support for ignoring memcache errors through the - `ignore_memcache_errors` parameter. - """ - - def __init__( - self, - client: "_MemcachedClient", - prefix: str = "jinja2/bytecode/", - timeout: t.Optional[int] = None, - ignore_memcache_errors: bool = True, - ): - self.client = client - self.prefix = prefix - self.timeout = timeout - self.ignore_memcache_errors = ignore_memcache_errors - - def load_bytecode(self, bucket: Bucket) -> None: - try: - code = self.client.get(self.prefix + bucket.key) - except Exception: - if not self.ignore_memcache_errors: - raise - else: - bucket.bytecode_from_string(code) - - def dump_bytecode(self, bucket: Bucket) -> None: - key = self.prefix + bucket.key - value = bucket.bytecode_to_string() - - try: - if self.timeout is not None: - self.client.set(key, value, self.timeout) - else: - self.client.set(key, value) - except Exception: - if not self.ignore_memcache_errors: - raise diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/_fontconfig_pattern.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/_fontconfig_pattern.py deleted file mode 100644 index d3933b9f396d091a3da061bbc2dbe9698d2fc0da..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/_fontconfig_pattern.py +++ /dev/null @@ -1,120 +0,0 @@ -""" -A module for parsing and generating `fontconfig patterns`_. - -.. _fontconfig patterns: - https://www.freedesktop.org/software/fontconfig/fontconfig-user.html -""" - -# This class logically belongs in `matplotlib.font_manager`, but placing it -# there would have created cyclical dependency problems, because it also needs -# to be available from `matplotlib.rcsetup` (for parsing matplotlibrc files). - -from functools import lru_cache, partial -import re - -from pyparsing import ( - Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore) - -from matplotlib import _api - - -_family_punc = r'\\\-:,' -_family_unescape = partial(re.compile(r'\\(?=[%s])' % _family_punc).sub, '') -_family_escape = partial(re.compile(r'(?=[%s])' % _family_punc).sub, r'\\') -_value_punc = r'\\=_:,' -_value_unescape = partial(re.compile(r'\\(?=[%s])' % _value_punc).sub, '') -_value_escape = partial(re.compile(r'(?=[%s])' % _value_punc).sub, r'\\') - - -_CONSTANTS = { - 'thin': ('weight', 'light'), - 'extralight': ('weight', 'light'), - 'ultralight': ('weight', 'light'), - 'light': ('weight', 'light'), - 'book': ('weight', 'book'), - 'regular': ('weight', 'regular'), - 'normal': ('weight', 'normal'), - 'medium': ('weight', 'medium'), - 'demibold': ('weight', 'demibold'), - 'semibold': ('weight', 'semibold'), - 'bold': ('weight', 'bold'), - 'extrabold': ('weight', 'extra bold'), - 'black': ('weight', 'black'), - 'heavy': ('weight', 'heavy'), - 'roman': ('slant', 'normal'), - 'italic': ('slant', 'italic'), - 'oblique': ('slant', 'oblique'), - 'ultracondensed': ('width', 'ultra-condensed'), - 'extracondensed': ('width', 'extra-condensed'), - 'condensed': ('width', 'condensed'), - 'semicondensed': ('width', 'semi-condensed'), - 'expanded': ('width', 'expanded'), - 'extraexpanded': ('width', 'extra-expanded'), - 'ultraexpanded': ('width', 'ultra-expanded'), -} - - -@lru_cache # The parser instance is a singleton. -def _make_fontconfig_parser(): - def comma_separated(elem): - return elem + ZeroOrMore(Suppress(",") + elem) - - family = Regex(fr"([^{_family_punc}]|(\\[{_family_punc}]))*") - size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)") - name = Regex(r"[a-z]+") - value = Regex(fr"([^{_value_punc}]|(\\[{_value_punc}]))*") - # replace trailing `| name` by oneOf(_CONSTANTS) in mpl 3.9. - prop = Group((name + Suppress("=") + comma_separated(value)) | name) - return ( - Optional(comma_separated(family)("families")) - + Optional("-" + comma_separated(size)("sizes")) - + ZeroOrMore(":" + prop("properties*")) - + StringEnd() - ) - - -# `parse_fontconfig_pattern` is a bottleneck during the tests because it is -# repeatedly called when the rcParams are reset (to validate the default -# fonts). In practice, the cache size doesn't grow beyond a few dozen entries -# during the test suite. -@lru_cache -def parse_fontconfig_pattern(pattern): - """ - Parse a fontconfig *pattern* into a dict that can initialize a - `.font_manager.FontProperties` object. - """ - parser = _make_fontconfig_parser() - try: - parse = parser.parseString(pattern) - except ParseException as err: - # explain becomes a plain method on pyparsing 3 (err.explain(0)). - raise ValueError("\n" + ParseException.explain(err, 0)) from None - parser.resetCache() - props = {} - if "families" in parse: - props["family"] = [*map(_family_unescape, parse["families"])] - if "sizes" in parse: - props["size"] = [*parse["sizes"]] - for prop in parse.get("properties", []): - if len(prop) == 1: - if prop[0] not in _CONSTANTS: - _api.warn_deprecated( - "3.7", message=f"Support for unknown constants " - f"({prop[0]!r}) is deprecated since %(since)s and " - f"will be removed %(removal)s.") - continue - prop = _CONSTANTS[prop[0]] - k, *v = prop - props.setdefault(k, []).extend(map(_value_unescape, v)) - return props - - -def generate_fontconfig_pattern(d): - """Convert a `.FontProperties` to a fontconfig pattern string.""" - kvs = [(k, getattr(d, f"get_{k}")()) - for k in ["style", "variant", "weight", "stretch", "file", "size"]] - # Families is given first without a leading keyword. Other entries (which - # are necessarily scalar) are given as key=value, skipping Nones. - return (",".join(_family_escape(f) for f in d.get_family()) - + "".join(f":{k}={_value_escape(str(v))}" - for k, v in kvs if v is not None)) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/distutils/command/bdist_rpm.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/distutils/command/bdist_rpm.py deleted file mode 100644 index 682e7a8eb8e2b8cdd922fe77ed13992c5a7a1252..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/distutils/command/bdist_rpm.py +++ /dev/null @@ -1,22 +0,0 @@ -import os -import sys -if 'setuptools' in sys.modules: - from setuptools.command.bdist_rpm import bdist_rpm as old_bdist_rpm -else: - from distutils.command.bdist_rpm import bdist_rpm as old_bdist_rpm - -class bdist_rpm(old_bdist_rpm): - - def _make_spec_file(self): - spec_file = old_bdist_rpm._make_spec_file(self) - - # Replace hardcoded setup.py script name - # with the real setup script name. - setup_py = os.path.basename(sys.argv[0]) - if setup_py == 'setup.py': - return spec_file - new_spec_file = [] - for line in spec_file: - line = line.replace('setup.py', setup_py) - new_spec_file.append(line) - return new_spec_file diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_cov_corr.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_cov_corr.py deleted file mode 100644 index 23a9656193d2ccaf3ad64824510d60223ca9e6a9..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_cov_corr.py +++ /dev/null @@ -1,458 +0,0 @@ -import numpy as np -import pytest - -import pandas.util._test_decorators as td - -import pandas as pd -from pandas import ( - DataFrame, - Series, - isna, -) -import pandas._testing as tm - - -class TestDataFrameCov: - def test_cov(self, float_frame, float_string_frame): - # min_periods no NAs (corner case) - expected = float_frame.cov() - result = float_frame.cov(min_periods=len(float_frame)) - - tm.assert_frame_equal(expected, result) - - result = float_frame.cov(min_periods=len(float_frame) + 1) - assert isna(result.values).all() - - # with NAs - frame = float_frame.copy() - frame.iloc[:5, frame.columns.get_loc("A")] = np.nan - frame.iloc[5:10, frame.columns.get_loc("B")] = np.nan - result = frame.cov(min_periods=len(frame) - 8) - expected = frame.cov() - expected.loc["A", "B"] = np.nan - expected.loc["B", "A"] = np.nan - tm.assert_frame_equal(result, expected) - - # regular - result = frame.cov() - expected = frame["A"].cov(frame["C"]) - tm.assert_almost_equal(result["A"]["C"], expected) - - # fails on non-numeric types - with pytest.raises(ValueError, match="could not convert string to float"): - float_string_frame.cov() - result = float_string_frame.cov(numeric_only=True) - expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].cov() - tm.assert_frame_equal(result, expected) - - # Single column frame - df = DataFrame(np.linspace(0.0, 1.0, 10)) - result = df.cov() - expected = DataFrame( - np.cov(df.values.T).reshape((1, 1)), index=df.columns, columns=df.columns - ) - tm.assert_frame_equal(result, expected) - df.loc[0] = np.nan - result = df.cov() - expected = DataFrame( - np.cov(df.values[1:].T).reshape((1, 1)), - index=df.columns, - columns=df.columns, - ) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("test_ddof", [None, 0, 1, 2, 3]) - def test_cov_ddof(self, test_ddof): - # GH#34611 - np_array1 = np.random.default_rng(2).random(10) - np_array2 = np.random.default_rng(2).random(10) - df = DataFrame({0: np_array1, 1: np_array2}) - result = df.cov(ddof=test_ddof) - expected_np = np.cov(np_array1, np_array2, ddof=test_ddof) - expected = DataFrame(expected_np) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])] - ) - def test_cov_nullable_integer(self, other_column): - # https://github.com/pandas-dev/pandas/issues/33803 - data = DataFrame({"a": pd.array([1, 2, None]), "b": other_column}) - result = data.cov() - arr = np.array([[0.5, 0.5], [0.5, 1.0]]) - expected = DataFrame(arr, columns=["a", "b"], index=["a", "b"]) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("numeric_only", [True, False]) - def test_cov_numeric_only(self, numeric_only): - # when dtypes of pandas series are different - # then ndarray will have dtype=object, - # so it need to be properly handled - df = DataFrame({"a": [1, 0], "c": ["x", "y"]}) - expected = DataFrame(0.5, index=["a"], columns=["a"]) - if numeric_only: - result = df.cov(numeric_only=numeric_only) - tm.assert_frame_equal(result, expected) - else: - with pytest.raises(ValueError, match="could not convert string to float"): - df.cov(numeric_only=numeric_only) - - -class TestDataFrameCorr: - # DataFrame.corr(), as opposed to DataFrame.corrwith - - @pytest.mark.parametrize("method", ["pearson", "kendall", "spearman"]) - def test_corr_scipy_method(self, float_frame, method): - pytest.importorskip("scipy") - float_frame.loc[float_frame.index[:5], "A"] = np.nan - float_frame.loc[float_frame.index[5:10], "B"] = np.nan - float_frame.loc[float_frame.index[:10], "A"] = float_frame["A"][10:20] - - correls = float_frame.corr(method=method) - expected = float_frame["A"].corr(float_frame["C"], method=method) - tm.assert_almost_equal(correls["A"]["C"], expected) - - # --------------------------------------------------------------------- - - def test_corr_non_numeric(self, float_string_frame): - with pytest.raises(ValueError, match="could not convert string to float"): - float_string_frame.corr() - result = float_string_frame.corr(numeric_only=True) - expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].corr() - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"]) - def test_corr_nooverlap(self, meth): - # nothing in common - pytest.importorskip("scipy") - df = DataFrame( - { - "A": [1, 1.5, 1, np.nan, np.nan, np.nan], - "B": [np.nan, np.nan, np.nan, 1, 1.5, 1], - "C": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], - } - ) - rs = df.corr(meth) - assert isna(rs.loc["A", "B"]) - assert isna(rs.loc["B", "A"]) - assert rs.loc["A", "A"] == 1 - assert rs.loc["B", "B"] == 1 - assert isna(rs.loc["C", "C"]) - - @pytest.mark.parametrize("meth", ["pearson", "spearman"]) - def test_corr_constant(self, meth): - # constant --> all NA - df = DataFrame( - { - "A": [1, 1, 1, np.nan, np.nan, np.nan], - "B": [np.nan, np.nan, np.nan, 1, 1, 1], - } - ) - rs = df.corr(meth) - assert isna(rs.values).all() - - @pytest.mark.filterwarnings("ignore::RuntimeWarning") - @pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"]) - def test_corr_int_and_boolean(self, meth): - # when dtypes of pandas series are different - # then ndarray will have dtype=object, - # so it need to be properly handled - pytest.importorskip("scipy") - df = DataFrame({"a": [True, False], "b": [1, 0]}) - - expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"]) - result = df.corr(meth) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("method", ["cov", "corr"]) - def test_corr_cov_independent_index_column(self, method): - # GH#14617 - df = DataFrame( - np.random.default_rng(2).standard_normal(4 * 10).reshape(10, 4), - columns=list("abcd"), - ) - result = getattr(df, method)() - assert result.index is not result.columns - assert result.index.equals(result.columns) - - def test_corr_invalid_method(self): - # GH#22298 - df = DataFrame(np.random.default_rng(2).normal(size=(10, 2))) - msg = "method must be either 'pearson', 'spearman', 'kendall', or a callable, " - with pytest.raises(ValueError, match=msg): - df.corr(method="____") - - def test_corr_int(self): - # dtypes other than float64 GH#1761 - df = DataFrame({"a": [1, 2, 3, 4], "b": [1, 2, 3, 4]}) - - df.cov() - df.corr() - - @pytest.mark.parametrize( - "nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])] - ) - @pytest.mark.parametrize( - "other_column", - [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.0, 2.0, np.nan])], - ) - @pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"]) - def test_corr_nullable_integer(self, nullable_column, other_column, method): - # https://github.com/pandas-dev/pandas/issues/33803 - pytest.importorskip("scipy") - data = DataFrame({"a": nullable_column, "b": other_column}) - result = data.corr(method=method) - expected = DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"]) - tm.assert_frame_equal(result, expected) - - def test_corr_item_cache(self, using_copy_on_write): - # Check that corr does not lead to incorrect entries in item_cache - - df = DataFrame({"A": range(10)}) - df["B"] = range(10)[::-1] - - ser = df["A"] # populate item_cache - assert len(df._mgr.arrays) == 2 # i.e. 2 blocks - - _ = df.corr(numeric_only=True) - - if using_copy_on_write: - ser.iloc[0] = 99 - assert df.loc[0, "A"] == 0 - else: - # Check that the corr didn't break link between ser and df - ser.values[0] = 99 - assert df.loc[0, "A"] == 99 - assert df["A"] is ser - assert df.values[0, 0] == 99 - - @pytest.mark.parametrize("length", [2, 20, 200, 2000]) - def test_corr_for_constant_columns(self, length): - # GH: 37448 - df = DataFrame(length * [[0.4, 0.1]], columns=["A", "B"]) - result = df.corr() - expected = DataFrame( - {"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"] - ) - tm.assert_frame_equal(result, expected) - - def test_calc_corr_small_numbers(self): - # GH: 37452 - df = DataFrame( - {"A": [1.0e-20, 2.0e-20, 3.0e-20], "B": [1.0e-20, 2.0e-20, 3.0e-20]} - ) - result = df.corr() - expected = DataFrame({"A": [1.0, 1.0], "B": [1.0, 1.0]}, index=["A", "B"]) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"]) - def test_corr_min_periods_greater_than_length(self, method): - pytest.importorskip("scipy") - df = DataFrame({"A": [1, 2], "B": [1, 2]}) - result = df.corr(method=method, min_periods=3) - expected = DataFrame( - {"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"] - ) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"]) - @pytest.mark.parametrize("numeric_only", [True, False]) - def test_corr_numeric_only(self, meth, numeric_only): - # when dtypes of pandas series are different - # then ndarray will have dtype=object, - # so it need to be properly handled - pytest.importorskip("scipy") - df = DataFrame({"a": [1, 0], "b": [1, 0], "c": ["x", "y"]}) - expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"]) - if numeric_only: - result = df.corr(meth, numeric_only=numeric_only) - tm.assert_frame_equal(result, expected) - else: - with pytest.raises(ValueError, match="could not convert string to float"): - df.corr(meth, numeric_only=numeric_only) - - -class TestDataFrameCorrWith: - @pytest.mark.parametrize( - "dtype", - [ - "float64", - "Float64", - pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")), - ], - ) - def test_corrwith(self, datetime_frame, dtype): - datetime_frame = datetime_frame.astype(dtype) - - a = datetime_frame - noise = Series(np.random.default_rng(2).standard_normal(len(a)), index=a.index) - - b = datetime_frame.add(noise, axis=0) - - # make sure order does not matter - b = b.reindex(columns=b.columns[::-1], index=b.index[::-1][10:]) - del b["B"] - - colcorr = a.corrwith(b, axis=0) - tm.assert_almost_equal(colcorr["A"], a["A"].corr(b["A"])) - - rowcorr = a.corrwith(b, axis=1) - tm.assert_series_equal(rowcorr, a.T.corrwith(b.T, axis=0)) - - dropped = a.corrwith(b, axis=0, drop=True) - tm.assert_almost_equal(dropped["A"], a["A"].corr(b["A"])) - assert "B" not in dropped - - dropped = a.corrwith(b, axis=1, drop=True) - assert a.index[-1] not in dropped.index - - # non time-series data - index = ["a", "b", "c", "d", "e"] - columns = ["one", "two", "three", "four"] - df1 = DataFrame( - np.random.default_rng(2).standard_normal((5, 4)), - index=index, - columns=columns, - ) - df2 = DataFrame( - np.random.default_rng(2).standard_normal((4, 4)), - index=index[:4], - columns=columns, - ) - correls = df1.corrwith(df2, axis=1) - for row in index[:4]: - tm.assert_almost_equal(correls[row], df1.loc[row].corr(df2.loc[row])) - - def test_corrwith_with_objects(self): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame() - cols = ["A", "B", "C", "D"] - - df1["obj"] = "foo" - df2["obj"] = "bar" - - with pytest.raises(TypeError, match="Could not convert"): - df1.corrwith(df2) - result = df1.corrwith(df2, numeric_only=True) - expected = df1.loc[:, cols].corrwith(df2.loc[:, cols]) - tm.assert_series_equal(result, expected) - - with pytest.raises(TypeError, match="unsupported operand type"): - df1.corrwith(df2, axis=1) - result = df1.corrwith(df2, axis=1, numeric_only=True) - expected = df1.loc[:, cols].corrwith(df2.loc[:, cols], axis=1) - tm.assert_series_equal(result, expected) - - def test_corrwith_series(self, datetime_frame): - result = datetime_frame.corrwith(datetime_frame["A"]) - expected = datetime_frame.apply(datetime_frame["A"].corr) - - tm.assert_series_equal(result, expected) - - def test_corrwith_matches_corrcoef(self): - df1 = DataFrame(np.arange(10000), columns=["a"]) - df2 = DataFrame(np.arange(10000) ** 2, columns=["a"]) - c1 = df1.corrwith(df2)["a"] - c2 = np.corrcoef(df1["a"], df2["a"])[0][1] - - tm.assert_almost_equal(c1, c2) - assert c1 < 1 - - @pytest.mark.parametrize("numeric_only", [True, False]) - def test_corrwith_mixed_dtypes(self, numeric_only): - # GH#18570 - df = DataFrame( - {"a": [1, 4, 3, 2], "b": [4, 6, 7, 3], "c": ["a", "b", "c", "d"]} - ) - s = Series([0, 6, 7, 3]) - if numeric_only: - result = df.corrwith(s, numeric_only=numeric_only) - corrs = [df["a"].corr(s), df["b"].corr(s)] - expected = Series(data=corrs, index=["a", "b"]) - tm.assert_series_equal(result, expected) - else: - with pytest.raises( - ValueError, - match="could not convert string to float", - ): - df.corrwith(s, numeric_only=numeric_only) - - def test_corrwith_index_intersection(self): - df1 = DataFrame( - np.random.default_rng(2).random(size=(10, 2)), columns=["a", "b"] - ) - df2 = DataFrame( - np.random.default_rng(2).random(size=(10, 3)), columns=["a", "b", "c"] - ) - - result = df1.corrwith(df2, drop=True).index.sort_values() - expected = df1.columns.intersection(df2.columns).sort_values() - tm.assert_index_equal(result, expected) - - def test_corrwith_index_union(self): - df1 = DataFrame( - np.random.default_rng(2).random(size=(10, 2)), columns=["a", "b"] - ) - df2 = DataFrame( - np.random.default_rng(2).random(size=(10, 3)), columns=["a", "b", "c"] - ) - - result = df1.corrwith(df2, drop=False).index.sort_values() - expected = df1.columns.union(df2.columns).sort_values() - tm.assert_index_equal(result, expected) - - def test_corrwith_dup_cols(self): - # GH#21925 - df1 = DataFrame(np.vstack([np.arange(10)] * 3).T) - df2 = df1.copy() - df2 = pd.concat((df2, df2[0]), axis=1) - - result = df1.corrwith(df2) - expected = Series(np.ones(4), index=[0, 0, 1, 2]) - tm.assert_series_equal(result, expected) - - def test_corr_numerical_instabilities(self): - # GH#45640 - df = DataFrame([[0.2, 0.4], [0.4, 0.2]]) - result = df.corr() - expected = DataFrame({0: [1.0, -1.0], 1: [-1.0, 1.0]}) - tm.assert_frame_equal(result - 1, expected - 1, atol=1e-17) - - def test_corrwith_spearman(self): - # GH#21925 - pytest.importorskip("scipy") - df = DataFrame(np.random.default_rng(2).random(size=(100, 3))) - result = df.corrwith(df**2, method="spearman") - expected = Series(np.ones(len(result))) - tm.assert_series_equal(result, expected) - - def test_corrwith_kendall(self): - # GH#21925 - pytest.importorskip("scipy") - df = DataFrame(np.random.default_rng(2).random(size=(100, 3))) - result = df.corrwith(df**2, method="kendall") - expected = Series(np.ones(len(result))) - tm.assert_series_equal(result, expected) - - def test_corrwith_spearman_with_tied_data(self): - # GH#48826 - pytest.importorskip("scipy") - df1 = DataFrame( - { - "A": [1, np.nan, 7, 8], - "B": [False, True, True, False], - "C": [10, 4, 9, 3], - } - ) - df2 = df1[["B", "C"]] - result = (df1 + 1).corrwith(df2.B, method="spearman") - expected = Series([0.0, 1.0, 0.0], index=["A", "B", "C"]) - tm.assert_series_equal(result, expected) - - df_bool = DataFrame( - {"A": [True, True, False, False], "B": [True, False, False, True]} - ) - ser_bool = Series([True, True, False, True]) - result = df_bool.corrwith(ser_bool) - expected = Series([0.57735, 0.57735], index=["A", "B"]) - tm.assert_series_equal(result, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/urllib3/util/ssltransport.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/urllib3/util/ssltransport.py deleted file mode 100644 index 4a7105d17916a7237f3df6e59d65ca82375f8803..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/urllib3/util/ssltransport.py +++ /dev/null @@ -1,221 +0,0 @@ -import io -import socket -import ssl - -from ..exceptions import ProxySchemeUnsupported -from ..packages import six - -SSL_BLOCKSIZE = 16384 - - -class SSLTransport: - """ - The SSLTransport wraps an existing socket and establishes an SSL connection. - - Contrary to Python's implementation of SSLSocket, it allows you to chain - multiple TLS connections together. It's particularly useful if you need to - implement TLS within TLS. - - The class supports most of the socket API operations. - """ - - @staticmethod - def _validate_ssl_context_for_tls_in_tls(ssl_context): - """ - Raises a ProxySchemeUnsupported if the provided ssl_context can't be used - for TLS in TLS. - - The only requirement is that the ssl_context provides the 'wrap_bio' - methods. - """ - - if not hasattr(ssl_context, "wrap_bio"): - if six.PY2: - raise ProxySchemeUnsupported( - "TLS in TLS requires SSLContext.wrap_bio() which isn't " - "supported on Python 2" - ) - else: - raise ProxySchemeUnsupported( - "TLS in TLS requires SSLContext.wrap_bio() which isn't " - "available on non-native SSLContext" - ) - - def __init__( - self, socket, ssl_context, server_hostname=None, suppress_ragged_eofs=True - ): - """ - Create an SSLTransport around socket using the provided ssl_context. - """ - self.incoming = ssl.MemoryBIO() - self.outgoing = ssl.MemoryBIO() - - self.suppress_ragged_eofs = suppress_ragged_eofs - self.socket = socket - - self.sslobj = ssl_context.wrap_bio( - self.incoming, self.outgoing, server_hostname=server_hostname - ) - - # Perform initial handshake. - self._ssl_io_loop(self.sslobj.do_handshake) - - def __enter__(self): - return self - - def __exit__(self, *_): - self.close() - - def fileno(self): - return self.socket.fileno() - - def read(self, len=1024, buffer=None): - return self._wrap_ssl_read(len, buffer) - - def recv(self, len=1024, flags=0): - if flags != 0: - raise ValueError("non-zero flags not allowed in calls to recv") - return self._wrap_ssl_read(len) - - def recv_into(self, buffer, nbytes=None, flags=0): - if flags != 0: - raise ValueError("non-zero flags not allowed in calls to recv_into") - if buffer and (nbytes is None): - nbytes = len(buffer) - elif nbytes is None: - nbytes = 1024 - return self.read(nbytes, buffer) - - def sendall(self, data, flags=0): - if flags != 0: - raise ValueError("non-zero flags not allowed in calls to sendall") - count = 0 - with memoryview(data) as view, view.cast("B") as byte_view: - amount = len(byte_view) - while count < amount: - v = self.send(byte_view[count:]) - count += v - - def send(self, data, flags=0): - if flags != 0: - raise ValueError("non-zero flags not allowed in calls to send") - response = self._ssl_io_loop(self.sslobj.write, data) - return response - - def makefile( - self, mode="r", buffering=None, encoding=None, errors=None, newline=None - ): - """ - Python's httpclient uses makefile and buffered io when reading HTTP - messages and we need to support it. - - This is unfortunately a copy and paste of socket.py makefile with small - changes to point to the socket directly. - """ - if not set(mode) <= {"r", "w", "b"}: - raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) - - writing = "w" in mode - reading = "r" in mode or not writing - assert reading or writing - binary = "b" in mode - rawmode = "" - if reading: - rawmode += "r" - if writing: - rawmode += "w" - raw = socket.SocketIO(self, rawmode) - self.socket._io_refs += 1 - if buffering is None: - buffering = -1 - if buffering < 0: - buffering = io.DEFAULT_BUFFER_SIZE - if buffering == 0: - if not binary: - raise ValueError("unbuffered streams must be binary") - return raw - if reading and writing: - buffer = io.BufferedRWPair(raw, raw, buffering) - elif reading: - buffer = io.BufferedReader(raw, buffering) - else: - assert writing - buffer = io.BufferedWriter(raw, buffering) - if binary: - return buffer - text = io.TextIOWrapper(buffer, encoding, errors, newline) - text.mode = mode - return text - - def unwrap(self): - self._ssl_io_loop(self.sslobj.unwrap) - - def close(self): - self.socket.close() - - def getpeercert(self, binary_form=False): - return self.sslobj.getpeercert(binary_form) - - def version(self): - return self.sslobj.version() - - def cipher(self): - return self.sslobj.cipher() - - def selected_alpn_protocol(self): - return self.sslobj.selected_alpn_protocol() - - def selected_npn_protocol(self): - return self.sslobj.selected_npn_protocol() - - def shared_ciphers(self): - return self.sslobj.shared_ciphers() - - def compression(self): - return self.sslobj.compression() - - def settimeout(self, value): - self.socket.settimeout(value) - - def gettimeout(self): - return self.socket.gettimeout() - - def _decref_socketios(self): - self.socket._decref_socketios() - - def _wrap_ssl_read(self, len, buffer=None): - try: - return self._ssl_io_loop(self.sslobj.read, len, buffer) - except ssl.SSLError as e: - if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: - return 0 # eof, return 0. - else: - raise - - def _ssl_io_loop(self, func, *args): - """Performs an I/O loop between incoming/outgoing and the socket.""" - should_loop = True - ret = None - - while should_loop: - errno = None - try: - ret = func(*args) - except ssl.SSLError as e: - if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): - # WANT_READ, and WANT_WRITE are expected, others are not. - raise e - errno = e.errno - - buf = self.outgoing.read() - self.socket.sendall(buf) - - if errno is None: - should_loop = False - elif errno == ssl.SSL_ERROR_WANT_READ: - buf = self.socket.recv(SSL_BLOCKSIZE) - if buf: - self.incoming.write(buf) - else: - self.incoming.write_eof() - return ret diff --git a/spaces/pyodide-demo/self-hosted/networkx.js b/spaces/pyodide-demo/self-hosted/networkx.js deleted file mode 100644 index da6f992ddae71d4bfa0dfd5b45686bbcf1e86861..0000000000000000000000000000000000000000 --- a/spaces/pyodide-demo/self-hosted/networkx.js +++ /dev/null @@ -1 +0,0 @@ -var Module=typeof globalThis.__pyodide_module!=="undefined"?globalThis.__pyodide_module:{};if(!Module.expectedDataFileDownloads){Module.expectedDataFileDownloads=0}Module.expectedDataFileDownloads++;(function(){var loadPackage=function(metadata){var PACKAGE_PATH="";if(typeof window==="object"){PACKAGE_PATH=window["encodeURIComponent"](window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/")}else if(typeof process==="undefined"&&typeof location!=="undefined"){PACKAGE_PATH=encodeURIComponent(location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/")}var PACKAGE_NAME="networkx.data";var REMOTE_PACKAGE_BASE="networkx.data";if(typeof Module["locateFilePackage"]==="function"&&!Module["locateFile"]){Module["locateFile"]=Module["locateFilePackage"];err("warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)")}var REMOTE_PACKAGE_NAME=Module["locateFile"]?Module["locateFile"](REMOTE_PACKAGE_BASE,""):REMOTE_PACKAGE_BASE;var REMOTE_PACKAGE_SIZE=metadata["remote_package_size"];var PACKAGE_UUID=metadata["package_uuid"];function fetchRemotePackage(packageName,packageSize,callback,errback){if(typeof process==="object"){require("fs").readFile(packageName,(function(err,contents){if(err){errback(err)}else{callback(contents.buffer)}}));return}var xhr=new XMLHttpRequest;xhr.open("GET",packageName,true);xhr.responseType="arraybuffer";xhr.onprogress=function(event){var url=packageName;var size=packageSize;if(event.total)size=event.total;if(event.loaded){if(!xhr.addedTotal){xhr.addedTotal=true;if(!Module.dataFileDownloads)Module.dataFileDownloads={};Module.dataFileDownloads[url]={loaded:event.loaded,total:size}}else{Module.dataFileDownloads[url].loaded=event.loaded}var total=0;var loaded=0;var num=0;for(var download in Module.dataFileDownloads){var data=Module.dataFileDownloads[download];total+=data.total;loaded+=data.loaded;num++}total=Math.ceil(total*Module.expectedDataFileDownloads/num);if(Module["setStatus"])Module["setStatus"]("Downloading data... ("+loaded+"/"+total+")")}else if(!Module.dataFileDownloads){if(Module["setStatus"])Module["setStatus"]("Downloading data...")}};xhr.onerror=function(event){throw new Error("NetworkError for: "+packageName)};xhr.onload=function(event){if(xhr.status==200||xhr.status==304||xhr.status==206||xhr.status==0&&xhr.response){var packageData=xhr.response;callback(packageData)}else{throw new Error(xhr.statusText+" : "+xhr.responseURL)}};xhr.send(null)}function handleError(error){console.error("package error:",error)}var fetchedCallback=null;var fetched=Module["getPreloadedPackage"]?Module["getPreloadedPackage"](REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE):null;if(!fetched)fetchRemotePackage(REMOTE_PACKAGE_NAME,REMOTE_PACKAGE_SIZE,(function(data){if(fetchedCallback){fetchedCallback(data);fetchedCallback=null}else{fetched=data}}),handleError);function runWithFS(){function assert(check,msg){if(!check)throw msg+(new Error).stack}Module["FS_createPath"]("/","lib",true,true);Module["FS_createPath"]("/lib","python3.9",true,true);Module["FS_createPath"]("/lib/python3.9","site-packages",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages","networkx",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","algorithms",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","assortativity",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","bipartite",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","node_classification",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","centrality",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","community",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","components",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","connectivity",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","coloring",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","flow",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","minors",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","traversal",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","isomorphism",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","shortest_paths",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","link_analysis",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","operators",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","approximation",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/algorithms","tree",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","classes",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","generators",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","drawing",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","linalg",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","readwrite",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx/readwrite","json_graph",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","testing",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages/networkx","utils",true,true);Module["FS_createPath"]("/lib/python3.9/site-packages","networkx-2.6.3-py3.9.egg-info",true,true);Module["FS_createPath"]("/","share",true,true);Module["FS_createPath"]("/share","doc",true,true);Module["FS_createPath"]("/share/doc","networkx-2.6.3",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3","examples",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3/examples","algorithms",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3/examples","basic",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3/examples","3d_drawing",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3/examples","drawing",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3/examples","graph",true,true);Module["FS_createPath"]("/share/doc/networkx-2.6.3/examples","subclass",true,true);function processPackageData(arrayBuffer){assert(arrayBuffer,"Loading data file failed.");assert(arrayBuffer instanceof ArrayBuffer,"bad input to processPackageData");var byteArray=new Uint8Array(arrayBuffer);var curr;var compressedData={data:null,cachedOffset:2707174,cachedIndexes:[-1,-1],cachedChunks:[null,null],offsets:[0,900,2027,3185,4036,5327,6679,7686,8757,9759,11116,12483,13844,15077,16363,17631,18793,20048,21432,22736,23905,25315,26715,27973,29025,30384,31674,33092,34423,35821,37163,38426,39787,41098,42225,43611,44844,46251,47222,48443,49248,49912,50572,51627,52973,54145,55385,56741,58046,59320,60646,62023,63308,64546,65870,67183,68502,69624,70898,72071,73450,74747,76290,77734,79023,80505,81887,83212,84143,84999,86173,87240,88703,90025,91244,92211,93092,94538,95923,96995,98392,99623,100981,102349,103913,105313,106490,107750,109118,110368,111756,113094,114407,115726,117094,118255,119235,120305,121264,122658,124006,125467,126705,128002,129333,130641,131726,133151,134513,135948,137391,138733,139790,140986,142296,143469,144705,146076,147429,148734,149914,151149,152553,153698,155143,156494,157905,159260,160039,161095,162256,163120,164394,165763,167091,168278,169450,170718,171870,173153,174601,175906,176936,178268,179500,180525,181821,182952,184070,185493,186840,188038,189302,190721,192190,193636,194984,196142,197359,198777,200160,201337,202709,203783,205171,206507,207866,209236,210608,211952,213367,214738,216076,217400,218820,220075,221558,222906,224113,225258,226603,227896,228965,230171,231497,232850,234017,235269,236367,237461,238544,239543,240622,241726,242905,244026,244932,245787,246751,248107,249452,250831,252319,253411,254768,255954,257085,258238,259521,260709,262163,263007,264109,265218,266181,267300,268202,269287,270148,271096,272124,273054,274424,275535,276745,277799,278631,279683,280899,282093,283218,284286,285252,286659,288203,289568,290552,291750,293087,294060,295317,296475,297452,298778,299749,301159,302054,303188,304163,305261,306202,307044,307831,308773,309799,310973,312188,313536,314806,316106,317360,318825,320238,321692,322893,324259,325366,326481,327408,328618,329821,331110,332321,333525,334563,335569,336937,337892,339120,340550,341824,343323,344518,345881,347174,348588,349969,350887,351881,353037,354233,355710,357142,358409,359682,361068,362467,363645,364721,365789,366915,367929,369140,370473,371714,373017,374292,375666,377064,378145,379211,380503,381802,382836,383986,385309,386581,387932,389042,390212,391408,392665,393976,395331,396552,397894,399237,400477,401842,403032,404344,405754,407264,408498,409572,410778,411681,412989,414359,415784,417011,418370,419529,420725,422032,423210,424464,425622,427010,428260,429684,430981,432179,433516,434867,436295,437350,438565,439754,440975,442144,443438,444761,445993,447189,448507,449781,451157,452394,453724,454958,456149,457322,458595,459908,461199,462537,463932,465314,466691,468144,469487,470840,472180,473648,475029,476092,477468,478689,479959,481088,482440,483788,485213,486627,487955,489366,490694,491940,493178,494548,495881,497129,498438,499559,500922,502117,503557,504857,506e3,507355,508460,509619,510678,512023,513426,514689,516091,517312,518123,519306,520666,521989,523328,524251,525584,526969,528212,529659,530810,532222,533764,535098,536577,538052,539351,540801,542170,543689,545106,546628,547595,548779,550093,551368,552855,554282,555778,557147,558043,559331,560692,562187,563071,564169,565457,566961,568104,568964,569769,570854,572350,573580,574379,575687,577092,578457,579966,581348,582828,584249,585421,586805,588018,589447,590799,592049,593389,594760,596302,597749,599147,600478,601826,603255,604713,606191,607452,608884,610107,611337,612684,613599,614880,615973,617313,618636,619934,621273,622627,623962,625357,626734,628176,629492,630729,631776,633083,634481,635800,636869,637943,639228,640246,641310,642297,643551,644921,646436,647646,648819,649885,650954,652317,653637,654913,656245,657449,658577,659545,660765,662050,663082,664176,665371,666583,667859,668913,669946,671219,672466,673719,674958,676309,677510,678870,680161,681431,682664,683888,685196,686506,687554,688838,690026,691379,692688,693946,695225,696570,697744,699057,700418,701417,702636,703926,705197,706501,707805,709075,710321,711701,712844,714165,715243,716357,717719,718986,720151,721463,722858,724169,725623,727030,728461,729953,731208,732580,734030,735307,736494,737767,739001,740372,741711,742903,744235,745479,746718,747668,748801,750173,751554,752966,754356,755739,757031,758469,759899,760972,761945,763207,764430,765713,766996,768208,769515,770909,771865,772798,773582,774511,775890,777086,778484,779712,780945,782159,783473,784782,785862,786983,787861,789129,790468,791800,793004,793966,795008,796402,797588,798619,799826,801087,802278,803348,804592,805851,807105,808292,809453,810590,811838,813034,814342,815612,816942,818238,819546,820805,822098,823393,824558,825852,827125,828432,829707,830960,832177,833414,834554,835914,837281,838427,839577,840533,841605,842553,843667,844787,846006,847290,848435,849225,850338,851409,852595,853871,855017,856080,857158,858445,859729,860887,862169,863447,864651,865979,867187,868444,869868,871153,872346,873747,874899,876200,877371,878700,880071,881416,882697,883989,885345,886726,888071,889426,890739,892021,893263,894560,895833,897192,898369,899527,900562,901867,903117,904306,905595,906691,907880,908949,910078,911199,912536,913837,915046,916265,916942,917674,918771,919844,921045,921995,923113,924168,925204,926393,927500,928716,929908,930866,931965,933094,933837,934939,936161,937395,938758,940103,941369,942665,943857,944749,945962,946653,947823,948916,950245,950935,951620,952154,952986,953948,955176,955884,957055,958210,959274,960133,961228,962435,963787,965074,966313,967106,968134,969531,970756,972123,973436,974677,975918,977068,977928,979043,980411,981729,983040,984415,985738,986984,988214,989328,990179,991258,992391,993121,994415,995578,996836,998071,999378,1000567,1001769,1002982,1004277,1005470,1006585,1007872,1009202,1010494,1011847,1013202,1014501,1015900,1017234,1018648,1019995,1021354,1022629,1023838,1025192,1026524,1027887,1029189,1030565,1031771,1033136,1034430,1035627,1036644,1037843,1039082,1040135,1041462,1042867,1043972,1045362,1046716,1048163,1049405,1050744,1052083,1053490,1054361,1055782,1057108,1058561,1059920,1061390,1062636,1064006,1065283,1066799,1068174,1069708,1070969,1072070,1073170,1074399,1075650,1076706,1077914,1079193,1080030,1080644,1081800,1082778,1083778,1085029,1086386,1087497,1088775,1090075,1091365,1092679,1094110,1095519,1096794,1098115,1099505,1100815,1101938,1103378,1104512,1105774,1107051,1108415,1109776,1111273,1112444,1113746,1114816,1116004,1117408,1118723,1119973,1121149,1122558,1123938,1125398,1126849,1128268,1129620,1131067,1132531,1133868,1135195,1136528,1137821,1139131,1140521,1141908,1143227,1144631,1145900,1147204,1148509,1149973,1151324,1152814,1154098,1155507,1156820,1158064,1159210,1160308,1161087,1162162,1163225,1164116,1165375,1166627,1167969,1169367,1170764,1172097,1173461,1174813,1176168,1177399,1178540,1179618,1180498,1181797,1183026,1184293,1185560,1186818,1188221,1189526,1190797,1191951,1192874,1193997,1194871,1196020,1196990,1197979,1199103,1200152,1201269,1202646,1204104,1205442,1206305,1207656,1208794,1209789,1210969,1212035,1213066,1214233,1215476,1216443,1217467,1218705,1219912,1220946,1221894,1222904,1224232,1225280,1226305,1227495,1228645,1229491,1230874,1232234,1233427,1234628,1235844,1236978,1238194,1239186,1240165,1241350,1242626,1243630,1244483,1245746,1247126,1248573,1249933,1250853,1252028,1253192,1254289,1255360,1256560,1257686,1258936,1259970,1260870,1262136,1263367,1264469,1265523,1266774,1267699,1268814,1270057,1271275,1272450,1273493,1274790,1275994,1277189,1278452,1279548,1280667,1281741,1282922,1284195,1285399,1286522,1287848,1289219,1290594,1291898,1292737,1294023,1295277,1296392,1297678,1298758,1300025,1301137,1302215,1303226,1304410,1305719,1306949,1308322,1309690,1311096,1312019,1313097,1314343,1315657,1316989,1318026,1319246,1320328,1321443,1322696,1323935,1325072,1326266,1327543,1328745,1329871,1331099,1332381,1333240,1333885,1335334,1336692,1337829,1339029,1340114,1341295,1342489,1343277,1344019,1344742,1345634,1346802,1347851,1348742,1349472,1350559,1351847,1353071,1354001,1354968,1355930,1357190,1358500,1359814,1361070,1362493,1363716,1365040,1366295,1367556,1368800,1370084,1371272,1372591,1373844,1375098,1376264,1377668,1379027,1380326,1381742,1382905,1384345,1385670,1386797,1388038,1389278,1390641,1391922,1392945,1394261,1395500,1396792,1398055,1399364,1400813,1402115,1403519,1404873,1406376,1407828,1409078,1410326,1411554,1412953,1414047,1415114,1416494,1417959,1419139,1420385,1421595,1422750,1424071,1425543,1426908,1428258,1429545,1430937,1432252,1433687,1435076,1436526,1437955,1439288,1440779,1442170,1443523,1444980,1446352,1447826,1449268,1450670,1452066,1453448,1454777,1456104,1457365,1458659,1459717,1460840,1461905,1463081,1464365,1465803,1466867,1468316,1469510,1470775,1472096,1473478,1474566,1475486,1476812,1478074,1479363,1480793,1481820,1482845,1483987,1485274,1486591,1488025,1489362,1490715,1492024,1493455,1494903,1496139,1497412,1498772,1500023,1501176,1502454,1503514,1504780,1506082,1507337,1508379,1509758,1511132,1512451,1513667,1515042,1516292,1517747,1519125,1520478,1521931,1523144,1524445,1525752,1526972,1528310,1529466,1530459,1531889,1533152,1534530,1535783,1536856,1538316,1539674,1540824,1542184,1543027,1544048,1544997,1545985,1546826,1547989,1548733,1549505,1550053,1551079,1551611,1552171,1552784,1553358,1553902,1554416,1555753,1557185,1558639,1560100,1561414,1562763,1564079,1565409,1566749,1568103,1569499,1570915,1572145,1573519,1575567,1577615,1579663,1581711,1583269,1584417,1585823,1587239,1588697,1590022,1591327,1592725,1594031,1595413,1596772,1598259,1599564,1600958,1602307,1603688,1605097,1606352,1607504,1608662,1609544,1611e3,1612437,1613713,1615211,1616424,1617563,1618722,1620153,1621520,1622788,1624034,1625266,1626279,1627626,1628973,1630283,1631554,1632844,1634070,1635366,1636366,1637410,1638633,1639893,1641206,1642394,1643079,1644323,1645527,1646743,1647901,1649331,1650610,1651873,1653118,1654431,1655752,1657099,1658407,1659470,1660722,1661983,1663242,1664528,1665701,1667080,1668517,1669870,1671192,1672524,1673755,1675167,1676545,1677845,1679168,1680571,1681930,1682855,1683898,1684813,1685983,1687253,1688489,1689733,1691041,1692254,1693490,1694639,1695921,1697200,1698613,1700056,1701329,1702445,1703477,1704605,1705472,1706113,1707196,1708044,1708896,1709708,1710674,1711728,1712752,1713715,1714549,1715617,1716762,1717970,1719608,1720860,1722338,1723794,1725080,1725998,1727084,1728218,1729430,1730202,1731609,1732700,1733740,1734948,1736522,1737430,1738941,1740333,1741710,1743040,1744352,1745686,1747058,1748414,1749633,1750888,1752224,1753432,1754491,1755668,1756778,1757582,1758771,1759885,1760653,1761891,1762985,1764120,1765329,1766302,1767470,1768853,1769793,1770791,1772058,1773061,1774179,1775520,1776873,1778151,1779515,1780670,1781946,1782877,1784298,1785704,1786830,1788121,1789018,1790395,1791760,1793120,1794493,1795686,1797051,1798170,1799312,1800327,1801641,1802809,1804035,1805324,1806476,1807708,1809018,1810395,1811738,1813008,1814285,1815517,1816716,1817905,1818846,1819989,1821073,1822333,1823724,1824789,1825865,1827028,1828453,1829693,1830918,1832316,1833727,1835099,1836468,1837655,1838995,1840265,1841481,1842783,1843832,1845044,1846138,1847436,1848341,1849426,1850435,1851561,1852517,1853633,1854977,1856135,1857224,1858487,1859606,1860546,1861615,1862874,1864278,1865419,1866491,1867575,1868873,1870183,1871513,1872751,1874293,1875563,1876841,1878107,1879302,1879909,1880619,1881470,1882337,1883041,1883586,1884072,1884596,1885129,1885683,1886221,1886811,1887381,1887975,1888604,1889375,1890944,1892083,1893083,1894211,1895320,1896558,1897795,1898977,1899880,1901087,1902267,1903339,1904431,1905485,1906704,1907875,1908920,1910039,1911250,1912458,1913689,1914760,1915949,1917051,1918280,1919421,1920535,1921663,1922549,1923424,1924250,1925095,1925888,1926710,1927574,1928405,1929241,1930054,1930925,1931804,1932643,1933469,1934299,1935110,1936055,1936957,1937813,1938694,1939562,1940406,1941241,1942076,1942938,1943762,1944573,1945367,1946315,1947328,1948275,1949254,1950204,1951165,1952108,1953077,1954024,1954967,1955945,1956897,1957803,1958761,1959697,1960647,1961580,1962527,1963459,1964390,1965337,1966270,1967132,1968045,1968977,1969849,1970748,1971615,1972477,1973378,1974266,1975153,1976051,1976936,1977789,1978653,1979522,1980374,1981238,1982058,1982853,1983595,1984349,1985326,1986330,1987308,1988102,1989020,1989976,1990919,1991885,1992860,1993829,1994780,1995757,1996713,1997684,1998634,1999594,2000554,2001505,2002445,2003371,2004318,2005249,2006188,2007121,2008075,2009002,2009922,2010856,2011747,2012688,2013586,2014497,2015432,2016366,2017281,2018176,2019062,2019930,2020822,2021686,2022588,2023484,2024355,2025220,2026064,2026896,2027721,2028514,2029291,2030057,2031001,2031956,2032872,2033827,2034731,2035653,2036561,2037449,2038285,2039181,2040031,2040880,2041683,2042528,2043358,2044219,2045069,2045909,2046777,2047631,2048495,2049341,2050178,2051006,2051916,2052737,2053574,2054351,2055225,2056079,2056941,2057766,2058614,2059423,2060324,2061141,2061952,2062781,2063695,2064548,2065409,2066200,2067030,2067871,2068750,2069568,2070486,2071332,2072196,2073022,2073828,2074661,2075508,2076399,2077267,2078117,2078955,2079891,2080747,2081621,2082450,2083284,2084170,2085038,2085917,2086784,2087651,2088501,2089360,2090187,2091075,2091994,2092801,2093669,2094498,2095333,2096189,2097064,2097891,2098826,2099734,2100587,2101408,2102314,2103143,2103983,2104841,2105640,2106491,2107323,2108134,2109015,2109874,2110716,2111482,2112411,2113312,2114237,2115099,2115966,2116856,2117740,2118598,2119457,2120320,2121176,2122015,2122873,2123669,2124455,2125205,2126185,2127122,2128089,2129032,2129981,2130900,2131850,2132772,2133709,2134644,2135576,2136484,2137382,2138296,2139182,2140077,2140977,2141859,2142730,2143607,2144450,2145295,2146153,2147029,2147882,2148722,2149569,2150416,2151225,2152010,2152785,2153779,2154762,2155744,2156750,2157765,2158758,2159764,2160718,2161667,2162671,2163670,2164608,2165572,2166541,2167491,2168429,2169406,2170354,2171333,2172295,2173241,2174187,2175128,2176110,2177058,2178013,2178947,2179884,2180840,2181793,2182735,2183692,2184645,2185576,2186467,2187375,2188241,2189155,2190069,2190964,2191840,2192727,2193574,2194504,2195389,2196264,2197116,2197967,2198778,2199528,2200275,2201131,2202048,2202945,2203774,2204691,2205598,2206502,2207380,2208285,2209147,2210009,2210902,2211747,2212600,2213423,2214300,2215147,2215996,2216858,2217710,2218521,2219284,2220117,2220956,2221796,2222627,2223442,2224196,2225057,2225903,2226754,2227588,2228573,2229516,2230518,2231537,2232501,2233474,2234419,2235369,2236324,2237294,2238202,2239166,2240135,2241088,2242030,2242925,2243847,2244790,2245741,2246670,2247616,2248549,2249473,2250411,2251320,2252268,2253212,2254094,2255030,2255925,2256801,2257729,2258640,2259517,2260409,2261283,2262148,2263107,2263970,2264820,2265698,2266537,2267350,2268159,2268932,2269667,2270403,2271303,2272135,2272988,2273863,2274683,2275512,2276377,2277188,2278066,2278914,2279761,2280605,2281458,2282291,2283159,2283989,2284940,2285826,2286711,2287574,2288478,2289364,2290244,2291125,2292008,2292878,2293752,2294627,2295475,2296313,2297155,2297986,2298808,2299664,2300488,2301379,2302266,2303098,2303942,2304759,2305606,2306434,2307302,2308151,2309045,2309889,2310743,2311544,2312523,2313455,2314417,2315354,2316282,2317185,2318067,2318962,2319893,2320820,2321729,2322656,2323578,2324499,2325387,2326289,2327187,2328079,2328955,2329825,2330681,2331538,2332430,2333303,2334212,2335053,2335864,2336652,2337385,2338148,2338897,2339795,2340640,2341470,2342360,2343330,2344309,2345237,2346205,2347156,2348065,2349028,2349978,2350931,2351881,2352826,2353789,2354761,2355718,2356664,2357565,2358504,2359377,2360230,2361174,2362120,2363062,2364008,2364961,2365896,2366803,2367714,2368651,2369570,2370476,2371412,2372326,2373240,2374175,2375101,2376026,2376937,2377861,2378796,2379722,2380654,2381576,2382480,2383310,2384229,2385085,2385939,2386798,2387687,2388605,2389490,2390361,2391210,2392082,2392919,2393724,2394520,2395274,2396037,2396921,2397846,2398733,2399637,2400573,2401455,2402391,2403302,2404231,2405137,2406050,2406948,2407845,2408722,2409576,2410440,2411328,2412163,2413052,2413885,2414737,2415556,2416344,2417092,2418017,2418951,2419877,2420782,2421689,2422583,2423495,2424381,2425278,2426160,2427044,2427924,2428793,2429648,2430494,2431330,2432171,2432978,2433817,2434609,2435390,2436278,2437159,2437999,2438871,2439710,2440580,2441438,2442260,2443047,2443919,2444840,2445758,2446658,2447529,2448416,2449291,2450125,2450982,2451849,2452716,2453567,2454428,2455290,2456099,2456852,2457732,2458549,2459461,2460350,2461227,2462118,2462988,2463870,2464718,2465564,2466439,2467305,2468146,2468989,2469798,2470594,2471465,2472320,2473178,2474073,2475035,2475898,2476743,2477576,2478385,2479398,2480819,2482152,2483652,2485167,2486469,2487758,2489007,2490526,2492056,2493011,2494337,2495588,2496710,2498017,2499700,2500990,2502314,2503911,2505325,2506767,2508256,2509636,2510955,2512373,2513828,2515240,2516445,2517955,2519270,2520672,2521913,2523336,2525358,2527406,2529454,2531502,2533550,2535598,2537646,2539694,2541742,2543790,2545838,2547886,2549934,2551982,2554030,2556078,2558126,2560174,2562222,2564270,2566318,2568366,2570414,2572462,2574510,2576558,2578606,2580654,2582702,2584750,2586798,2588846,2590894,2592942,2594990,2597038,2599086,2601134,2603182,2605230,2607278,2609326,2611374,2613422,2615470,2617518,2619566,2621614,2623662,2625710,2627758,2629806,2631854,2633902,2635950,2637998,2640046,2642094,2643978,2645331,2646762,2648164,2649674,2651173,2652635,2654658,2656706,2658754,2660802,2662850,2664898,2666946,2668994,2671042,2673090,2675138,2677186,2679234,2681282,2683330,2685378,2687426,2689474,2691522,2693570,2695618,2697666,2699714,2701762,2703398,2704527,2705671,2706718],sizes:[900,1127,1158,851,1291,1352,1007,1071,1002,1357,1367,1361,1233,1286,1268,1162,1255,1384,1304,1169,1410,1400,1258,1052,1359,1290,1418,1331,1398,1342,1263,1361,1311,1127,1386,1233,1407,971,1221,805,664,660,1055,1346,1172,1240,1356,1305,1274,1326,1377,1285,1238,1324,1313,1319,1122,1274,1173,1379,1297,1543,1444,1289,1482,1382,1325,931,856,1174,1067,1463,1322,1219,967,881,1446,1385,1072,1397,1231,1358,1368,1564,1400,1177,1260,1368,1250,1388,1338,1313,1319,1368,1161,980,1070,959,1394,1348,1461,1238,1297,1331,1308,1085,1425,1362,1435,1443,1342,1057,1196,1310,1173,1236,1371,1353,1305,1180,1235,1404,1145,1445,1351,1411,1355,779,1056,1161,864,1274,1369,1328,1187,1172,1268,1152,1283,1448,1305,1030,1332,1232,1025,1296,1131,1118,1423,1347,1198,1264,1419,1469,1446,1348,1158,1217,1418,1383,1177,1372,1074,1388,1336,1359,1370,1372,1344,1415,1371,1338,1324,1420,1255,1483,1348,1207,1145,1345,1293,1069,1206,1326,1353,1167,1252,1098,1094,1083,999,1079,1104,1179,1121,906,855,964,1356,1345,1379,1488,1092,1357,1186,1131,1153,1283,1188,1454,844,1102,1109,963,1119,902,1085,861,948,1028,930,1370,1111,1210,1054,832,1052,1216,1194,1125,1068,966,1407,1544,1365,984,1198,1337,973,1257,1158,977,1326,971,1410,895,1134,975,1098,941,842,787,942,1026,1174,1215,1348,1270,1300,1254,1465,1413,1454,1201,1366,1107,1115,927,1210,1203,1289,1211,1204,1038,1006,1368,955,1228,1430,1274,1499,1195,1363,1293,1414,1381,918,994,1156,1196,1477,1432,1267,1273,1386,1399,1178,1076,1068,1126,1014,1211,1333,1241,1303,1275,1374,1398,1081,1066,1292,1299,1034,1150,1323,1272,1351,1110,1170,1196,1257,1311,1355,1221,1342,1343,1240,1365,1190,1312,1410,1510,1234,1074,1206,903,1308,1370,1425,1227,1359,1159,1196,1307,1178,1254,1158,1388,1250,1424,1297,1198,1337,1351,1428,1055,1215,1189,1221,1169,1294,1323,1232,1196,1318,1274,1376,1237,1330,1234,1191,1173,1273,1313,1291,1338,1395,1382,1377,1453,1343,1353,1340,1468,1381,1063,1376,1221,1270,1129,1352,1348,1425,1414,1328,1411,1328,1246,1238,1370,1333,1248,1309,1121,1363,1195,1440,1300,1143,1355,1105,1159,1059,1345,1403,1263,1402,1221,811,1183,1360,1323,1339,923,1333,1385,1243,1447,1151,1412,1542,1334,1479,1475,1299,1450,1369,1519,1417,1522,967,1184,1314,1275,1487,1427,1496,1369,896,1288,1361,1495,884,1098,1288,1504,1143,860,805,1085,1496,1230,799,1308,1405,1365,1509,1382,1480,1421,1172,1384,1213,1429,1352,1250,1340,1371,1542,1447,1398,1331,1348,1429,1458,1478,1261,1432,1223,1230,1347,915,1281,1093,1340,1323,1298,1339,1354,1335,1395,1377,1442,1316,1237,1047,1307,1398,1319,1069,1074,1285,1018,1064,987,1254,1370,1515,1210,1173,1066,1069,1363,1320,1276,1332,1204,1128,968,1220,1285,1032,1094,1195,1212,1276,1054,1033,1273,1247,1253,1239,1351,1201,1360,1291,1270,1233,1224,1308,1310,1048,1284,1188,1353,1309,1258,1279,1345,1174,1313,1361,999,1219,1290,1271,1304,1304,1270,1246,1380,1143,1321,1078,1114,1362,1267,1165,1312,1395,1311,1454,1407,1431,1492,1255,1372,1450,1277,1187,1273,1234,1371,1339,1192,1332,1244,1239,950,1133,1372,1381,1412,1390,1383,1292,1438,1430,1073,973,1262,1223,1283,1283,1212,1307,1394,956,933,784,929,1379,1196,1398,1228,1233,1214,1314,1309,1080,1121,878,1268,1339,1332,1204,962,1042,1394,1186,1031,1207,1261,1191,1070,1244,1259,1254,1187,1161,1137,1248,1196,1308,1270,1330,1296,1308,1259,1293,1295,1165,1294,1273,1307,1275,1253,1217,1237,1140,1360,1367,1146,1150,956,1072,948,1114,1120,1219,1284,1145,790,1113,1071,1186,1276,1146,1063,1078,1287,1284,1158,1282,1278,1204,1328,1208,1257,1424,1285,1193,1401,1152,1301,1171,1329,1371,1345,1281,1292,1356,1381,1345,1355,1313,1282,1242,1297,1273,1359,1177,1158,1035,1305,1250,1189,1289,1096,1189,1069,1129,1121,1337,1301,1209,1219,677,732,1097,1073,1201,950,1118,1055,1036,1189,1107,1216,1192,958,1099,1129,743,1102,1222,1234,1363,1345,1266,1296,1192,892,1213,691,1170,1093,1329,690,685,534,832,962,1228,708,1171,1155,1064,859,1095,1207,1352,1287,1239,793,1028,1397,1225,1367,1313,1241,1241,1150,860,1115,1368,1318,1311,1375,1323,1246,1230,1114,851,1079,1133,730,1294,1163,1258,1235,1307,1189,1202,1213,1295,1193,1115,1287,1330,1292,1353,1355,1299,1399,1334,1414,1347,1359,1275,1209,1354,1332,1363,1302,1376,1206,1365,1294,1197,1017,1199,1239,1053,1327,1405,1105,1390,1354,1447,1242,1339,1339,1407,871,1421,1326,1453,1359,1470,1246,1370,1277,1516,1375,1534,1261,1101,1100,1229,1251,1056,1208,1279,837,614,1156,978,1e3,1251,1357,1111,1278,1300,1290,1314,1431,1409,1275,1321,1390,1310,1123,1440,1134,1262,1277,1364,1361,1497,1171,1302,1070,1188,1404,1315,1250,1176,1409,1380,1460,1451,1419,1352,1447,1464,1337,1327,1333,1293,1310,1390,1387,1319,1404,1269,1304,1305,1464,1351,1490,1284,1409,1313,1244,1146,1098,779,1075,1063,891,1259,1252,1342,1398,1397,1333,1364,1352,1355,1231,1141,1078,880,1299,1229,1267,1267,1258,1403,1305,1271,1154,923,1123,874,1149,970,989,1124,1049,1117,1377,1458,1338,863,1351,1138,995,1180,1066,1031,1167,1243,967,1024,1238,1207,1034,948,1010,1328,1048,1025,1190,1150,846,1383,1360,1193,1201,1216,1134,1216,992,979,1185,1276,1004,853,1263,1380,1447,1360,920,1175,1164,1097,1071,1200,1126,1250,1034,900,1266,1231,1102,1054,1251,925,1115,1243,1218,1175,1043,1297,1204,1195,1263,1096,1119,1074,1181,1273,1204,1123,1326,1371,1375,1304,839,1286,1254,1115,1286,1080,1267,1112,1078,1011,1184,1309,1230,1373,1368,1406,923,1078,1246,1314,1332,1037,1220,1082,1115,1253,1239,1137,1194,1277,1202,1126,1228,1282,859,645,1449,1358,1137,1200,1085,1181,1194,788,742,723,892,1168,1049,891,730,1087,1288,1224,930,967,962,1260,1310,1314,1256,1423,1223,1324,1255,1261,1244,1284,1188,1319,1253,1254,1166,1404,1359,1299,1416,1163,1440,1325,1127,1241,1240,1363,1281,1023,1316,1239,1292,1263,1309,1449,1302,1404,1354,1503,1452,1250,1248,1228,1399,1094,1067,1380,1465,1180,1246,1210,1155,1321,1472,1365,1350,1287,1392,1315,1435,1389,1450,1429,1333,1491,1391,1353,1457,1372,1474,1442,1402,1396,1382,1329,1327,1261,1294,1058,1123,1065,1176,1284,1438,1064,1449,1194,1265,1321,1382,1088,920,1326,1262,1289,1430,1027,1025,1142,1287,1317,1434,1337,1353,1309,1431,1448,1236,1273,1360,1251,1153,1278,1060,1266,1302,1255,1042,1379,1374,1319,1216,1375,1250,1455,1378,1353,1453,1213,1301,1307,1220,1338,1156,993,1430,1263,1378,1253,1073,1460,1358,1150,1360,843,1021,949,988,841,1163,744,772,548,1026,532,560,613,574,544,514,1337,1432,1454,1461,1314,1349,1316,1330,1340,1354,1396,1416,1230,1374,2048,2048,2048,2048,1558,1148,1406,1416,1458,1325,1305,1398,1306,1382,1359,1487,1305,1394,1349,1381,1409,1255,1152,1158,882,1456,1437,1276,1498,1213,1139,1159,1431,1367,1268,1246,1232,1013,1347,1347,1310,1271,1290,1226,1296,1e3,1044,1223,1260,1313,1188,685,1244,1204,1216,1158,1430,1279,1263,1245,1313,1321,1347,1308,1063,1252,1261,1259,1286,1173,1379,1437,1353,1322,1332,1231,1412,1378,1300,1323,1403,1359,925,1043,915,1170,1270,1236,1244,1308,1213,1236,1149,1282,1279,1413,1443,1273,1116,1032,1128,867,641,1083,848,852,812,966,1054,1024,963,834,1068,1145,1208,1638,1252,1478,1456,1286,918,1086,1134,1212,772,1407,1091,1040,1208,1574,908,1511,1392,1377,1330,1312,1334,1372,1356,1219,1255,1336,1208,1059,1177,1110,804,1189,1114,768,1238,1094,1135,1209,973,1168,1383,940,998,1267,1003,1118,1341,1353,1278,1364,1155,1276,931,1421,1406,1126,1291,897,1377,1365,1360,1373,1193,1365,1119,1142,1015,1314,1168,1226,1289,1152,1232,1310,1377,1343,1270,1277,1232,1199,1189,941,1143,1084,1260,1391,1065,1076,1163,1425,1240,1225,1398,1411,1372,1369,1187,1340,1270,1216,1302,1049,1212,1094,1298,905,1085,1009,1126,956,1116,1344,1158,1089,1263,1119,940,1069,1259,1404,1141,1072,1084,1298,1310,1330,1238,1542,1270,1278,1266,1195,607,710,851,867,704,545,486,524,533,554,538,590,570,594,629,771,1569,1139,1e3,1128,1109,1238,1237,1182,903,1207,1180,1072,1092,1054,1219,1171,1045,1119,1211,1208,1231,1071,1189,1102,1229,1141,1114,1128,886,875,826,845,793,822,864,831,836,813,871,879,839,826,830,811,945,902,856,881,868,844,835,835,862,824,811,794,948,1013,947,979,950,961,943,969,947,943,978,952,906,958,936,950,933,947,932,931,947,933,862,913,932,872,899,867,862,901,888,887,898,885,853,864,869,852,864,820,795,742,754,977,1004,978,794,918,956,943,966,975,969,951,977,956,971,950,960,960,951,940,926,947,931,939,933,954,927,920,934,891,941,898,911,935,934,915,895,886,868,892,864,902,896,871,865,844,832,825,793,777,766,944,955,916,955,904,922,908,888,836,896,850,849,803,845,830,861,850,840,868,854,864,846,837,828,910,821,837,777,874,854,862,825,848,809,901,817,811,829,914,853,861,791,830,841,879,818,918,846,864,826,806,833,847,891,868,850,838,936,856,874,829,834,886,868,879,867,867,850,859,827,888,919,807,868,829,835,856,875,827,935,908,853,821,906,829,840,858,799,851,832,811,881,859,842,766,929,901,925,862,867,890,884,858,859,863,856,839,858,796,786,750,980,937,967,943,949,919,950,922,937,935,932,908,898,914,886,895,900,882,871,877,843,845,858,876,853,840,847,847,809,785,775,994,983,982,1006,1015,993,1006,954,949,1004,999,938,964,969,950,938,977,948,979,962,946,946,941,982,948,955,934,937,956,953,942,957,953,931,891,908,866,914,914,895,876,887,847,930,885,875,852,851,811,750,747,856,917,897,829,917,907,904,878,905,862,862,893,845,853,823,877,847,849,862,852,811,763,833,839,840,831,815,754,861,846,851,834,985,943,1002,1019,964,973,945,950,955,970,908,964,969,953,942,895,922,943,951,929,946,933,924,938,909,948,944,882,936,895,876,928,911,877,892,874,865,959,863,850,878,839,813,809,773,735,736,900,832,853,875,820,829,865,811,878,848,847,844,853,833,868,830,951,886,885,863,904,886,880,881,883,870,874,875,848,838,842,831,822,856,824,891,887,832,844,817,847,828,868,849,894,844,854,801,979,932,962,937,928,903,882,895,931,927,909,927,922,921,888,902,898,892,876,870,856,857,892,873,909,841,811,788,733,763,749,898,845,830,890,970,979,928,968,951,909,963,950,953,950,945,963,972,957,946,901,939,873,853,944,946,942,946,953,935,907,911,937,919,906,936,914,914,935,926,925,911,924,935,926,932,922,904,830,919,856,854,859,889,918,885,871,849,872,837,805,796,754,763,884,925,887,904,936,882,936,911,929,906,913,898,897,877,854,864,888,835,889,833,852,819,788,748,925,934,926,905,907,894,912,886,897,882,884,880,869,855,846,836,841,807,839,792,781,888,881,840,872,839,870,858,822,787,872,921,918,900,871,887,875,834,857,867,867,851,861,862,809,753,880,817,912,889,877,891,870,882,848,846,875,866,841,843,809,796,871,855,858,895,962,863,845,833,809,1013,1421,1333,1500,1515,1302,1289,1249,1519,1530,955,1326,1251,1122,1307,1683,1290,1324,1597,1414,1442,1489,1380,1319,1418,1455,1412,1205,1510,1315,1402,1241,1423,2022,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,1884,1353,1431,1402,1510,1499,1462,2023,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048,1636,1129,1144,1047,456],successes:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,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,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,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1]};compressedData["data"]=byteArray;assert(typeof Module.LZ4==="object","LZ4 not present - was your app build with -s LZ4=1 ?");Module.LZ4.loadPackage({metadata:metadata,compressedData:compressedData},true);Module["removeRunDependency"]("datafile_networkx.data")}Module["addRunDependency"]("datafile_networkx.data");if(!Module.preloadResults)Module.preloadResults={};Module.preloadResults[PACKAGE_NAME]={fromCache:false};if(fetched){processPackageData(fetched);fetched=null}else{fetchedCallback=processPackageData}}if(Module["calledRun"]){runWithFS()}else{if(!Module["preRun"])Module["preRun"]=[];Module["preRun"].push(runWithFS)}};loadPackage({files:[{filename:"/lib/python3.9/site-packages/networkx/__init__.py",start:0,end:2906,audio:0},{filename:"/lib/python3.9/site-packages/networkx/convert.py",start:2906,end:18750,audio:0},{filename:"/lib/python3.9/site-packages/networkx/convert_matrix.py",start:18750,end:67054,audio:0},{filename:"/lib/python3.9/site-packages/networkx/exception.py",start:67054,end:70591,audio:0},{filename:"/lib/python3.9/site-packages/networkx/relabel.py",start:70591,end:80597,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/__init__.py",start:80597,end:86846,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/asteroidal.py",start:86846,end:92657,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/boundary.py",start:92657,end:97352,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bridges.py",start:97352,end:102628,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/chains.py",start:102628,end:109236,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/chordal.py",start:109236,end:123613,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/clique.py",start:123613,end:147726,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/cluster.py",start:147726,end:166536,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/communicability_alg.py",start:166536,end:171087,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/core.py",start:171087,end:186670,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/covering.py",start:186670,end:190777,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/cuts.py",start:190777,end:200499,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/cycles.py",start:200499,end:222191,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/d_separation.py",start:222191,end:226446,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/dag.py",start:226446,end:256317,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/distance_measures.py",start:256317,end:275299,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/distance_regular.py",start:275299,end:282168,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/dominance.py",start:282168,end:285561,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/dominating.py",start:285561,end:288208,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/efficiency_measures.py",start:288208,end:292484,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/euler.py",start:292484,end:305200,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/graph_hashing.py",start:305200,end:310328,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/graphical.py",start:310328,end:323776,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/hierarchy.py",start:323776,end:325287,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/hybrid.py",start:325287,end:331438,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isolate.py",start:331438,end:333699,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/link_prediction.py",start:333699,end:352932,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/lowest_common_ancestors.py",start:352932,end:366968,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/matching.py",start:366968,end:406022,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/mis.py",start:406022,end:408373,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/moral.py",start:408373,end:409632,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/non_randomness.py",start:409632,end:412016,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/planar_drawing.py",start:412016,end:428336,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/planarity.py",start:428336,end:466368,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/reciprocity.py",start:466368,end:469193,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/regular.py",start:469193,end:475442,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/richclub.py",start:475442,end:479593,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/similarity.py",start:479593,end:539883,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/simple_paths.py",start:539883,end:569282,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/smallworld.py",start:569282,end:581848,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/smetric.py",start:581848,end:583027,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/sparsifiers.py",start:583027,end:593064,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/structuralholes.py",start:593064,end:602209,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/summarization.py",start:602209,end:625165,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/swap.py",start:625165,end:634994,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/threshold.py",start:634994,end:666046,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tournament.py",start:666046,end:676548,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/triads.py",start:676548,end:687987,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/vitality.py",start:687987,end:690283,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/voronoi.py",start:690283,end:693441,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/wiener.py",start:693441,end:695734,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/assortativity/__init__.py",start:695734,end:696028,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/assortativity/connectivity.py",start:696028,end:700542,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/assortativity/correlation.py",start:700542,end:708706,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/assortativity/mixing.py",start:708706,end:717800,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/assortativity/neighbor_degree.py",start:717800,end:721458,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/assortativity/pairs.py",start:721458,end:724750,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/__init__.py",start:724750,end:728518,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/basic.py",start:728518,end:736239,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/centrality.py",start:736239,end:744707,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/cluster.py",start:744707,end:751575,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/covering.py",start:751575,end:753666,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/edgelist.py",start:753666,end:764833,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/generators.py",start:764833,end:784420,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/matching.py",start:784420,end:805693,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/matrix.py",start:805693,end:811803,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/projection.py",start:811803,end:828289,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/redundancy.py",start:828289,end:831768,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/bipartite/spectral.py",start:831768,end:833658,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/node_classification/__init__.py",start:833658,end:834394,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/node_classification/hmn.py",start:834394,end:838239,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/node_classification/lgc.py",start:838239,end:842350,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/node_classification/utils.py",start:842350,end:844930,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/__init__.py",start:844930,end:845463,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/betweenness.py",start:845463,end:858582,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/betweenness_subset.py",start:858582,end:868093,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/closeness.py",start:868093,end:877984,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/current_flow_betweenness.py",start:877984,end:889861,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/current_flow_betweenness_subset.py",start:889861,end:897836,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/current_flow_closeness.py",start:897836,end:901196,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/degree_alg.py",start:901196,end:904435,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/dispersion.py",start:904435,end:907837,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/eigenvector.py",start:907837,end:916022,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/flow_matrix.py",start:916022,end:920446,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/group.py",start:920446,end:948219,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/harmonic.py",start:948219,end:950808,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/katz.py",start:950808,end:961503,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/load.py",start:961503,end:968349,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/percolation.py",start:968349,end:972444,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/reaching.py",start:972444,end:979392,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/second_order.py",start:979392,end:984160,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/subgraph_alg.py",start:984160,end:993673,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/trophic.py",start:993673,end:998222,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/centrality/voterank_alg.py",start:998222,end:1000908,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/__init__.py",start:1000908,end:1002101,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/asyn_fluid.py",start:1002101,end:1007981,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/centrality.py",start:1007981,end:1014478,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/community_utils.py",start:1014478,end:1015345,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/kclique.py",start:1015345,end:1017831,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/kernighan_lin.py",start:1017831,end:1022090,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/label_propagation.py",start:1022090,end:1028873,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/lukes.py",start:1028873,end:1036996,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/modularity_max.py",start:1036996,end:1050229,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/community/quality.py",start:1050229,end:1064843,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/__init__.py",start:1064843,end:1065016,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/attracting.py",start:1065016,end:1067673,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/biconnected.py",start:1067673,end:1080138,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/connected.py",start:1080138,end:1083973,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/semiconnected.py",start:1083973,end:1085561,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/strongly_connected.py",start:1085561,end:1096314,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/components/weakly_connected.py",start:1096314,end:1100018,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/__init__.py",start:1100018,end:1100598,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/connectivity.py",start:1100598,end:1130451,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/cuts.py",start:1130451,end:1153126,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/disjoint_paths.py",start:1153126,end:1167624,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/edge_augmentation.py",start:1167624,end:1211342,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py",start:1211342,end:1232054,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/kcomponents.py",start:1232054,end:1240276,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/kcutsets.py",start:1240276,end:1249605,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/stoerwagner.py",start:1249605,end:1254984,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/connectivity/utils.py",start:1254984,end:1258128,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/coloring/__init__.py",start:1258128,end:1258310,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/coloring/equitable_coloring.py",start:1258310,end:1274823,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/coloring/greedy_coloring.py",start:1274823,end:1287641,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/coloring/greedy_coloring_with_interchange.py",start:1287641,end:1294296,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/__init__.py",start:1294296,end:1294637,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/boykovkolmogorov.py",start:1294637,end:1307875,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/capacityscaling.py",start:1307875,end:1322286,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/dinitz_alg.py",start:1322286,end:1329394,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/edmondskarp.py",start:1329394,end:1337350,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/gomory_hu.py",start:1337350,end:1343617,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/maxflow.py",start:1343617,end:1366332,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/mincost.py",start:1366332,end:1378300,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/networksimplex.py",start:1378300,end:1403472,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/preflowpush.py",start:1403472,end:1419138,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/shortestaugmentingpath.py",start:1419138,end:1429410,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/flow/utils.py",start:1429410,end:1435152,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/minors/__init__.py",start:1435152,end:1435739,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/minors/contraction.py",start:1435739,end:1457356,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/traversal/__init__.py",start:1457356,end:1457498,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/traversal/beamsearch.py",start:1457498,end:1460886,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/traversal/breadth_first_search.py",start:1460886,end:1473457,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/traversal/depth_first_search.py",start:1473457,end:1486298,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/traversal/edgebfs.py",start:1486298,end:1492530,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/traversal/edgedfs.py",start:1492530,end:1498468,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/__init__.py",start:1498468,end:1498822,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/ismags.py",start:1498822,end:1541579,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/isomorph.py",start:1541579,end:1547961,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/isomorphvf2.py",start:1547961,end:1588517,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/matchhelpers.py",start:1588517,end:1599817,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/temporalisomorphvf2.py",start:1599817,end:1610765,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/tree_isomorphism.py",start:1610765,end:1620031,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/isomorphism/vf2userfunc.py",start:1620031,end:1627527,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/shortest_paths/__init__.py",start:1627527,end:1627812,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/shortest_paths/astar.py",start:1627812,end:1634170,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/shortest_paths/dense.py",start:1634170,end:1641461,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/shortest_paths/generic.py",start:1641461,end:1660259,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/shortest_paths/unweighted.py",start:1660259,end:1674479,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/shortest_paths/weighted.py",start:1674479,end:1745181,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/link_analysis/__init__.py",start:1745181,end:1745299,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/link_analysis/hits_alg.py",start:1745299,end:1757352,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/link_analysis/pagerank_alg.py",start:1757352,end:1774762,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/operators/__init__.py",start:1774762,end:1774963,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/operators/all.py",start:1774963,end:1779132,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/operators/binary.py",start:1779132,end:1790295,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/operators/product.py",start:1790295,end:1804152,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/operators/unary.py",start:1804152,end:1805320,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/__init__.py",start:1805320,end:1806517,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/clique.py",start:1806517,end:1813698,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/clustering_coefficient.py",start:1813698,end:1815740,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/connectivity.py",start:1815740,end:1828467,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/distance_measures.py",start:1828467,end:1834017,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/dominating_set.py",start:1834017,end:1838160,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/kcomponents.py",start:1838160,end:1851313,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/matching.py",start:1851313,end:1852468,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/maxcut.py",start:1852468,end:1856062,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/ramsey.py",start:1856062,end:1857400,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/steinertree.py",start:1857400,end:1860776,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/traveling_salesman.py",start:1860776,end:1891893,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/treewidth.py",start:1891893,end:1899912,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/approximation/vertex_cover.py",start:1899912,end:1902550,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/__init__.py",start:1902550,end:1902699,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/branchings.py",start:1902699,end:1927646,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/coding.py",start:1927646,end:1940633,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/decomposition.py",start:1940633,end:1943666,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/mst.py",start:1943666,end:1964454,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/operations.py",start:1964454,end:1967974,audio:0},{filename:"/lib/python3.9/site-packages/networkx/algorithms/tree/recognition.py",start:1967974,end:1974418,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/__init__.py",start:1974418,end:1974753,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/coreviews.py",start:1974753,end:1990224,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/digraph.py",start:1990224,end:2032888,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/filters.py",start:2032888,end:2034603,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/function.py",start:2034603,end:2069733,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/graph.py",start:2069733,end:2135503,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/graphviews.py",start:2135503,end:2142011,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/multidigraph.py",start:2142011,end:2176181,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/multigraph.py",start:2176181,end:2218853,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/ordered.py",start:2218853,end:2224344,audio:0},{filename:"/lib/python3.9/site-packages/networkx/classes/reportviews.py",start:2224344,end:2265278,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/__init__.py",start:2265278,end:2266550,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/atlas.py",start:2266550,end:2272098,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/classic.py",start:2272098,end:2295687,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/cographs.py",start:2295687,end:2297531,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/community.py",start:2297531,end:2331967,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/degree_seq.py",start:2331967,end:2361834,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/directed.py",start:2361834,end:2377318,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/duplication.py",start:2377318,end:2382277,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/ego.py",start:2382277,end:2384113,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/expanders.py",start:2384113,end:2390307,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/geometric.py",start:2390307,end:2417703,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/harary_graph.py",start:2417703,end:2423775,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/internet_as_graphs.py",start:2423775,end:2437923,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/intersection.py",start:2437923,end:2441870,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/interval_graph.py",start:2441870,end:2444055,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/joint_degree_seq.py",start:2444055,end:2468847,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/lattice.py",start:2468847,end:2482147,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/line.py",start:2482147,end:2499943,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/mycielski.py",start:2499943,end:2503196,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/nonisomorphic_trees.py",start:2503196,end:2508437,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/random_clustered.py",start:2508437,end:2512569,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/random_graphs.py",start:2512569,end:2557174,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/small.py",start:2557174,end:2572226,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/social.py",start:2572226,end:2594956,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/spectral_graph_forge.py",start:2594956,end:2600786,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/stochastic.py",start:2600786,end:2602654,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/sudoku.py",start:2602654,end:2606897,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/trees.py",start:2606897,end:2621043,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/triads.py",start:2621043,end:2623227,audio:0},{filename:"/lib/python3.9/site-packages/networkx/generators/atlas.dat.gz",start:2623227,end:2632114,audio:0},{filename:"/lib/python3.9/site-packages/networkx/drawing/__init__.py",start:2632114,end:2632250,audio:0},{filename:"/lib/python3.9/site-packages/networkx/drawing/layout.py",start:2632250,end:2667624,audio:0},{filename:"/lib/python3.9/site-packages/networkx/drawing/nx_agraph.py",start:2667624,end:2682265,audio:0},{filename:"/lib/python3.9/site-packages/networkx/drawing/nx_pydot.py",start:2682265,end:2691643,audio:0},{filename:"/lib/python3.9/site-packages/networkx/drawing/nx_pylab.py",start:2691643,end:2733978,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/__init__.py",start:2733978,end:2734546,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/algebraicconnectivity.py",start:2734546,end:2752947,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/attrmatrix.py",start:2752947,end:2768381,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/bethehessianmatrix.py",start:2768381,end:2770673,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/graphmatrix.py",start:2770673,end:2776253,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/laplacianmatrix.py",start:2776253,end:2787122,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/modularitymatrix.py",start:2787122,end:2791698,audio:0},{filename:"/lib/python3.9/site-packages/networkx/linalg/spectrum.py",start:2791698,end:2795574,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/__init__.py",start:2795574,end:2798090,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/adjlist.py",start:2798090,end:2805849,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/edgelist.py",start:2805849,end:2819680,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/gexf.py",start:2819680,end:2859091,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/gml.py",start:2859091,end:2888992,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/gpickle.py",start:2888992,end:2891792,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/graph6.py",start:2891792,end:2903003,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/graphml.py",start:2903003,end:2941501,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/leda.py",start:2941501,end:2944209,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/multiline_adjlist.py",start:2944209,end:2955390,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/nx_shp.py",start:2955390,end:2967192,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/nx_yaml.py",start:2967192,end:2969392,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/p2g.py",start:2969392,end:2972387,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/pajek.py",start:2972387,end:2981019,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/sparse6.py",start:2981019,end:2991208,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/text.py",start:2991208,end:2997706,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/json_graph/__init__.py",start:2997706,end:2998430,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/json_graph/adjacency.py",start:2998430,end:3003174,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/json_graph/cytoscape.py",start:3003174,end:3011316,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/json_graph/jit.py",start:3011316,end:3014397,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/json_graph/node_link.py",start:3014397,end:3020106,audio:0},{filename:"/lib/python3.9/site-packages/networkx/readwrite/json_graph/tree.py",start:3020106,end:3026763,audio:0},{filename:"/lib/python3.9/site-packages/networkx/testing/__init__.py",start:3026763,end:3026838,audio:0},{filename:"/lib/python3.9/site-packages/networkx/testing/test.py",start:3026838,end:3027772,audio:0},{filename:"/lib/python3.9/site-packages/networkx/testing/utils.py",start:3027772,end:3029262,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/__init__.py",start:3029262,end:3029534,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/contextmanagers.py",start:3029534,end:3030635,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/decorators.py",start:3030635,end:3075446,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/heaps.py",start:3075446,end:3086274,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/mapped_queue.py",start:3086274,end:3095412,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/misc.py",start:3095412,end:3113727,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/random_sequence.py",start:3113727,end:3117977,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/rcm.py",start:3117977,end:3122605,audio:0},{filename:"/lib/python3.9/site-packages/networkx/utils/union_find.py",start:3122605,end:3125928,audio:0},{filename:"/lib/python3.9/site-packages/networkx-2.6.3-py3.9.egg-info/PKG-INFO",start:3125928,end:3129936,audio:0},{filename:"/lib/python3.9/site-packages/networkx-2.6.3-py3.9.egg-info/SOURCES.txt",start:3129936,end:3163964,audio:0},{filename:"/lib/python3.9/site-packages/networkx-2.6.3-py3.9.egg-info/dependency_links.txt",start:3163964,end:3163965,audio:0},{filename:"/lib/python3.9/site-packages/networkx-2.6.3-py3.9.egg-info/not-zip-safe",start:3163965,end:3163966,audio:0},{filename:"/lib/python3.9/site-packages/networkx-2.6.3-py3.9.egg-info/requires.txt",start:3163966,end:3164296,audio:0},{filename:"/lib/python3.9/site-packages/networkx-2.6.3-py3.9.egg-info/top_level.txt",start:3164296,end:3164305,audio:0},{filename:"/share/doc/networkx-2.6.3/LICENSE.txt",start:3164305,end:3166068,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/README.txt",start:3166068,end:3166253,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/README.txt",start:3166253,end:3166275,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/WormNet.v3.benchmark.txt",start:3166275,end:4513021,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_beam_search.py",start:4513021,end:4517140,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_betweenness_centrality.py",start:4517140,end:4519262,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_blockmodel.py",start:4519262,end:4521941,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_circuits.py",start:4521941,end:4525437,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_davis_club.py",start:4525437,end:4526638,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_dedensification.py",start:4526638,end:4528888,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_iterated_dynamical_systems.py",start:4528888,end:4534886,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_krackhardt_centrality.py",start:4534886,end:4535523,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_parallel_betweenness.py",start:4535523,end:4537980,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_rcm.py",start:4537980,end:4539025,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/plot_snap.py",start:4539025,end:4542113,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/algorithms/hartford_drug.edgelist",start:4542113,end:4544448,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/basic/README.txt",start:4544448,end:4544460,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/basic/plot_properties.py",start:4544460,end:4545525,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/basic/plot_read_write.py",start:4545525,end:4546050,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/basic/plot_simple_graph.py",start:4546050,end:4547290,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/3d_drawing/README.txt",start:4547290,end:4547312,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/3d_drawing/mayavi2_spring.py",start:4547312,end:4548246,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/3d_drawing/plot_basic.py",start:4548246,end:4549395,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/README.txt",start:4549395,end:4549411,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_chess_masters.py",start:4549411,end:4553994,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_custom_node_icons.py",start:4553994,end:4556133,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_degree.py",start:4556133,end:4557689,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_directed.py",start:4557689,end:4558797,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_edge_colormap.py",start:4558797,end:4559238,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_ego_graph.py",start:4559238,end:4560148,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_eigenvalues.py",start:4560148,end:4560692,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_four_grids.py",start:4560692,end:4561746,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_house_with_colors.py",start:4561746,end:4562411,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_knuth_miles.py",start:4562411,end:4566524,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_labels_and_colors.py",start:4566524,end:4567767,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_multipartite_graph.py",start:4567767,end:4568762,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_node_colormap.py",start:4568762,end:4569050,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_rainbow_coloring.py",start:4569050,end:4571222,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_random_geometric_graph.py",start:4571222,end:4572160,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_sampson.py",start:4572160,end:4573388,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_selfloops.py",start:4573388,end:4574141,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_simple_path.py",start:4574141,end:4574393,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_spectral_grid.py",start:4574393,end:4575985,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_unix_email.py",start:4575985,end:4577953,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/plot_weighted_graph.py",start:4577953,end:4578951,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/chess_masters_WCC.pgn.bz2",start:4578951,end:4679175,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/knuth_miles.txt.gz",start:4679175,end:4699492,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/drawing/unix_email.mbox",start:4699492,end:4701201,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/README.txt",start:4701201,end:4701213,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_degree_sequence.py",start:4701213,end:4702012,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_erdos_renyi.py",start:4702012,end:4702853,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_expected_degree_sequence.py",start:4702853,end:4703349,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_football.py",start:4703349,end:4704539,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_karate_club.py",start:4704539,end:4705033,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_napoleon_russian_campaign.py",start:4705033,end:4707940,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_roget.py",start:4707940,end:4710066,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/plot_words.py",start:4710066,end:4712764,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/roget_dat.txt.gz",start:4712764,end:4728522,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/graph/words_dat.txt.gz",start:4728522,end:4762217,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/subclass/README.txt",start:4762217,end:4762235,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/subclass/plot_antigraph.py",start:4762235,end:4768254,audio:0},{filename:"/share/doc/networkx-2.6.3/examples/subclass/plot_printgraph.py",start:4768254,end:4770546,audio:0}],remote_package_size:2711270,package_uuid:"9360febd-2fba-4cea-b4e6-1b967d3aa21d"})})(); \ No newline at end of file diff --git a/spaces/qiantong-xu/toolbench-leaderboard/README.md b/spaces/qiantong-xu/toolbench-leaderboard/README.md deleted file mode 100644 index d074829777818763d786fbe25eb74a24f99aa054..0000000000000000000000000000000000000000 --- a/spaces/qiantong-xu/toolbench-leaderboard/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Toolbench Leaderboard -emoji: ⚡ -colorFrom: red -colorTo: green -sdk: gradio -sdk_version: 3.32.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/quidiaMuxgu/Expedit-SAM/A Cunning Chess Opening Repertoire For White Pdf [Extra Quality] Download.md b/spaces/quidiaMuxgu/Expedit-SAM/A Cunning Chess Opening Repertoire For White Pdf [Extra Quality] Download.md deleted file mode 100644 index 564cdc132e324bcc2a6f54c97cfa9ceb81d0d1d2..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/A Cunning Chess Opening Repertoire For White Pdf [Extra Quality] Download.md +++ /dev/null @@ -1,17 +0,0 @@ - -

    A Cunning Chess Opening Repertoire For White Pdf Download: How to Outsmart Your Opponents with 1 d4 and Nf3

    -

    If you are looking for a chess opening repertoire that is flexible, effective and easy to learn, you might want to check out the book A Cunning Chess Opening Repertoire for White by Graham Burgess. This book presents a repertoire based on 1 d4 and Nf3, with the aim of steering the game to positions that suit White and deny the opponent his preferred strategies.

    -

    A Cunning Chess Opening Repertoire For White Pdf Download


    Download File ->->->-> https://geags.com/2uCsmH



    -

    The main idea of this repertoire is to play 5 Bf4 in the Queen's Gambit Declined, the Torre Attack against ...e6, and various fianchetto options against the King's Indian and related set-ups. White's position is kept highly flexible, with many possible transpositions to a wide variety of systems that the reader can use to extend and vary the repertoire. The book features a wealth of new ideas and original analysis.

    -

    The author, FIDE Master Graham Burgess, is a highly experienced chess opening writer and one of the founders of Gambit Publications. He holds the world record for marathon blitz chess playing, and lives in Minnesota. This is his 23rd chess book.

    -

    If you want to download a pdf version of this book, you can find it at chess.co.uk, which is one of the web search results for the keyword "A Cunning Chess Opening Repertoire For White Pdf Download". Alternatively, you can also find it at gambitbooks.com, which is another web search result for the same keyword.

    -

    We hope you enjoy this book and improve your chess skills with this cunning chess opening repertoire for White!

    -

    - -

    Of course, 1.e4 is not the only option for White. Some players prefer to start with 1.d4, 1.c4 or 1.Nf3, which can lead to different types of positions and strategies. In this article, we will briefly compare these moves and their advantages and disadvantages.

    -

    After 1.d4, White aims to control the center with his pawns and pieces, and often plays c4 to support the d4-pawn. Black has several ways to challenge White's center, such as the Queen's Gambit Declined, the Slav Defense, the Nimzo-Indian Defense, the Grunfeld Defense and the King's Indian Defense. These openings are very solid and well-analyzed, and White has to work hard to create problems for Black. On the other hand, White can also choose quieter and more positional lines, such as the London System or the Colle System, which avoid a lot of theory and aim for a slight edge in the endgame.

    -

    After 1.c4, White plays the English Opening, which is very flexible and can transpose to many other openings. White can choose between different set-ups, such as playing e4 or d4 later, or fianchettoing one or both bishops. Black has a huge variety of options against 1.c4, ranging from symmetrical replies like 1...c5 or 1...e5, to asymmetrical ones like 1...b6 or 1...f5. The English Opening is mainly popular at higher levels, as it requires a lot of preparation and understanding of different pawn structures and plans.

    -

    After 1.Nf3, White plays a hypermodern move that does not commit to any specific pawn structure or opening. White can later play e4 or d4 or c4, depending on how Black reacts. Black can also choose from many different replies, such as 1...d5, 1...c5, 1...Nf6 or 1...g6. The advantage of 1.Nf3 is that it avoids some sharp lines that Black can play after 1.e4 or 1.d4, such as the Sicilian Defense or the Grunfeld Defense. The disadvantage is that it gives Black more freedom and does not put immediate pressure on the center.

    -

    As you can see, each of these moves has its pros and cons, and it is up to you to decide which one suits your style and preferences better. In any case, you should always study the main ideas and principles behind each opening system, rather than memorizing long variations. This will help you to play confidently and creatively in any position that arises on the board.

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Battle For Middle Earth 1 No Cd Crack [2021] 1.03.md b/spaces/quidiaMuxgu/Expedit-SAM/Battle For Middle Earth 1 No Cd Crack [2021] 1.03.md deleted file mode 100644 index 81ced7c7ca4ded301177a7d32762f16777caa319..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Battle For Middle Earth 1 No Cd Crack [2021] 1.03.md +++ /dev/null @@ -1,6 +0,0 @@ -

    battle for middle earth 1 no cd crack 1.03


    DOWNLOAD ✸✸✸ https://geags.com/2uCquq



    - -Download Archive LotR Battle for Middle-Earth ENGLISH No-CD/Fixed Image PC. Extract the LOTR BFME Patch from the Lord Of The. 1fdad05405
    -
    -
    -

    diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Biblioteca Con 65.534 Libros En Espa Ol (EPUB) (67 GB) Free Download _TOP_.md b/spaces/quidiaMuxgu/Expedit-SAM/Biblioteca Con 65.534 Libros En Espa Ol (EPUB) (67 GB) Free Download _TOP_.md deleted file mode 100644 index 676c56b12fdb05846e1dbf63d6d74d7ad41f09f0..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Biblioteca Con 65.534 Libros En Espa Ol (EPUB) (67 GB) Free Download _TOP_.md +++ /dev/null @@ -1,25 +0,0 @@ - -

    ¿Cómo descargar gratis una biblioteca con más de 65 mil libros en español?

    -

    Si eres un amante de la lectura y quieres tener acceso a una enorme colección de libros en español, te tenemos una buena noticia: puedes descargar gratis una biblioteca con 65.534 libros en formato EPUB que ocupa solo 67 GB de espacio.

    -

    Biblioteca con 65.534 libros en espa ol (EPUB) (67 GB) free download


    DOWNLOADhttps://geags.com/2uCr5S



    -

    Se trata de una compilación realizada por un usuario de Reddit, que ha recopilado miles de libros de diferentes géneros, autores y épocas, desde clásicos de la literatura hasta best-sellers actuales. Todos los libros están en español y en formato EPUB, que es compatible con la mayoría de los dispositivos de lectura electrónica.

    -

    Para descargar esta impresionante biblioteca, solo tienes que seguir estos pasos:

    -
      -
    1. Entra en este enlace de Reddit, donde encontrarás el enlace de descarga y la contraseña para acceder al archivo.
    2. -
    3. Descarga el archivo comprimido que contiene todos los libros. Puedes usar un gestor de descargas como JDownloader para acelerar el proceso.
    4. -
    5. Descomprime el archivo usando un programa como WinRAR o 7-Zip. Necesitarás introducir la contraseña que se indica en el post de Reddit.
    6. -
    7. Disfruta de tu biblioteca con más de 65 mil libros en español. Puedes transferirlos a tu dispositivo de lectura preferido o leerlos en tu ordenador usando un programa como Calibre.
    8. -
    -

    Así de fácil y rápido puedes descargar gratis una biblioteca con 65.534 libros en español (EPUB) (67 GB). No pierdas esta oportunidad de ampliar tu cultura y tu entretenimiento con esta increíble colección de libros.

    -

    - -

    ¿Qué libros puedes encontrar en esta biblioteca? La respuesta es: de todo. Desde obras maestras de la literatura universal como Don Quijote de la Mancha, Cien años de soledad o El principito, hasta novelas populares como Los juegos del hambre, Crepúsculo o Harry Potter.

    -

    También hay libros de ciencia ficción, fantasía, terror, romance, historia, filosofía, psicología, autoayuda, biografías y mucho más. Puedes buscar por género, autor o título, o simplemente explorar al azar y descubrir nuevas lecturas.

    -

    Esta biblioteca es una verdadera joya para los amantes de los libros en español, ya que ofrece una gran variedad y calidad de obras. Además, al estar en formato EPUB, puedes personalizar la fuente, el tamaño, el color y el margen de los textos, así como añadir marcadores, notas y resaltados.

    -

    No esperes más y descarga gratis esta biblioteca con 65.534 libros en español (EPUB) (67 GB). Te garantizamos que no te arrepentirás.

    - -

    ¿Cómo se ha creado esta biblioteca? Según el usuario de Reddit que la ha compartido, se trata de un proyecto personal que lleva años realizando. Ha ido recopilando libros de diferentes fuentes, como páginas web, foros, blogs y redes sociales. Ha revisado y corregido los archivos para asegurarse de que estén completos y sin errores. Ha organizado y clasificado los libros por género, autor y título. Y ha comprimido todo en un solo archivo para facilitar la descarga.

    -

    El resultado es una biblioteca impresionante, que contiene más libros de los que podrías leer en toda tu vida. Y lo mejor de todo es que la ha puesto a disposición de todos los interesados de forma gratuita y altruista. Solo pide que se respeten los derechos de autor de las obras y que se difunda el enlace para que más personas puedan disfrutar de esta maravilla.

    -

    Así que ya sabes, si quieres descargar gratis una biblioteca con 65.534 libros en español (EPUB) (67 GB), solo tienes que seguir los pasos que te hemos indicado. No dejes pasar esta oportunidad única de tener una colección de libros inigualable.

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (download Pyaar Ka Punchnama 2 Movie ).md b/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (download Pyaar Ka Punchnama 2 Movie ).md deleted file mode 100644 index 13fcaba17a700ca9f444aa9fdef5caced04bf377..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (download Pyaar Ka Punchnama 2 Movie ).md +++ /dev/null @@ -1,9 +0,0 @@ -

    HD Online Player (download Pyaar Ka Punchnama 2 movie )


    DOWNLOAD ○○○ https://geags.com/2uCsZG



    -
    -Pyaar Ka Punchnama 2 Full movie online with release date, trailer, cast and songs. Find out where to watch or stream this Hindi comedy on DIgit. Pyaar Ka Punchnama 2 is the sequel to Pyaar Ka Punchnama, a film directed by Aditya Chopra and produced by Aashish Shah starring Aditya Chopra and Amitabh Bachchan. The film was released on May 25, 2019 in theaters. -Brief description of the film -The film is about a family looking for their daughter who is in danger because of her love of adventure.Director Aditya Chopra is the writer and producer of the film. -Amitabh Bachchan is the executive producer of the film. 8a78ff9644
    -
    -
    -

    diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Halion Sonic Download HOT! Full.16.md b/spaces/quidiaMuxgu/Expedit-SAM/Halion Sonic Download HOT! Full.16.md deleted file mode 100644 index 89cf926985cf2c1e642f00a97c0fb887b400612f..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Halion Sonic Download HOT! Full.16.md +++ /dev/null @@ -1,18 +0,0 @@ -

    Halion Sonic Download Full.16


    Downloadhttps://geags.com/2uCrJw



    - -halion sonic .16 Halion Sonic. -Oct 16, 2012 ... -Halion Sonic. -Description, characteristics, cost. ... -You can play computer games with this toy. -Halion Sonic... -Halion Sonic Game (Sonic.exe) - PlayGround.com -Nov 27, 2011 ... -Halion Sonic game (Sonic.exe). -In this game, you will control a spaceship that ... -Halions - Wikipedia. -Halions is a space simulation video game developed by... -In 1984, HAL Laboratory, currently HALO Laboratory, ... 8a78ff9644
    -
    -
    -

    diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Ml2 Bootloader Installer.pkg.zip.md b/spaces/quidiaMuxgu/Expedit-SAM/Ml2 Bootloader Installer.pkg.zip.md deleted file mode 100644 index dcd44c2101151229657c8c82403e8da7fc9b504e..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Ml2 Bootloader Installer.pkg.zip.md +++ /dev/null @@ -1,6 +0,0 @@ -

    ml2 bootloader installer.pkg.zip


    Download Ziphttps://geags.com/2uCrTE



    -
    -January 2, 2013 - This guide describes how to install iAtkos ML2. . A USB hard drive can cause your Hackintosh bootloader to give you EBIOS errors on startup. Follow these steps to troubleshoot. 1. Connect a USB hard drive to the USB host port. 2. Make sure the USB hard drive is connected. If the USB hard drive is not connected, press the power button on the back of the computer to turn on the power. On some computer models, this button may have a lightning bolt symbol or an exclamation point. 3. On some computer models, in order for the computer to boot, you must first enable recovery mode (in the BIOS). 8a78ff9644
    -
    -
    -

    diff --git a/spaces/radames/MusicGen-Continuation/audiocraft/data/audio_dataset.py b/spaces/radames/MusicGen-Continuation/audiocraft/data/audio_dataset.py deleted file mode 100644 index cf21422ea0059cb2d6553f93e608b8f9fa0d3a50..0000000000000000000000000000000000000000 --- a/spaces/radames/MusicGen-Continuation/audiocraft/data/audio_dataset.py +++ /dev/null @@ -1,525 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import argparse -import copy -from concurrent.futures import ThreadPoolExecutor, Future -from dataclasses import dataclass, fields -from contextlib import ExitStack -import gzip -import json -import logging -import os -from pathlib import Path -import random -import sys -import typing as tp - -import torch -import torch.nn.functional as F - -from .audio import audio_read, audio_info -from .audio_utils import convert_audio -from .zip import PathInZip - -try: - import dora -except ImportError: - dora = None # type: ignore - - -@dataclass(order=True) -class BaseInfo: - - @classmethod - def _dict2fields(cls, dictionary: dict): - return { - field.name: dictionary[field.name] - for field in fields(cls) if field.name in dictionary - } - - @classmethod - def from_dict(cls, dictionary: dict): - _dictionary = cls._dict2fields(dictionary) - return cls(**_dictionary) - - def to_dict(self): - return { - field.name: self.__getattribute__(field.name) - for field in fields(self) - } - - -@dataclass(order=True) -class AudioMeta(BaseInfo): - path: str - duration: float - sample_rate: int - amplitude: tp.Optional[float] = None - weight: tp.Optional[float] = None - # info_path is used to load additional information about the audio file that is stored in zip files. - info_path: tp.Optional[PathInZip] = None - - @classmethod - def from_dict(cls, dictionary: dict): - base = cls._dict2fields(dictionary) - if 'info_path' in base and base['info_path'] is not None: - base['info_path'] = PathInZip(base['info_path']) - return cls(**base) - - def to_dict(self): - d = super().to_dict() - if d['info_path'] is not None: - d['info_path'] = str(d['info_path']) - return d - - -@dataclass(order=True) -class SegmentInfo(BaseInfo): - meta: AudioMeta - seek_time: float - n_frames: int # actual number of frames without padding - total_frames: int # total number of frames, padding included - sample_rate: int # actual sample rate - - -DEFAULT_EXTS = ['.wav', '.mp3', '.flac', '.ogg', '.m4a'] - -logger = logging.getLogger(__name__) - - -def _get_audio_meta(file_path: str, minimal: bool = True) -> AudioMeta: - """AudioMeta from a path to an audio file. - - Args: - file_path (str): Resolved path of valid audio file. - minimal (bool): Whether to only load the minimal set of metadata (takes longer if not). - Returns: - AudioMeta: Audio file path and its metadata. - """ - info = audio_info(file_path) - amplitude: tp.Optional[float] = None - if not minimal: - wav, sr = audio_read(file_path) - amplitude = wav.abs().max().item() - return AudioMeta(file_path, info.duration, info.sample_rate, amplitude) - - -def _resolve_audio_meta(m: AudioMeta, fast: bool = True) -> AudioMeta: - """If Dora is available as a dependency, try to resolve potential relative paths - in list of AudioMeta. This method is expected to be used when loading meta from file. - - Args: - m (AudioMeta): Audio meta to resolve. - fast (bool): If True, uses a really fast check for determining if a file is already absolute or not. - Only valid on Linux/Mac. - Returns: - AudioMeta: Audio meta with resolved path. - """ - def is_abs(m): - if fast: - return str(m)[0] == '/' - else: - os.path.isabs(str(m)) - - if not dora: - return m - - if not is_abs(m.path): - m.path = dora.git_save.to_absolute_path(m.path) - if m.info_path is not None and not is_abs(m.info_path.zip_path): - m.info_path.zip_path = dora.git_save.to_absolute_path(m.path) - return m - - -def find_audio_files(path: tp.Union[Path, str], - exts: tp.List[str] = DEFAULT_EXTS, - resolve: bool = True, - minimal: bool = True, - progress: bool = False, - workers: int = 0) -> tp.List[AudioMeta]: - """Build a list of AudioMeta from a given path, - collecting relevant audio files and fetching meta info. - - Args: - path (str or Path): Path to folder containing audio files. - exts (list of str): List of file extensions to consider for audio files. - minimal (bool): Whether to only load the minimal set of metadata (takes longer if not). - progress (bool): Whether to log progress on audio files collection. - workers (int): number of parallel workers, if 0, use only the current thread. - Returns: - List[AudioMeta]: List of audio file path and its metadata. - """ - audio_files = [] - futures: tp.List[Future] = [] - pool: tp.Optional[ThreadPoolExecutor] = None - with ExitStack() as stack: - if workers > 0: - pool = ThreadPoolExecutor(workers) - stack.enter_context(pool) - - if progress: - print("Finding audio files...") - for root, folders, files in os.walk(path, followlinks=True): - for file in files: - full_path = Path(root) / file - if full_path.suffix.lower() in exts: - audio_files.append(full_path) - if pool is not None: - futures.append(pool.submit(_get_audio_meta, str(audio_files[-1]), minimal)) - if progress: - print(format(len(audio_files), " 8d"), end='\r', file=sys.stderr) - - if progress: - print("Getting audio metadata...") - meta: tp.List[AudioMeta] = [] - for idx, file_path in enumerate(audio_files): - try: - if pool is None: - m = _get_audio_meta(str(file_path), minimal) - else: - m = futures[idx].result() - if resolve: - m = _resolve_audio_meta(m) - except Exception as err: - print("Error with", str(file_path), err, file=sys.stderr) - continue - meta.append(m) - if progress: - print(format((1 + idx) / len(audio_files), " 3.1%"), end='\r', file=sys.stderr) - meta.sort() - return meta - - -def load_audio_meta(path: tp.Union[str, Path], - resolve: bool = True, fast: bool = True) -> tp.List[AudioMeta]: - """Load list of AudioMeta from an optionally compressed json file. - - Args: - path (str or Path): Path to JSON file. - resolve (bool): Whether to resolve the path from AudioMeta (default=True). - fast (bool): activates some tricks to make things faster. - Returns: - List[AudioMeta]: List of audio file path and its total duration. - """ - open_fn = gzip.open if str(path).lower().endswith('.gz') else open - with open_fn(path, 'rb') as fp: # type: ignore - lines = fp.readlines() - meta = [] - for line in lines: - d = json.loads(line) - m = AudioMeta.from_dict(d) - if resolve: - m = _resolve_audio_meta(m, fast=fast) - meta.append(m) - return meta - - -def save_audio_meta(path: tp.Union[str, Path], meta: tp.List[AudioMeta]): - """Save the audio metadata to the file pointer as json. - - Args: - path (str or Path): Path to JSON file. - metadata (list of BaseAudioMeta): List of audio meta to save. - """ - Path(path).parent.mkdir(exist_ok=True, parents=True) - open_fn = gzip.open if str(path).lower().endswith('.gz') else open - with open_fn(path, 'wb') as fp: # type: ignore - for m in meta: - json_str = json.dumps(m.to_dict()) + '\n' - json_bytes = json_str.encode('utf-8') - fp.write(json_bytes) - - -class AudioDataset: - """Base audio dataset. - - The dataset takes a list of AudioMeta and create a dataset composed of segments of audio - and potentially additional information, by creating random segments from the list of audio - files referenced in the metadata and applying minimal data pre-processing such as resampling, - mixing of channels, padding, etc. - - If no segment_duration value is provided, the AudioDataset will return the full wav for each - audio file. Otherwise, it will randomly sample audio files and create a segment of the specified - duration, applying padding if required. - - By default, only the torch Tensor corresponding to the waveform is returned. Setting return_info=True - allows to return a tuple containing the torch Tensor and additional metadata on the segment and the - original audio meta. - - Args: - meta (tp.List[AudioMeta]): List of audio files metadata. - segment_duration (float): Optional segment duration of audio to load. - If not specified, the dataset will load the full audio segment from the file. - shuffle (bool): Set to `True` to have the data reshuffled at every epoch. - sample_rate (int): Target sample rate of the loaded audio samples. - channels (int): Target number of channels of the loaded audio samples. - sample_on_duration (bool): Set to `True` to sample segments with probability - dependent on audio file duration. This is only used if `segment_duration` is provided. - sample_on_weight (bool): Set to `True` to sample segments using the `weight` entry of - `AudioMeta`. If `sample_on_duration` is also True, the actual weight will be the product - of the file duration and file weight. This is only used if `segment_duration` is provided. - min_segment_ratio (float): Minimum segment ratio to use when the audio file - is shorter than the desired segment. - max_read_retry (int): Maximum number of retries to sample an audio segment from the dataset. - return_info (bool): Whether to return the wav only or return wav along with segment info and metadata. - min_audio_duration (tp.Optional[float], optional): Minimum audio file duration, in seconds, if provided - audio shorter than this will be filtered out. - max_audio_duration (tp.Optional[float], optional): Maximal audio file duration in seconds, if provided - audio longer than this will be filtered out. - """ - def __init__(self, - meta: tp.List[AudioMeta], - segment_duration: tp.Optional[float] = None, - shuffle: bool = True, - num_samples: int = 10_000, - sample_rate: int = 48_000, - channels: int = 2, - pad: bool = True, - sample_on_duration: bool = True, - sample_on_weight: bool = True, - min_segment_ratio: float = 0.5, - max_read_retry: int = 10, - return_info: bool = False, - min_audio_duration: tp.Optional[float] = None, - max_audio_duration: tp.Optional[float] = None - ): - assert len(meta) > 0, 'No audio meta provided to AudioDataset. Please check loading of audio meta.' - assert segment_duration is None or segment_duration > 0 - assert segment_duration is None or min_segment_ratio >= 0 - logging.debug(f'sample_on_duration: {sample_on_duration}') - logging.debug(f'sample_on_weight: {sample_on_weight}') - logging.debug(f'pad: {pad}') - logging.debug(f'min_segment_ratio: {min_segment_ratio}') - - self.segment_duration = segment_duration - self.min_segment_ratio = min_segment_ratio - self.max_audio_duration = max_audio_duration - self.min_audio_duration = min_audio_duration - if self.min_audio_duration is not None and self.max_audio_duration is not None: - assert self.min_audio_duration <= self.max_audio_duration - self.meta: tp.List[AudioMeta] = self._filter_duration(meta) - assert len(self.meta) # Fail fast if all data has been filtered. - self.total_duration = sum(d.duration for d in self.meta) - - if segment_duration is None: - num_samples = len(self.meta) - self.num_samples = num_samples - self.shuffle = shuffle - self.sample_rate = sample_rate - self.channels = channels - self.pad = pad - self.sample_on_weight = sample_on_weight - self.sample_on_duration = sample_on_duration - self.sampling_probabilities = self._get_sampling_probabilities() - self.max_read_retry = max_read_retry - self.return_info = return_info - - def __len__(self): - return self.num_samples - - def _get_sampling_probabilities(self, normalized: bool = True): - """Return the sampling probabilities for each file inside `self.meta`. - """ - scores: tp.List[float] = [] - for file_meta in self.meta: - score = 1. - if self.sample_on_weight and file_meta.weight is not None: - score *= file_meta.weight - if self.sample_on_duration: - score *= file_meta.duration - scores.append(score) - probabilities = torch.tensor(scores) - if normalized: - probabilities /= probabilities.sum() - return probabilities - - def sample_file(self, rng: torch.Generator) -> AudioMeta: - """Sample a given file from `self.meta`. Can be overriden in subclasses. - This is only called if `segment_duration` is not None. - - You must use the provided random number generator `rng` for reproducibility. - """ - if not self.sample_on_weight and not self.sample_on_duration: - file_index = int(torch.randint(len(self.sampling_probabilities), (1,), generator=rng).item()) - else: - file_index = int(torch.multinomial(self.sampling_probabilities, 1, generator=rng).item()) - - return self.meta[file_index] - - def __getitem__(self, index: int) -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, SegmentInfo]]: - if self.segment_duration is None: - file_meta = self.meta[index] - out, sr = audio_read(file_meta.path) - out = convert_audio(out, sr, self.sample_rate, self.channels) - n_frames = out.shape[-1] - segment_info = SegmentInfo(file_meta, seek_time=0., n_frames=n_frames, total_frames=n_frames, - sample_rate=self.sample_rate) - else: - rng = torch.Generator() - if self.shuffle: - # We use index, plus extra randomness - rng.manual_seed(index + self.num_samples * random.randint(0, 2**24)) - else: - # We only use index - rng.manual_seed(index) - - for retry in range(self.max_read_retry): - file_meta = self.sample_file(rng) - # We add some variance in the file position even if audio file is smaller than segment - # without ending up with empty segments - max_seek = max(0, file_meta.duration - self.segment_duration * self.min_segment_ratio) - seek_time = torch.rand(1, generator=rng).item() * max_seek - try: - out, sr = audio_read(file_meta.path, seek_time, self.segment_duration, pad=False) - out = convert_audio(out, sr, self.sample_rate, self.channels) - n_frames = out.shape[-1] - target_frames = int(self.segment_duration * self.sample_rate) - if self.pad: - out = F.pad(out, (0, target_frames - n_frames)) - segment_info = SegmentInfo(file_meta, seek_time, n_frames=n_frames, total_frames=target_frames, - sample_rate=self.sample_rate) - except Exception as exc: - logger.warning("Error opening file %s: %r", file_meta.path, exc) - if retry == self.max_read_retry - 1: - raise - else: - break - - if self.return_info: - # Returns the wav and additional information on the wave segment - return out, segment_info - else: - return out - - def collater(self, samples): - """The collater function has to be provided to the dataloader - if AudioDataset has return_info=True in order to properly collate - the samples of a batch. - """ - if self.segment_duration is None and len(samples) > 1: - assert self.pad, "Must allow padding when batching examples of different durations." - - # In this case the audio reaching the collater is of variable length as segment_duration=None. - to_pad = self.segment_duration is None and self.pad - if to_pad: - max_len = max([wav.shape[-1] for wav, _ in samples]) - - def _pad_wav(wav): - return F.pad(wav, (0, max_len - wav.shape[-1])) - - if self.return_info: - if len(samples) > 0: - assert len(samples[0]) == 2 - assert isinstance(samples[0][0], torch.Tensor) - assert isinstance(samples[0][1], SegmentInfo) - - wavs = [wav for wav, _ in samples] - segment_infos = [copy.deepcopy(info) for _, info in samples] - - if to_pad: - # Each wav could be of a different duration as they are not segmented. - for i in range(len(samples)): - # Determines the total legth of the signal with padding, so we update here as we pad. - segment_infos[i].total_frames = max_len - wavs[i] = _pad_wav(wavs[i]) - - wav = torch.stack(wavs) - return wav, segment_infos - else: - assert isinstance(samples[0], torch.Tensor) - if to_pad: - samples = [_pad_wav(s) for s in samples] - return torch.stack(samples) - - def _filter_duration(self, meta: tp.List[AudioMeta]) -> tp.List[AudioMeta]: - """Filters out audio files with short durations. - Removes from meta files that have durations that will not allow to samples examples from them. - """ - orig_len = len(meta) - - # Filter data that is too short. - if self.min_audio_duration is not None: - meta = [m for m in meta if m.duration >= self.min_audio_duration] - - # Filter data that is too long. - if self.max_audio_duration is not None: - meta = [m for m in meta if m.duration <= self.max_audio_duration] - - filtered_len = len(meta) - removed_percentage = 100*(1-float(filtered_len)/orig_len) - msg = 'Removed %.2f percent of the data because it was too short or too long.' % removed_percentage - if removed_percentage < 10: - logging.debug(msg) - else: - logging.warning(msg) - return meta - - @classmethod - def from_meta(cls, root: tp.Union[str, Path], **kwargs): - """Instantiate AudioDataset from a path to a directory containing a manifest as a jsonl file. - - Args: - root (str or Path): Path to root folder containing audio files. - kwargs: Additional keyword arguments for the AudioDataset. - """ - root = Path(root) - if root.is_dir(): - if (root / 'data.jsonl').exists(): - root = root / 'data.jsonl' - elif (root / 'data.jsonl.gz').exists(): - root = root / 'data.jsonl.gz' - else: - raise ValueError("Don't know where to read metadata from in the dir. " - "Expecting either a data.jsonl or data.jsonl.gz file but none found.") - meta = load_audio_meta(root) - return cls(meta, **kwargs) - - @classmethod - def from_path(cls, root: tp.Union[str, Path], minimal_meta: bool = True, - exts: tp.List[str] = DEFAULT_EXTS, **kwargs): - """Instantiate AudioDataset from a path containing (possibly nested) audio files. - - Args: - root (str or Path): Path to root folder containing audio files. - minimal_meta (bool): Whether to only load minimal metadata or not. - exts (list of str): Extensions for audio files. - kwargs: Additional keyword arguments for the AudioDataset. - """ - root = Path(root) - if root.is_file(): - meta = load_audio_meta(root, resolve=True) - else: - meta = find_audio_files(root, exts, minimal=minimal_meta, resolve=True) - return cls(meta, **kwargs) - - -def main(): - logging.basicConfig(stream=sys.stderr, level=logging.INFO) - parser = argparse.ArgumentParser( - prog='audio_dataset', - description='Generate .jsonl files by scanning a folder.') - parser.add_argument('root', help='Root folder with all the audio files') - parser.add_argument('output_meta_file', - help='Output file to store the metadata, ') - parser.add_argument('--complete', - action='store_false', dest='minimal', default=True, - help='Retrieve all metadata, even the one that are expansive ' - 'to compute (e.g. normalization).') - parser.add_argument('--resolve', - action='store_true', default=False, - help='Resolve the paths to be absolute and with no symlinks.') - parser.add_argument('--workers', - default=10, type=int, - help='Number of workers.') - args = parser.parse_args() - meta = find_audio_files(args.root, DEFAULT_EXTS, progress=True, - resolve=args.resolve, minimal=args.minimal, workers=args.workers) - save_audio_meta(args.output_meta_file, meta) - - -if __name__ == '__main__': - main() diff --git a/spaces/radames/transformers-js-sveltekit-server-example-app/src/app.html b/spaces/radames/transformers-js-sveltekit-server-example-app/src/app.html deleted file mode 100644 index effe0d0d266c6d908a42d8f3be199165d03fb6e4..0000000000000000000000000000000000000000 --- a/spaces/radames/transformers-js-sveltekit-server-example-app/src/app.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - %sveltekit.head% - - -
    %sveltekit.body%
    - - diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Bluetooth device Rfcomm Protocol Tdi Driver Windows 8.1 Download and Install in Minutes..md b/spaces/raedeXanto/academic-chatgpt-beta/Bluetooth device Rfcomm Protocol Tdi Driver Windows 8.1 Download and Install in Minutes..md deleted file mode 100644 index 83a16173f32de6f88ba18edaaa6fe683aa5bc9fd..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Bluetooth device Rfcomm Protocol Tdi Driver Windows 8.1 Download and Install in Minutes..md +++ /dev/null @@ -1,132 +0,0 @@ -
    -

    Bluetooth Device Rfcomm Protocol Tdi Driver Windows 8.1

    -

    Do you have a Bluetooth device that you want to connect to your Windows 8.1 computer? If so, you may need to install a driver for Bluetooth device Rfcomm Protocol Tdi. In this article, we will explain what Bluetooth device Rfcomm Protocol Tdi is, why you need a driver for it, how to download and install the driver, and how to troubleshoot common issues with it.

    -

    What is Bluetooth?

    -

    Bluetooth is a wireless technology that allows devices to communicate with each other over short distances. It was invented in 1994 by a group of engineers from different companies who wanted to create a universal standard for wireless connectivity. The name Bluetooth comes from the nickname of a 10th-century Danish king, Harald Bluetooth, who united different tribes in Scandinavia.

    -

    Bluetooth device Rfcomm Protocol Tdi Driver Windows 8.1


    Downloadhttps://tinourl.com/2uKZK3



    -

    Bluetooth devices use radio waves to transmit data between each other. They can form networks called piconets, which consist of up to eight devices, or scatternets, which consist of multiple piconets. Each device has a unique address and can act as a master or a slave in a network. The master device controls the communication among the devices, while the slave devices follow the instructions of the master device.

    -

    Bluetooth devices can support different profiles, which are sets of specifications that define how they interact with each other for specific purposes. For example, some common profiles are Headset Profile (HSP), which allows a Bluetooth headset to connect to a phone or a computer; Advanced Audio Distribution Profile (A2DP), which allows a Bluetooth speaker to stream audio from a phone or a computer; and Personal Area Networking Profile (PAN), which allows a Bluetooth device to share internet access with another device.

    -

    What is Rfcomm Protocol Tdi?

    -

    Rfcomm Protocol Tdi is a component of the Bluetooth driver stack that implements the Bluetooth serial cable emulation protocol. This protocol allows Bluetooth devices to emulate a serial port connection over a wireless link. This way, applications that use serial port communication can work with Bluetooth devices without any modification.

    -

    Rfcomm Protocol Tdi exposes the Transport Driver Interface (TDI) to applications, which is a standard interface for network transport drivers in Windows. This allows applications to access Rfcomm Protocol Tdi as if it were a networking transport driver. For example, applications can use Windows sockets (Winsock) API to communicate with Rfcomm Protocol Tdi.

    -

    How to install Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver update for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver error code 10 on Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver not working on Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver download link for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver compatibility with Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver missing from device manager on Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver troubleshooting guide for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver alternative for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver features and specifications for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver reviews and ratings for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver price and availability for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver manual and instructions for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver warranty and support for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver benefits and advantages for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver comparison with other Bluetooth drivers for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver best practices and tips for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver common issues and solutions for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver performance and speed test for Windows 8.1
    -Bluetooth device Rfcomm Protocol Tdi Driver security and privacy settings for Windows 8.1
    -How to uninstall Bluetooth device Rfcomm Protocol Tdi Driver from Windows 8.1
    -How to fix Bluetooth device Rfcomm Protocol Tdi Driver blue screen of death on Windows 8.1
    -How to enable or disable Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to pair or unpair Bluetooth device Rfcomm Protocol Tdi Driver with other devices on Windows 8.1
    -How to configure or customize Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to upgrade or downgrade Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to backup or restore Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use Bluetooth device Rfcomm Protocol Tdi Driver with different applications on Windows 8.1
    -How to troubleshoot Bluetooth device Rfcomm Protocol Tdi Driver connection problems on Windows 8.1
    -How to optimize or improve Bluetooth device Rfcomm Protocol Tdi Driver performance on Windows 8.1
    -How to check or verify Bluetooth device Rfcomm Protocol Tdi Driver version on Windows 8.1
    -How to change or reset Bluetooth device Rfcomm Protocol Tdi Driver password on Windows 8.1
    -How to share or transfer files using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to stream or play audio using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to print or scan documents using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to sync or backup data using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to access or control remote devices using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to monitor or manage power consumption using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use voice commands or speech recognition using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use gestures or touch controls using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use location services or GPS using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use NFC or RFID using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use Wi-Fi Direct or hotspot using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use infrared or IR using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use Zigbee or Z-Wave using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use ANT+ or BLE using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use USB or serial port using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use Ethernet or LAN using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1
    -How to use VPN or proxy using Bluetooth device Rfcomm Protocol Tdi Driver on Windows 8.1

    -

    Rfcomm Protocol Tdi also uses the Logical Link Control and Adaptation Protocol (L2CAP) and the Service Discovery Protocol (SDP) interfaces provided by BthPort, which is another component of the Bluetooth driver stack that handles the communication between the Bluetooth hardware and the software. L2CAP provides reliable data transfer and multiplexing services for Bluetooth connections, while SDP provides service discovery and browsing services for Bluetooth devices.

    -

    Why do you need a driver for Bluetooth device Rfcomm Protocol Tdi?

    -

    A driver is a software program that allows your operating system to communicate with a hardware device. Without a driver, your operating system cannot recognize or control your hardware device properly.

    -

    You need a driver for Bluetooth device Rfcomm Protocol Tdi because it enables your Windows 8.1 computer to communicate with your Bluetooth device that supports the serial cable emulation protocol. This way, you can use your Bluetooth device with applications that use serial port communication, such as terminal emulators, dial-up networking, or file transfer programs.

    -

    If you do not have a driver for Bluetooth device Rfcomm Protocol Tdi installed on your Windows 8.1 computer, you may encounter some problems when trying to connect or use your Bluetooth device. For example, you may see an error message saying "Bluetooth peripheral device driver not found" or "Device driver software was not successfully installed". You may also experience poor performance or compatibility issues with your Bluetooth device.

    -

    How to download and install the driver for Bluetooth device Rfcomm Protocol Tdi on Windows 8.1?

    -

    To download and install the driver for Bluetooth device Rfcomm Protocol Tdi on Windows 8.1, you can follow these steps:

    -
      -
    1. Make sure your Windows 8.1 computer has a built-in or external Bluetooth adapter that is compatible with your Bluetooth device.
    2. -
    3. Turn on your Bluetooth device and make it discoverable by other devices.
    4. -
    5. On your Windows 8.1 computer, go to Settings > PC settings > PC and devices > Devices.
    6. -
    7. Click Add a device and wait for your computer to scan for nearby devices.
    8. -
    9. Select your Bluetooth device from the list and click Pair.
    10. -
    11. If prompted, enter the pairing code or confirm the pairing request on both devices.
    12. -
    13. Wait for your computer to install the driver for your Bluetooth device automatically.
    14. -
    15. If your computer cannot find or install the driver automatically, you may need to download it manually from the manufacturer's website or use a third-party software such as Intel® Driver & Support Assistant or Dell SupportAssist .
    16. -
    17. Follow the instructions on the screen or in the documentation provided by the manufacturer or software provider to complete the installation process.
    18. -
    19. Restart your computer if required.
    20. -
    -

    How to troubleshoot common issues with Bluetooth device Rfcomm Protocol Tdi on Windows 8.1?

    -

    If you encounter any issues with Bluetooth device Rfcomm Protocol Tdi on Windows 8.1, you can try these tips and solutions:

    -
      -
    • Make sure your Bluetooth device is turned on and has enough battery power.
    • -
    • Make sure your Bluetooth device is within range of your computer and there are no physical obstacles or interferences between them.
    • -
    • Make sure your computer and your Bluetooth device are paired correctly and have compatible profiles.
    • -
    • Make sure your computer has the latest updates installed for Windows 8.1 and the driver for your Bluetooth device.
    • -
    • Make sure your computer has enough free disk space and memory available.
    • -
    • Make sure your computer does not have any conflicting programs or services running in the background that may interfere with your Bluetooth connection.
    • -
    • Make sure your computer does not have any malware or viruses that may affect your system performance or security.
    • -
    • If none of these tips work, you may need to uninstall and reinstall the driver for your Bluetooth device or contact the manufacturer or software provider for further assistance.
    • -
    -

    Conclusion

    -

    In conclusion, we have explained what Bluetooth device Rfcomm Protocol Tdi is, why you need a driver for it, how to download and install the driver, and how to troubleshoot common issues with it on Windows 8.1. We hope this article has been helpful and informative for you.

    -

    If you have any questions or feedback about this topic, please feel free to leave us a comment below. We would love to hear from you!

    -

    Frequently Asked Questions

    -
      -
    1. What is the difference between Rfcomm Protocol Tdi and WshBth?
    2. -the Windows Sockets (Winsock) API to applications. Rfcomm Protocol Tdi is used by applications that use serial port communication directly, while WshBth is used by applications that use Winsock API to communicate with Rfcomm Protocol Tdi.

      -
    3. How can I check if the driver for Bluetooth device Rfcomm Protocol Tdi is installed correctly on my Windows 8.1 computer?
    4. -

      One way to check if the driver for Bluetooth device Rfcomm Protocol Tdi is installed correctly on your Windows 8.1 computer is to use the Device Manager. To do this, follow these steps:

      -
        -
      1. Press Windows key + X and select Device Manager from the menu.
      2. -
      3. Expand the Bluetooth category and look for your Bluetooth device.
      4. -
      5. Right-click on your Bluetooth device and select Properties.
      6. -
      7. Click on the Driver tab and check the driver details, such as the provider, date, version, and digital signer.
      8. -
      9. If the driver details match the driver that you downloaded and installed, then the driver is installed correctly. If not, you may need to update or reinstall the driver.
      10. -
      -
    5. What are some examples of applications that use Bluetooth device Rfcomm Protocol Tdi?
    6. -

      Some examples of applications that use Bluetooth device Rfcomm Protocol Tdi are:

      -
        -
      • Terminal emulators, such as PuTTY or HyperTerminal, that allow you to access remote devices or systems via serial port communication.
      • -
      • Dial-up networking, such as Dial-Up Networking (DUN) or Personal Area Network (PAN), that allow you to use your Bluetooth device as a modem to access the internet or a network.
      • -
      • File transfer programs, such as Bluetooth File Transfer (BFT) or Object Push Profile (OPP), that allow you to send and receive files between your Bluetooth device and your computer.
      • -
      -
    7. How can I improve the performance and security of my Bluetooth connection?
    8. -

      Some ways to improve the performance and security of your Bluetooth connection are:

      -
        -
      • Use a strong pairing code or confirm the pairing request on both devices when pairing your Bluetooth device with your computer.
      • -
      • Turn off your Bluetooth device or make it undiscoverable when not in use.
      • -
      • Avoid connecting to unknown or untrusted Bluetooth devices or networks.
      • -
      • Use encryption and authentication features if available on your Bluetooth device and your computer.
      • -
      -
    9. Where can I find more information about Bluetooth technology and drivers?
    10. -

      You can find more information about Bluetooth technology and drivers on these websites:

      - -

      0a6ba089eb
      -
      -
      \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/HACK GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP The Ultimate CDDVDBlu-ray Burning Software.md b/spaces/raedeXanto/academic-chatgpt-beta/HACK GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP The Ultimate CDDVDBlu-ray Burning Software.md deleted file mode 100644 index bb00c276ec861f28da9e841b62f3c0afc4b16146..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/HACK GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP The Ultimate CDDVDBlu-ray Burning Software.md +++ /dev/null @@ -1,108 +0,0 @@ -
      -

      HACK GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP

      -

      If you are looking for a powerful and reliable CD/DVD/Blu-ray burning software, you might have come across a file named GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP. This file claims to contain the latest version of CDRWIN, a popular burning software developed by Golden Hawk Technology, along with a keygen (a tool that generates serial numbers or activation codes) created by ORiON, a well-known cracking group. But what exactly is this file, why would you want to download it, how can you install it, and how can you use it? In this article, we will answer these questions and more.

      -

      HACK GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP


      Download File >>>>> https://tinourl.com/2uKZiu



      -

      What is GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP?

      -

      Before we dive into the details of this file, let us first understand what are the components that make up this file name.

      -

      A brief introduction to CDRWIN

      -

      CDRWIN is a CD/DVD/Blu-ray burning software for Microsoft Windows developed by Golden Hawk Technology company. It was first released in 1996 and has since become one of the most popular burning software among users who need advanced features and functionality. CDRWIN supports the recording of digital audio, CD-ROM (Mode 1), CD-ROM-XA (Mode 2), CD-I, mixed-mode, and multi-session discs. It also features the Cue Sheet scripting language that allows users to create custom disc layouts and manipulate disc data. CDRWIN is compatible with Windows 7, 8, and 10.

      -

      A brief introduction to ORiON

      -

      ORiON is a cracking group that specializes in releasing keygens, patches, cracks, and serials for various software products. They are one of the oldest and most respected groups in the scene, having been active since 1996. ORiON has cracked many popular software products such as Adobe Photoshop, WinRAR, Nero Burning ROM, and of course, CDRWIN.

      -

      A brief introduction to keygen

      -

      A keygen is a tool that generates serial numbers or activation codes for software products that require registration or activation. A keygen usually works by analyzing the algorithm or pattern used by the software vendor to create valid serial numbers or activation codes, and then replicating that algorithm or pattern to produce new serial numbers or activation codes that can be used to activate the software product. A keygen may also include instructions on how to use it or bypass any protection mechanisms implemented by the software vendor.

      -

      How to hack GoldenHawk CDRWin v3.9K with ORiON keygen
      -Download GoldenHawk CDRWin v3.9K cracked by ORiON
      -GoldenHawk CDRWin v3.9K hack tutorial and keygen download
      -ORiON keygen for GoldenHawk CDRWin v3.9K free download
      -GoldenHawk CDRWin v3.9K full version hack with ORiON keygen
      -Hack GoldenHawk CDRWin v3.9K using ORiON keygen zip file
      -GoldenHawk CDRWin v3.9K hack and keygen by ORiON zip download
      -ORiON zip file with keygen for GoldenHawk CDRWin v3.9K hack
      -GoldenHawk CDRWin v3.9K hacked version and ORiON keygen zip
      -Zip file with ORiON keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K incl keygen by ORiON zip
      -GoldenHawk CDRWin v3.9K incl ORiON keygen hack zip
      -ORiON zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON keygen and GoldenHawk CDRWin v3.9K hack incl
      -Hack GoldenHawk CDRWin v3.9K with keygen by ORiON in zip
      -GoldenHawk CDRWin v3.9K with ORiON keygen hack in zip
      -ORiON in zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON in it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K using keygen by ORiON from zip
      -GoldenHawk CDRWin v3.9K using ORiON keygen hack from zip
      -ORiON from zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON from it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K by using keygen by ORiON inside zip
      -GoldenHawk CDRWin v3.9K by using ORiON keygen hack inside zip
      -ORiON inside zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON inside it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K via keygen by ORiON within zip
      -GoldenHawk CDRWin v3.9K via ORiON keygen hack within zip
      -ORiON within zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON within it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K through keygen by ORiON inside the zip
      -GoldenHawk CDRWin v3.9K through ORiON keygen hack inside the zip
      -ORiON inside the zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON inside the it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K by means of keygen by ORiON in the zip
      -GoldenHawk CDRWin v3.9K by means of ORiON keygen hack in the zip
      -ORiON in the zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON in the it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K thanks to keygen by ORiON within the zip
      -GoldenHawk CDRWin v3.9K thanks to ORiON keygen hack within the zip
      -ORiON within the zip with keygen and hack for GoldenHawk CDRWin v3.9K
      -Zip with ORiON within the it and keygen and GoldenHawk CDRWin v3.9K hack
      -Hack GoldenHawk CDRWin v3.9K owing to keygen by ORiON inside the zip file
      -GoldenHawk CDRWin v3.9K owing to ORiON keygen hack inside the zip file
      -ORiON inside the zip file with keygen and hack for GoldenHawk CDRWin v3.9K

      -

      Why would you want to download GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP?

      -

      Now that we know what this file contains, let us explore why someone would want to download it.

      -

      The benefits of CDRWIN

      -

      As mentioned earlier, CDRWIN is a powerful and reliable burning software that offers many features and functions that other burning software may not have. Some of the benefits of using CDRWIN are:

      -
        -
      • It supports a wide range of disc formats and types, including audio CDs (CD-DA), data CDs (CD-ROM, CD-ROM/XA), video CDs (VCD), Blu-rays (BD-R/RE), and more.
      • -
      • It allows users to create custom disc layouts and manipulate disc data using the Cue Sheet scripting language.
      • -
      • It can copy discs of all formats, whether audio, data, video, mixed mode or game CDs, even if only the burner is on the computer as the only CD drive.
      • -
      • It can handle overburning of blanks and overlong 90 min and 99 min blanks.
      • -
      • It can enable and disable jitter correction and set subcode options for copying audio discs.
      • -
      • It can adjust the Mode 1 and Mode 2 transfer for copying mixed and raw data discs.
      • -
      • It can back up existing discs or SCSI devices to image files or vice versa.
      • -
      • It can display disc information such as tracks, sessions, time, etc.
      • -
      • It has a simple and intuitive interface that offers quick access to the most important functions.
      • -
      -

      The benefits of ORiON keygen

      -

      The main benefit of using ORiON keygen is that it allows users to activate CDRWIN without paying for it or going through any registration or activation process. This means that users can enjoy all the features and functions of CDRWIN without any limitations or restrictions imposed by the software vendor. ORiON keygen also provides instructions on how to use it or bypass any protection mechanisms implemented by the software vendor.

      -

      The risks of downloading GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP

      -

      However, downloading GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP also comes with some risks that users should be aware of before deciding to do so. Some of these risks are:

      -
        -
      • It is illegal to download or use pirated software products without permission from the software vendor. Users may face legal consequences such as fines or lawsuits if they are caught doing so.
      • -
      • It is unethical to download or use pirated software products without paying for them or supporting the software vendor who invested time and money into developing them.
      • -
      • It is unsafe to download or use pirated software products from unknown sources as they may contain malware such as viruses, trojans, worms, spyware, etc. that can harm your computer or steal your personal information.
      • -
      • It is unreliable to download or use pirated software products as they may not work properly or cause errors or crashes on your computer due to compatibility issues or bugs.
      • -
      • It is disrespectful to download or use pirated software products as they may damage the reputation or income of the software vendor who created them.
      • -
      -

      How to download and install GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP?

      -

      If you still want to download and install GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP despite knowing the risks involved, here are the steps you need to follow:

      -

      The steps to download GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP

      -
        -
      1. Find a reliable source that offers GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP for download. You can use a search engine such as Google or Bing to look for websites that host this file.
      2. -
      3. Download the file to your computer and extract it using a program such as WinRAR or 7-Zip. You should see two files: CDRWIN.EXE and ORiON.NFO.
      4. -
      5. Scan the files with your anti-virus program to make sure they are safe and free of malware. If you don't have an anti-virus program, you can use an online scanner such as VirusTotal or Jotti.
      6. -
      -

      The steps to install CDRWIN using ORiON keygen

      -
        -
      1. Run the CDRWIN.EXE file and follow the installation wizard. Choose the destination folder and the components you want to install.
      2. -
      3. Do not launch CDRWIN after the installation is complete. Close the wizard and go to the folder where you installed CDRWIN.
      4. -
      5. Open the ORiON.NFO file with a text editor such as Notepad or WordPad. You should see some information about ORiON and their keygen, along with some ASCII art.
      6. -
      7. Scroll down to the bottom of the file and look for a line that says \"Serial: \". Copy the serial number that follows this line.
      8. -
      9. Run the CDRWIN.EXE file again and choose \"Unlock\" from the main window. Paste the serial number you copied into the box and click \"OK\".
      10. -
      11. You should see a message that says \"CDRWIN has been successfully unlocked\". Click \"OK\" again and close CDRWIN.
      12. -
      -

      The steps to verify the installation and activation of CDRWIN

      -
        -
      1. Run the CDRWIN.EXE file one more time and choose \"Settings\" from the main window. Click on the \"About\" tab and check if the version number is 3.9K and if your name is displayed as \"Registered User\".
      2. -
      3. If everything is correct, congratulations! You have successfully installed and activated CDRWIN using ORiON keygen.
      4. -
      5. If something is wrong, try repeating the previous steps or look for another source of GoldenHawk.CDRWin.v3.9K.Incl.Keygen-ORiON.ZIP.
      6. -

      0a6ba089eb
      -
      -
      \ No newline at end of file diff --git a/spaces/ramiin2/AutoGPT/run.bat b/spaces/ramiin2/AutoGPT/run.bat deleted file mode 100644 index afbab57a0603a126b04845ec754d1ecf3fdea18d..0000000000000000000000000000000000000000 --- a/spaces/ramiin2/AutoGPT/run.bat +++ /dev/null @@ -1,8 +0,0 @@ -@echo off -python scripts/check_requirements.py requirements.txt -if errorlevel 1 ( - echo Installing missing packages... - pip install -r requirements.txt -) -python -m autogpt %* -pause diff --git a/spaces/razielpanic/CompVis-stable-diffusion-v1-4/app.py b/spaces/razielpanic/CompVis-stable-diffusion-v1-4/app.py deleted file mode 100644 index e1e1025c8f06010197c50917ac9dd1ddeaf7e5aa..0000000000000000000000000000000000000000 --- a/spaces/razielpanic/CompVis-stable-diffusion-v1-4/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/CompVis/stable-diffusion-v1-4").launch() \ No newline at end of file diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Adobe Premiere Pro Cs6 Free Download With Crack 64 Bit [UPD].md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Adobe Premiere Pro Cs6 Free Download With Crack 64 Bit [UPD].md deleted file mode 100644 index 292c7612db8c9dd48ea24a5e8d3086dc91e2f182..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Adobe Premiere Pro Cs6 Free Download With Crack 64 Bit [UPD].md +++ /dev/null @@ -1,77 +0,0 @@ -
      -

      Adobe Premiere Pro CS6 Free Download with Crack 64 Bit

      -

      If you are looking for a professional video editing software that can handle any type of project, you might want to consider Adobe Premiere Pro CS6. This software is one of the most popular and powerful tools for video editors, filmmakers, and content creators. It offers a sleek, revamped user interface, incredible performance, and a host of fantastic new creative features.

      -

      adobe premiere pro cs6 free download with crack 64 bit


      Download File ===> https://urlgoal.com/2uCJYM



      -

      However, Adobe Premiere Pro CS6 is not a cheap software. It costs $799 for a single license, which might be too expensive for some users. That's why some people are looking for ways to get Adobe Premiere Pro CS6 free download with crack 64 bit. This means that they can download the software from an unofficial source and activate it with a crack or a patch that bypasses the original license verification.

      -

      But is this a good idea? What are the risks and benefits of getting Adobe Premiere Pro CS6 free download with crack 64 bit? In this article, we will answer these questions and provide you with some useful information about this software and its features.

      - -

      What is Adobe Premiere Pro CS6?

      -

      Adobe Premiere Pro CS6 is a video editing software that was released in 2012 as part of the Adobe Creative Suite 6. It is the successor of Adobe Premiere Pro CS5 and the predecessor of Adobe Premiere Pro CC. It is compatible with Windows 7 SP1, Windows 8.1, and Windows 10 (64 bit only) and Mac OS X 10.6.8 or later (64 bit only).

      -

      Adobe Premiere Pro CS6 allows you to work natively with the latest mobile, DSLR, HD, and RAW formats; edit, trim, and adjust effects in real time; stabilize shaky footage; and enjoy a sleek, revamped user interface and expanded multicam support. It also has some new features that make it stand out from other video editing software, such as:

      -
        -
      • Warp Stabilizer: This effect can automatically stabilize a bumpy camera move or lock a shot with the same technology as in Adobe After Effects. It can also remove jitter and rolling shutter artifacts and other motion-related irregularities.
      • -
      • Dynamic timeline trimming: This feature allows you to finesse your editing with precision using advanced trimming tools. You can trim clips directly in the timeline via keyboard entry or dynamically in the Program Monitor using JKL shortcuts.
      • -
      • Lumetri Deep Color Engine: This feature enables you to apply rich, preset color grades in Adobe SpeedGrade CS6 with the new Lumetri Deep Color Engine. You can also create and save your own presets to use in Premiere Pro.
      • -
      • Adobe Anywhere integration: This feature allows you to collaborate with other editors and access shared projects across your enterprise using Adobe Anywhere for video.
      • -
      • Multicam editing: This feature allows you to quickly and easily edit multicam footage from as many cameras as you have on the shoot. You can sync via timecode, switch between tracks in real time, and adjust color across multiple shots.
      • -
      • Mercury Playback Engine: This feature allows you to work dramatically faster thanks to sweeping performance, stability enhancements, and support for NVIDIA Maximus dual-GPU configurations and certain MacBook Pro OpenCL-based AMD GPUs.
      • -
      - -

      How to get Adobe Premiere Pro CS6 free download with crack 64 bit?

      -

      If you want to get Adobe Premiere Pro CS6 free download with crack 64 bit, you will need to follow these steps:

      -

      -
        -
      1. Disconnect from the internet.
      2. -
      3. Download Adobe Premiere Pro CS6 from an unofficial source. You can find many websites that offer this software for free download, but be careful as some of them might contain viruses or malware. Make sure you scan the file before opening it.
      4. -
      5. Install Adobe Premiere Pro CS6 on your computer. You might need to disable your antivirus or firewall during the installation process.
      6. -
      7. Download a crack or a patch for Adobe Premiere Pro CS6 from another source. A crack or a patch is a small program that modifies the original software code to bypass the license verification. You can find many cracks or patches online, but again, be careful as some of them might be harmful or not work properly.
      8. -
      9. Run the crack or the patch as administrator and follow the instructions. Usually, you will need to copy and paste some files into the installation folder of Adobe Premiere Pro CS6 or enter some serial numbers or codes.
      10. -
      11. Restart your computer and launch Adobe Premiere Pro CS6. You should be able to use it without any limitations or restrictions.
      12. -
      - -

      What are the risks and benefits of getting Adobe Premiere Pro CS6 free download with crack 64 bit?

      -

      Getting Adobe Premiere Pro CS6 free download with crack 64 bit might seem like a good idea if you want to save money and enjoy this software without paying for it. However, there are also some risks and drawbacks that you should be aware of before doing so. Here are some of them:

      - -

      Risks:

      -
        -
      • You might violate the law: Downloading and using cracked software is illegal in most countries and regions. You might face legal consequences if you are caught by the authorities or reported by someone else.
      • -
      • You might damage your computer: Downloading cracked software from unofficial sources might expose your computer to viruses, malware, spyware, ransomware, or other harmful programs that can compromise your security and privacy. These programs might steal your personal information, encrypt your files, delete your data, or damage your hardware.
      • -
      • You might lose your work: Using cracked software might cause unexpected errors, crashes, glitches, or compatibility issues that can affect your work quality and productivity. You might lose your projects, files, or settings due to these problems.
      • -
      • You might miss out on updates and support: Using cracked software means that you will not be able to access official updates and support from Adobe. Updates are important as they can fix bugs, improve performance, add new features, or enhance security. Support is also important as it can help you solve any issues or problems that you might encounter while using the software.
      • -
      - -

      Benefits:

      -
        -
      • You might save money: Getting Adobe Premiere Pro CS6 free download with crack 64 bit means that you will not have to pay for it. You can use this software without spending any money on it.
      • -
      • You might enjoy its features: Getting Adobe Premiere Pro CS6 free download with crack 64 bit means that you will be able to use its features without any limitations or restrictions. You can edit any type of video project with this software and take advantage of its new creative features.
      • -
      - -

      Conclusion

      -

      In conclusion, getting Adobe Premiere Pro CS6 free download with crack 64 bit is a risky and illegal way to use this software. It might save you money and let you enjoy its features, but it also might expose you to legal consequences, security threats, work losses, or update and support issues. If you want to use this software safely and legally, we recommend that you buy it from the official website of Adobe or use an alternative video editing software that is free or cheaper than Adobe Premiere Pro CS6.

      -

      How to use Adobe Premiere Pro CS6?

      -

      Once you have installed Adobe Premiere Pro CS6 on your computer, you can start using it to create and edit your video projects. Here are some basic steps to follow:

      -
        -
      1. Launch Adobe Premiere Pro CS6 and create a new project. You can choose from various presets or customize your own settings.
      2. -
      3. Import your media files into the project. You can use the Media Browser or the Import command to browse and select the files you want to use. You can also drag and drop files from your computer or other sources.
      4. -
      5. Organize your media files in the Project panel. You can create bins, folders, labels, and metadata to sort and manage your files.
      6. -
      7. Edit your media files in the Timeline panel. You can use various tools and commands to trim, cut, split, move, copy, paste, delete, or adjust your clips. You can also use the Source Monitor and the Program Monitor to preview and edit your clips.
      8. -
      9. Add effects and transitions to your clips in the Effects panel. You can choose from hundreds of video mixing effects and apply them to your clips. You can also create adjustment layers, masks, keyframes, and expressions to control the effects.
      10. -
      11. Adjust the color and audio of your clips in the Color panel and the Audio panel. You can use the Three-Way Color Corrector, the Lumetri Deep Color Engine, the Audio Mixer, and other tools to enhance the quality and appearance of your clips.
      12. -
      13. Export your project as a video file or a sequence. You can use the Export Settings dialog box or the Adobe Media Encoder to choose from various formats, codecs, presets, and options for your output file.
      14. -
      - -

      What are the alternatives to Adobe Premiere Pro CS6?

      -

      If you are not satisfied with Adobe Premiere Pro CS6 or you want to try other video editing software, you can consider some of the alternatives that are available in the market. Here are some of them:

      -
        -
      • Davinci Resolve: This is a professional video editing software that offers advanced color correction, visual effects, motion graphics, and audio post-production. It is free for personal use and has a paid version for more features.
      • -
      • Final Cut Pro X: This is a video editing software that is designed for Mac users. It has a magnetic timeline, multicam editing, 360-degree video editing, and motion graphics templates.
      • -
      • Vegas Pro: This is a video editing software that is designed for Windows users. It has a flexible timeline, multicam editing, HDR support, and advanced audio editing.
      • -
      • HitFilm Express: This is a video editing software that is designed for beginners and enthusiasts. It has a simple interface, basic editing tools, and some visual effects and transitions.
      • -
      - -

      Conclusion

      -

      In conclusion, Adobe Premiere Pro CS6 is a powerful and professional video editing software that can handle any type of project. It has a sleek user interface, incredible performance, and a host of creative features. However, it is also expensive and illegal to get it for free with crack 64 bit. You might face legal consequences, security threats, work losses, or update and support issues if you do so. Therefore, we recommend that you buy it from the official website of Adobe or use an alternative video editing software that is free or cheaper than Adobe Premiere Pro CS6.

      -

      Conclusion

      -

      In conclusion, Adobe Premiere Pro CS6 is a powerful and professional video editing software that can handle any type of project. It has a sleek user interface, incredible performance, and a host of creative features. However, it is also expensive and illegal to get it for free with crack 64 bit. You might face legal consequences, security threats, work losses, or update and support issues if you do so. Therefore, we recommend that you buy it from the official website of Adobe or use an alternative video editing software that is free or cheaper than Adobe Premiere Pro CS6.

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Canopusediusdonglecrack15.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Canopusediusdonglecrack15.md deleted file mode 100644 index 4f3cc4f5d306337e2103f9900259254040aed8c5..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Canopusediusdonglecrack15.md +++ /dev/null @@ -1,6 +0,0 @@ -

      canopusediusdonglecrack15


      Download File > https://urlgoal.com/2uCLlq



      - -1 6b147819d6 Chevaliers De Sangreal Orchestral Score Pdf Download. 6b147819d6. canopusediusdonglecrack15. raidemeco's Ownd. 1fdad05405
      -
      -
      -

      diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Fifa 08 Highly Compressed 10mb Free 284.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Fifa 08 Highly Compressed 10mb Free 284.md deleted file mode 100644 index b3deadc1c97e28e7eba001ba13d323c79c7cfe8a..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Fifa 08 Highly Compressed 10mb Free 284.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Fifa 08 Highly Compressed 10mb Free 284


      DOWNLOAD ->>> https://urlgoal.com/2uCN8k



      -
      - d5da3c52bf
      -
      -
      -

      diff --git a/spaces/rishabh062/DocumentQuestionAnswerModel/README.md b/spaces/rishabh062/DocumentQuestionAnswerModel/README.md deleted file mode 100644 index 7480b62a9261f243641719d128b23196b5c0736a..0000000000000000000000000000000000000000 --- a/spaces/rishabh062/DocumentQuestionAnswerModel/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: DocumentQuestionAnswerModel -emoji: 🚀 -colorFrom: yellow -colorTo: gray -sdk: gradio -sdk_version: 3.23.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/rizam/literature-research-tool/README.md b/spaces/rizam/literature-research-tool/README.md deleted file mode 100644 index 9fe116664b3dc424c9914cf4cd0e928f2fe4ef8f..0000000000000000000000000000000000000000 --- a/spaces/rizam/literature-research-tool/README.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Literature Research Tool -emoji: 📉 -colorFrom: indigo -colorTo: blue -sdk: streamlit -sdk_version: 1.10.0 -app_file: app.py -pinned: false -license: mit -duplicated_from: Adapting/literature-research-tool ---- - -# Literature Research Tool -A project to develop a tool for researchers, which predicts the researching trend using natural language processing methodes. - -[[doc](https://leoxiang66.github.io/LRT-Doc/)] - - -项目目标: -构建一个搜索工具,可以实现搜索论文平台elvsier,IEEE和google scholar的论文摘要,并且通过自然语言学习的方式总结出论文的研究方向。 - -需求: -1. 搜索功能:通过api自动搜索elvsier,IEEE和google scholar的论文库,可以搜索摘要和关键字 -2. 总结功能:总结知识基础、学科结构、研究前沿。给定特定关键词,可以是单个或多个关键词,如digitalization+IOT,可以选择查找知识基础,学科结构或者研究前沿。 -3. 可视化 - -Todo list: -- [ ] 1. 选定具体idp课程以及写project description (Tao) -- [ ] 2. 具体化需求 (Zhen) -- [ ] 3. 提供各大论文库账户和api(Zhen) -- [ ] 4. 讨论确定实施方法(Zhen&Tao),可参考已有的文献分析网站,如CiteSpace,https://bibliometric.com, https://zhuanlan.zhihu.com/p/136964325 - - - diff --git a/spaces/rorallitri/biomedical-language-models/logs/Bd-Company - Bd-Mag 7 Lesbians Ls Magazine.avi !!HOT!!.md b/spaces/rorallitri/biomedical-language-models/logs/Bd-Company - Bd-Mag 7 Lesbians Ls Magazine.avi !!HOT!!.md deleted file mode 100644 index e3c8cc0117cd0a52d7325367235b65fd05288ba3..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Bd-Company - Bd-Mag 7 Lesbians Ls Magazine.avi !!HOT!!.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Bd-Company - Bd-Mag 7 lesbians ls magazine.avi


      Download Ziphttps://tinurll.com/2uznKI



      -
      - aaccfb2cb3
      -
      -
      -

      diff --git a/spaces/rossellison/kpop-face-generator/stylegan3-fun/.github/ISSUE_TEMPLATE/bug_report.md b/spaces/rossellison/kpop-face-generator/stylegan3-fun/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index de2966434faf1502d9e3ac93b79c7cf0b646fc7c..0000000000000000000000000000000000000000 --- a/spaces/rossellison/kpop-face-generator/stylegan3-fun/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: '' -assignees: '' - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. In '...' directory, run command '...' -2. See error (copy&paste full log, including exceptions and **stacktraces**). - -Please copy&paste text instead of screenshots for better searchability. - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Desktop (please complete the following information):** - - OS: [e.g. Linux Ubuntu 20.04, Windows 10] - - PyTorch version (e.g., pytorch 1.9.0) - - CUDA toolkit version (e.g., CUDA 11.4) - - NVIDIA driver version - - GPU [e.g., Titan V, RTX 3090] - - Docker: did you use Docker? If yes, specify docker image URL (e.g., nvcr.io/nvidia/pytorch:21.08-py3) - -**Additional context** -Add any other context about the problem here. diff --git a/spaces/saefro991/aet_demo/preprocess.py b/spaces/saefro991/aet_demo/preprocess.py deleted file mode 100644 index 6415348f80dfe8a8cdad60e8a433ebaec4724da0..0000000000000000000000000000000000000000 --- a/spaces/saefro991/aet_demo/preprocess.py +++ /dev/null @@ -1,152 +0,0 @@ -import numpy as np -import os -import librosa -import tqdm -import pickle -import random -import argparse -import yaml -import pathlib - - -def get_arg(): - parser = argparse.ArgumentParser() - parser.add_argument("--config_path", required=True, type=pathlib.Path) - parser.add_argument("--corpus_type", default=None, type=str) - parser.add_argument("--source_path", default=None, type=pathlib.Path) - parser.add_argument("--source_path_task", default=None, type=pathlib.Path) - parser.add_argument("--aux_path", default=None, type=pathlib.Path) - parser.add_argument("--preprocessed_path", default=None, type=pathlib.Path) - parser.add_argument("--n_train", default=None, type=int) - parser.add_argument("--n_val", default=None, type=int) - parser.add_argument("--n_test", default=None, type=int) - return parser.parse_args() - - -def preprocess(config): - - # configs - preprocessed_dir = pathlib.Path(config["general"]["preprocessed_path"]) - n_train = config["preprocess"]["n_train"] - n_val = config["preprocess"]["n_val"] - n_test = config["preprocess"]["n_test"] - SR = config["preprocess"]["sampling_rate"] - - os.makedirs(preprocessed_dir, exist_ok=True) - - sourcepath = pathlib.Path(config["general"]["source_path"]) - - if config["general"]["corpus_type"] == "single": - fulllist = list(sourcepath.glob("*.wav")) - random.seed(0) - random.shuffle(fulllist) - train_filelist = fulllist[:n_train] - val_filelist = fulllist[n_train : n_train + n_val] - test_filelist = fulllist[n_train + n_val : n_train + n_val + n_test] - filelist = train_filelist + val_filelist + test_filelist - elif config["general"]["corpus_type"] == "multi-seen": - fulllist = list(sourcepath.glob("*/*.wav")) - random.seed(0) - random.shuffle(fulllist) - train_filelist = fulllist[:n_train] - val_filelist = fulllist[n_train : n_train + n_val] - test_filelist = fulllist[n_train + n_val : n_train + n_val + n_test] - filelist = train_filelist + val_filelist + test_filelist - elif config["general"]["corpus_type"] == "multi-unseen": - spk_list = list(set([x.parent for x in sourcepath.glob("*/*.wav")])) - train_filelist = [] - val_filelist = [] - test_filelist = [] - random.seed(0) - random.shuffle(spk_list) - for i, spk in enumerate(spk_list): - sourcespkpath = sourcepath / spk - if i < n_train: - train_filelist.extend(list(sourcespkpath.glob("*.wav"))) - elif i < n_train + n_val: - val_filelist.extend(list(sourcespkpath.glob("*.wav"))) - elif i < n_train + n_val + n_test: - test_filelist.extend(list(sourcespkpath.glob("*.wav"))) - filelist = train_filelist + val_filelist + test_filelist - else: - raise NotImplementedError( - "corpus_type specified in config.yaml should be {single, multi-seen, multi-unseen}" - ) - - with open(preprocessed_dir / "train.txt", "w", encoding="utf-8") as f: - for m in train_filelist: - f.write(str(m) + "\n") - with open(preprocessed_dir / "val.txt", "w", encoding="utf-8") as f: - for m in val_filelist: - f.write(str(m) + "\n") - with open(preprocessed_dir / "test.txt", "w", encoding="utf-8") as f: - for m in test_filelist: - f.write(str(m) + "\n") - - for wp in tqdm.tqdm(filelist): - - if config["general"]["corpus_type"] == "single": - basename = str(wp.stem) - else: - basename = str(wp.parent.name) + "-" + str(wp.stem) - - wav, _ = librosa.load(wp, sr=SR) - wavsegs = [] - - if config["general"]["aux_path"] != None: - auxpath = pathlib.Path(config["general"]["aux_path"]) - if config["general"]["corpus_type"] == "single": - wav_aux, _ = librosa.load(auxpath / wp.name, sr=SR) - else: - wav_aux, _ = librosa.load(auxpath / wp.parent.name / wp.name, sr=SR) - wavauxsegs = [] - - if config["general"]["aux_path"] == None: - wavsegs.append(wav) - else: - min_seq_len = min(len(wav), len(wav_aux)) - wav = wav[:min_seq_len] - wav_aux = wav_aux[:min_seq_len] - wavsegs.append(wav) - wavauxsegs.append(wav_aux) - - wavsegs = np.asarray(wavsegs).astype(np.float32) - if config["general"]["aux_path"] != None: - wavauxsegs = np.asarray(wavauxsegs).astype(np.float32) - else: - wavauxsegs = None - - d_preprocessed = {"wavs": wavsegs, "wavsaux": wavauxsegs} - - with open(preprocessed_dir / "{}.pickle".format(basename), "wb") as fw: - pickle.dump(d_preprocessed, fw) - - -if __name__ == "__main__": - args = get_arg() - - config = yaml.load(open(args.config_path, "r"), Loader=yaml.FullLoader) - for key in ["corpus_type", "source_path", "aux_path", "preprocessed_path"]: - if getattr(args, key) != None: - config["general"][key] = str(getattr(args, key)) - for key in ["n_train", "n_val", "n_test"]: - if getattr(args, key) != None: - config["preprocess"][key] = getattr(args, key) - - print("Performing preprocessing ...") - preprocess(config) - - if "dual" in config: - if config["dual"]["enable"]: - task_config = yaml.load( - open(config["dual"]["config_path"], "r"), Loader=yaml.FullLoader - ) - task_preprocessed_dir = ( - pathlib.Path(config["general"]["preprocessed_path"]).parent - / pathlib.Path(task_config["general"]["preprocessed_path"]).name - ) - task_config["general"]["preprocessed_path"] = task_preprocessed_dir - if args.source_path_task != None: - task_config["general"]["source_path"] = args.source_path_task - print("Performing preprocessing for multi-task learning ...") - preprocess(task_config) diff --git a/spaces/saifytechnologies/ai-text-to-video-generation-saify-technologies/README.md b/spaces/saifytechnologies/ai-text-to-video-generation-saify-technologies/README.md deleted file mode 100644 index e03af3f7a198494395de89e2fcbf3385566dca26..0000000000000000000000000000000000000000 --- a/spaces/saifytechnologies/ai-text-to-video-generation-saify-technologies/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: ModelScope Text To Video Synthesis -emoji: 🚀 -colorFrom: pink -colorTo: pink -sdk: gradio -sdk_version: 3.22.1 -app_file: app.py -pinned: false -duplicated_from: damo-vilab/modelscope-text-to-video-synthesis ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/saifytechnologies/ai-text-to-video-generation-saify-technologies/style.css b/spaces/saifytechnologies/ai-text-to-video-generation-saify-technologies/style.css deleted file mode 100644 index 2f399e973fe275a7299ae85c6a85bd5d35eb64cb..0000000000000000000000000000000000000000 --- a/spaces/saifytechnologies/ai-text-to-video-generation-saify-technologies/style.css +++ /dev/null @@ -1,191 +0,0 @@ -/* -This CSS file is copied from here: -https://huggingface.co/spaces/stabilityai/stable-diffusion/blob/2794a3c3ba66115c307075098e713f572b08bf80/app.py -*/ - -h1 { - text-align: center; -} - -.gradio-container { - font-family: 'IBM Plex Sans', sans-serif; -} - -.gr-button { - color: white; - border-color: black; - background: black; -} - -input[type='range'] { - accent-color: black; -} - -.dark input[type='range'] { - accent-color: #dfdfdf; -} - -.container { - max-width: 730px; - margin: auto; - padding-top: 1.5rem; -} - -#gallery { - min-height: 22rem; - margin-bottom: 15px; - margin-left: auto; - margin-right: auto; - border-bottom-right-radius: .5rem !important; - border-bottom-left-radius: .5rem !important; -} - -#gallery>div>.h-full { - min-height: 20rem; -} - -.details:hover { - text-decoration: underline; -} - -.gr-button { - white-space: nowrap; -} - -.gr-button:focus { - border-color: rgb(147 197 253 / var(--tw-border-opacity)); - outline: none; - box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); - --tw-border-opacity: 1; - --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); - --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color); - --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity)); - --tw-ring-opacity: .5; -} - -#advanced-btn { - font-size: .7rem !important; - line-height: 19px; - margin-top: 12px; - margin-bottom: 12px; - padding: 2px 8px; - border-radius: 14px !important; -} - -#advanced-options { - display: none; - margin-bottom: 20px; -} - -.footer { - margin-bottom: 45px; - margin-top: 35px; - text-align: center; - border-bottom: 1px solid #e5e5e5; -} - -.footer>p { - font-size: .8rem; - display: inline-block; - padding: 0 10px; - transform: translateY(10px); - background: white; -} - -.dark .footer { - border-color: #303030; -} - -.dark .footer>p { - background: #0b0f19; -} - -.acknowledgments h4 { - margin: 1.25em 0 .25em 0; - font-weight: bold; - font-size: 115%; -} - -.animate-spin { - animation: spin 1s linear infinite; -} - -@keyframes spin { - from { - transform: rotate(0deg); - } - - to { - transform: rotate(360deg); - } -} - -#share-btn-container { - display: flex; - padding-left: 0.5rem !important; - padding-right: 0.5rem !important; - background-color: #000000; - justify-content: center; - align-items: center; - border-radius: 9999px !important; - width: 13rem; - margin-top: 10px; - margin-left: auto; -} - -#share-btn { - all: initial; - color: #ffffff; - font-weight: 600; - cursor: pointer; - font-family: 'IBM Plex Sans', sans-serif; - margin-left: 0.5rem !important; - padding-top: 0.25rem !important; - padding-bottom: 0.25rem !important; - right: 0; -} - -#share-btn * { - all: unset; -} - -#share-btn-container div:nth-child(-n+2) { - width: auto !important; - min-height: 0px !important; -} - -#share-btn-container .wrap { - display: none !important; -} - -.gr-form { - flex: 1 1 50%; - border-top-right-radius: 0; - border-bottom-right-radius: 0; -} - -#prompt-container { - gap: 0; -} - -#prompt-text-input, -#negative-prompt-text-input { - padding: .45rem 0.625rem -} - -#component-16 { - border-top-width: 1px !important; - margin-top: 1em -} - -.image_duplication { - position: absolute; - width: 100px; - left: 50px -} - -#component-0 { - max-width: 730px; - margin: auto; - padding-top: 1.5rem; -} diff --git a/spaces/samcaicn/bingai/src/lib/bots/bing/index.ts b/spaces/samcaicn/bingai/src/lib/bots/bing/index.ts deleted file mode 100644 index 2deca68bbf16f10df8aa4e22c167de4416567145..0000000000000000000000000000000000000000 --- a/spaces/samcaicn/bingai/src/lib/bots/bing/index.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { fetch, WebSocket, debug } from '@/lib/isomorphic' -import WebSocketAsPromised from 'websocket-as-promised' -import { - SendMessageParams, - BingConversationStyle, - ConversationResponse, - ChatResponseMessage, - ConversationInfo, - InvocationEventType, - ChatError, - ErrorCode, - ChatUpdateCompleteResponse -} from './types' - -import { convertMessageToMarkdown, websocketUtils, streamAsyncIterable } from './utils' -import { createChunkDecoder } from '@/lib/utils' - -type Params = SendMessageParams<{ bingConversationStyle: BingConversationStyle, useProxy: boolean }> - -const OPTIONS_SETS = [ - 'nlu_direct_response_filter', - 'deepleo', - 'disable_emoji_spoken_text', - 'responsible_ai_policy_235', - 'enablemm', - 'iycapbing', - 'iyxapbing', - 'objopinion', - 'rweasgv2', - 'dagslnv1', - 'dv3sugg', - 'autosave', - 'iyoloxap', - 'iyoloneutral', - 'clgalileo', - 'gencontentv3', -] - -export class BingWebBot { - protected conversationContext?: ConversationInfo - protected cookie: string - protected ua: string - protected endpoint = '' - private lastText = '' - private asyncTasks: Array> = [] - - constructor(opts: { - cookie: string - ua: string - bingConversationStyle?: BingConversationStyle - conversationContext?: ConversationInfo - }) { - const { cookie, ua, conversationContext } = opts - this.cookie = cookie?.includes(';') ? cookie : `_EDGE_V=1; _U=${cookie}` - this.ua = ua - this.conversationContext = conversationContext - } - - static buildChatRequest(conversation: ConversationInfo) { - const optionsSets = OPTIONS_SETS - if (conversation.conversationStyle === BingConversationStyle.Precise) { - optionsSets.push('h3precise') - } else if (conversation.conversationStyle === BingConversationStyle.Creative) { - optionsSets.push('h3imaginative') - } - return { - arguments: [ - { - source: 'cib', - optionsSets, - allowedMessageTypes: [ - 'Chat', - 'InternalSearchQuery', - 'Disengaged', - 'InternalLoaderMessage', - 'SemanticSerp', - 'GenerateContentQuery', - 'SearchQuery', - ], - sliceIds: [ - 'winmuid1tf', - 'anssupfor_c', - 'imgchatgptv2', - 'tts2cf', - 'contansperf', - 'mlchatpc8500w', - 'mlchatpc2', - 'ctrlworkpay', - 'winshortmsgtf', - 'cibctrl', - 'sydtransctrl', - 'sydconfigoptc', - '0705trt4', - '517opinion', - '628ajcopus0', - '330uaugs0', - '529rwea', - '0626snptrcs0', - '424dagslnv1', - ], - isStartOfSession: conversation.invocationId === 0, - message: { - author: 'user', - inputMethod: 'Keyboard', - text: conversation.prompt, - messageType: 'Chat', - }, - conversationId: conversation.conversationId, - conversationSignature: conversation.conversationSignature, - participant: { id: conversation.clientId }, - }, - ], - invocationId: conversation.invocationId.toString(), - target: 'chat', - type: InvocationEventType.StreamInvocation, - } - } - - async createConversation(): Promise { - const headers = { - 'Accept-Encoding': 'gzip, deflate, br, zsdch', - 'User-Agent': this.ua, - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32', - cookie: this.cookie, - } - - let resp: ConversationResponse | undefined - try { - const response = await fetch(this.endpoint + '/api/create', { method: 'POST', headers, redirect: 'error', mode: 'cors', credentials: 'include' }) - if (response.status === 404) { - throw new ChatError('Not Found', ErrorCode.NOTFOUND_ERROR) - } - resp = await response.json() as ConversationResponse - } catch (err) { - console.error('create conversation error', err) - } - - if (!resp?.result) { - throw new ChatError('Invalid response', ErrorCode.UNKOWN_ERROR) - } - - const { value, message } = resp.result || {} - if (value !== 'Success') { - const errorMsg = `${value}: ${message}` - if (value === 'UnauthorizedRequest') { - throw new ChatError(errorMsg, ErrorCode.BING_UNAUTHORIZED) - } - if (value === 'Forbidden') { - throw new ChatError(errorMsg, ErrorCode.BING_FORBIDDEN) - } - throw new ChatError(errorMsg, ErrorCode.UNKOWN_ERROR) - } - return resp - } - - async sendMessage(params: Params) { - try { - if (!this.conversationContext) { - const conversation = await this.createConversation() - this.conversationContext = { - conversationId: conversation.conversationId, - conversationSignature: conversation.conversationSignature, - clientId: conversation.clientId, - invocationId: 0, - conversationStyle: params.options.bingConversationStyle, - prompt: '' - } - } - Object.assign(this.conversationContext, { prompt: params.prompt }) - - if (params.options.useProxy) { - return this.useProxy(params) - } - return this.useWs(params) - } catch (error) { - params.onEvent({ - type: 'ERROR', - error: error instanceof ChatError ? error : new ChatError('Catch Error', ErrorCode.UNKOWN_ERROR), - }) - } - } - - private async useProxy(params: Params) { - const abortController = new AbortController() - const response = await fetch(this.endpoint + '/api/sydney', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - signal: abortController.signal, - body: JSON.stringify(this.conversationContext!) - }) - if (response.status !== 200) { - params.onEvent({ - type: 'ERROR', - error: new ChatError( - 'Unknown error', - ErrorCode.UNKOWN_ERROR, - ), - }) - } - params.signal?.addEventListener('abort', () => { - abortController.abort() - }) - - const textDecoder = createChunkDecoder() - for await (const chunk of streamAsyncIterable(response.body!)) { - this.parseEvents(params, websocketUtils.unpackMessage(textDecoder(chunk))) - } - } - - async sendWs() { - const wsConfig: ConstructorParameters[1] = { - packMessage: websocketUtils.packMessage, - unpackMessage: websocketUtils.unpackMessage, - createWebSocket: (url) => new WebSocket(url, { - headers: { - 'accept-language': 'zh-CN,zh;q=0.9', - 'cache-control': 'no-cache', - 'User-Agent': this.ua, - pragma: 'no-cache', - cookie: this.cookie, - } - }) - } - const wsp = new WebSocketAsPromised('wss://sydney.bing.com/sydney/ChatHub', wsConfig) - - wsp.open().then(() => { - wsp.sendPacked({ protocol: 'json', version: 1 }) - wsp.sendPacked({ type: 6 }) - wsp.sendPacked(BingWebBot.buildChatRequest(this.conversationContext!)) - }) - - return wsp - } - - private async useWs(params: Params) { - const wsp = await this.sendWs() - - wsp.onUnpackedMessage.addListener((events) => { - if (Math.ceil(Date.now() / 1000) % 3 === 0) { - wsp.sendPacked({ type: 6 }) - } - this.parseEvents(params, events) - }) - - wsp.onClose.addListener(() => { - params.onEvent({ type: 'DONE' }) - wsp.removeAllListeners() - }) - - params.signal?.addEventListener('abort', () => { - wsp.removeAllListeners() - wsp.close() - }) - } - - private async createImage(prompt: string, id: string) { - try { - const headers = { - 'Accept-Encoding': 'gzip, deflate, br, zsdch', - 'User-Agent': this.ua, - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32', - cookie: this.cookie, - } - const query = new URLSearchParams({ - prompt, - id - }) - const response = await fetch(this.endpoint + '/api/image?' + query.toString(), - { - method: 'POST', - headers, - mode: 'cors', - credentials: 'include' - }) - .then(res => res.text()) - if (response) { - this.lastText += '\n' + response - } - } catch (err) { - console.error('Create Image Error', err) - } - } - - private async generateContent(message: ChatResponseMessage) { - if (message.contentType === 'IMAGE') { - this.asyncTasks.push(this.createImage(message.text, message.messageId)) - } - } - - private async parseEvents(params: Params, events: any) { - const conversation = this.conversationContext! - - events?.forEach(async (event: ChatUpdateCompleteResponse) => { - debug('bing event', event) - if (event.type === 3) { - await Promise.all(this.asyncTasks) - this.asyncTasks = [] - params.onEvent({ type: 'UPDATE_ANSWER', data: { text: this.lastText } }) - params.onEvent({ type: 'DONE' }) - conversation.invocationId = parseInt(event.invocationId, 10) + 1 - } else if (event.type === 1) { - const messages = event.arguments[0].messages - if (messages) { - const text = convertMessageToMarkdown(messages[0]) - this.lastText = text - params.onEvent({ type: 'UPDATE_ANSWER', data: { text, throttling: event.arguments[0].throttling } }) - } - } else if (event.type === 2) { - const messages = event.item.messages as ChatResponseMessage[] | undefined - if (!messages) { - params.onEvent({ - type: 'ERROR', - error: new ChatError( - event.item.result.error || 'Unknown error', - event.item.result.value !== 'CaptchaChallenge' ? ErrorCode.UNKOWN_ERROR - : this.conversationContext?.conversationId?.includes('BingProdUnAuthenticatedUsers') ? ErrorCode.BING_UNAUTHORIZED - : ErrorCode.BING_CAPTCHA , - ), - }) - return - } - const limited = messages.some((message) => - message.contentOrigin === 'TurnLimiter' - || message.messageType === 'Disengaged' - ) - if (limited) { - params.onEvent({ - type: 'ERROR', - error: new ChatError( - 'Sorry, you have reached chat limit in this conversation.', - ErrorCode.CONVERSATION_LIMIT, - ), - }) - return - } - - const lastMessage = event.item.messages.at(-1) as ChatResponseMessage - if (lastMessage?.messageType) { - return this.generateContent(lastMessage) - } - - if (lastMessage) { - const text = convertMessageToMarkdown(lastMessage) - this.lastText = text - params.onEvent({ - type: 'UPDATE_ANSWER', - data: { text, throttling: event.item.throttling, suggestedResponses: lastMessage.suggestedResponses, sourceAttributions: lastMessage.sourceAttributions }, - }) - } - } - }) - } - - resetConversation() { - this.conversationContext = undefined - } -} diff --git a/spaces/samcaicn/bingai/tailwind.config.js b/spaces/samcaicn/bingai/tailwind.config.js deleted file mode 100644 index 03da3c3c45be6983b9f5ffa6df5f1fd0870e9636..0000000000000000000000000000000000000000 --- a/spaces/samcaicn/bingai/tailwind.config.js +++ /dev/null @@ -1,48 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -module.exports = { - content: [ - './src/pages/**/*.{js,ts,jsx,tsx,mdx}', - './src/components/**/*.{js,ts,jsx,tsx,mdx}', - './src/app/**/*.{js,ts,jsx,tsx,mdx}', - './src/ui/**/*.{js,ts,jsx,tsx,mdx}', - ], - "darkMode": "class", - theme: { - extend: { - colors: { - 'primary-blue': 'rgb(var(--color-primary-blue) / )', - secondary: 'rgb(var(--color-secondary) / )', - 'primary-background': 'rgb(var(--primary-background) / )', - 'primary-text': 'rgb(var(--primary-text) / )', - 'secondary-text': 'rgb(var(--secondary-text) / )', - 'light-text': 'rgb(var(--light-text) / )', - 'primary-border': 'rgb(var(--primary-border) / )', - }, - keyframes: { - slideDownAndFade: { - from: { opacity: 0, transform: 'translateY(-2px)' }, - to: { opacity: 1, transform: 'translateY(0)' }, - }, - slideLeftAndFade: { - from: { opacity: 0, transform: 'translateX(2px)' }, - to: { opacity: 1, transform: 'translateX(0)' }, - }, - slideUpAndFade: { - from: { opacity: 0, transform: 'translateY(2px)' }, - to: { opacity: 1, transform: 'translateY(0)' }, - }, - slideRightAndFade: { - from: { opacity: 0, transform: 'translateX(2px)' }, - to: { opacity: 1, transform: 'translateX(0)' }, - }, - }, - animation: { - slideDownAndFade: 'slideDownAndFade 400ms cubic-bezier(0.16, 1, 0.3, 1)', - slideLeftAndFade: 'slideLeftAndFade 400ms cubic-bezier(0.16, 1, 0.3, 1)', - slideUpAndFade: 'slideUpAndFade 400ms cubic-bezier(0.16, 1, 0.3, 1)', - slideRightAndFade: 'slideRightAndFade 400ms cubic-bezier(0.16, 1, 0.3, 1)', - }, - }, - }, - plugins: [require('@headlessui/tailwindcss'), require('tailwind-scrollbar')], -} diff --git a/spaces/sanchit-gandhi/whisper-jax/run.sh b/spaces/sanchit-gandhi/whisper-jax/run.sh deleted file mode 100644 index ad921267c3904625cd8e2cfff2370e849c3d3f7f..0000000000000000000000000000000000000000 --- a/spaces/sanchit-gandhi/whisper-jax/run.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -# Careful: can't create tmp files from this script -cat nginx.conf | sed "s|API_URL|${API_URL}|g" > /etc/nginx/sites-available/default -service nginx start -sleep infinity diff --git a/spaces/sanjayw/starchat-playground/dialogues.py b/spaces/sanjayw/starchat-playground/dialogues.py deleted file mode 100644 index 634c4a1d4f515f21b919cbf5d45440fb587d748f..0000000000000000000000000000000000000000 --- a/spaces/sanjayw/starchat-playground/dialogues.py +++ /dev/null @@ -1,241 +0,0 @@ -# coding=utf-8 -# Copyright 2023 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -from dataclasses import asdict, dataclass -from pathlib import Path -from typing import Any, Dict, List, Optional, Type, TypeVar, Union - -from huggingface_hub import ModelHubMixin, hf_hub_download - -# Generic variable that is either ModelHubMixin or a subclass thereof -T = TypeVar("T", bound="ModelHubMixin") - -TEMPLATE_FILENAME = "dialogue_template.json" -IGNORE_INDEX = -100 - - -@dataclass -class DialogueTemplate(ModelHubMixin): - """Converts all turns of a dialogue between a user and assistant to a standardized format. - - Adapted from OpenAI's ChatML (https://github.com/openai/openai-python/blob/main/chatml.md) and Vicuna (https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py) - """ - - system: str - messages: List[Dict[str, str]] = None - system_token: str = "<|system|>" - user_token: str = "<|user|>" - assistant_token: str = "<|assistant|>" - end_token: str = "<|end|>" - - def get_training_prompt(self) -> str: - prompt = self.system_token + "\n" + self.system + self.end_token + "\n" - if self.messages is None: - raise ValueError("Dialogue template must have at least one message.") - for message in self.messages: - if message["role"] == "user": - prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n" - else: - prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n" - return prompt - - def get_inference_prompt(self) -> str: - prompt = self.system_token + "\n" + self.system + self.end_token + "\n" - if self.messages is None: - raise ValueError("Dialogue template must have at least one message.") - for message in self.messages: - if message["role"] == "user": - prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n" - else: - prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n" - prompt += self.assistant_token - return prompt - - def get_dialogue(self): - """Helper function to format the messages as an easy-to-read dialogue.""" - prompt = "" - if self.messages is None: - raise ValueError("Dialogue template must have at least one message.") - for message in self.messages: - if message["role"] == "user": - prompt += "\n\nHuman: " + message["content"] - else: - prompt += "\n\nAssistant: " + message["content"] - return prompt - - def get_special_tokens(self) -> List[str]: - return [self.system_token, self.user_token, self.assistant_token, self.end_token] - - def copy(self): - return DialogueTemplate( - system=self.system, - messages=self.messages, - system_token=self.system_token, - user_token=self.user_token, - assistant_token=self.assistant_token, - end_token=self.end_token, - ) - - def to_dict(self) -> Dict[str, Any]: - return {k: v for k, v in asdict(self).items()} - - @classmethod - def from_dict(cls, data): - return DialogueTemplate( - system=data["system"] if "system" in data else "", - messages=data["messages"] if "messages" in data else None, - system_token=data["system_token"] if "system_token" in data else "<|system|>", - user_token=data["user_token"] if "user_token" in data else "<|user|>", - assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>", - end_token=data["end_token"] if "end_token" in data else "<|end|>", - ) - - def _save_pretrained(self, save_directory: Union[str, Path]) -> None: - save_directory = Path(save_directory) - save_directory.mkdir(exist_ok=True) - with open(save_directory / "dialogue_template.json", "w") as f: - json.dump(self.to_dict(), f, indent=2) - - @classmethod - def _from_pretrained( - cls: Type[T], - *, - model_id: str, - revision: Optional[str], - cache_dir: Optional[Union[str, Path]], - force_download: bool, - proxies: Optional[Dict], - resume_download: bool, - local_files_only: bool, - token: Optional[Union[str, bool]], - **model_kwargs, - ) -> T: - """Loads the dialogue template from a local directory or the Huggingface Hub. - - Args: - model_id (`str`): - ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`). - revision (`str`, *optional*): - Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the - latest commit on `main` branch. - force_download (`bool`, *optional*, defaults to `False`): - Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding - the existing cache. - resume_download (`bool`, *optional*, defaults to `False`): - Whether to delete incompletely received files. Will attempt to resume the download if such a file exists. - proxies (`Dict[str, str]`, *optional*): - A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128', - 'http://hostname': 'foo.bar:4012'}`). - token (`str` or `bool`, *optional*): - The token to use as HTTP bearer authorization for remote files. By default, it will use the token - cached when running `huggingface-cli login`. - cache_dir (`str`, `Path`, *optional*): - Path to the folder where cached files are stored. - local_files_only (`bool`, *optional*, defaults to `False`): - If `True`, avoid downloading the file and return the path to the local cached file if it exists. - model_kwargs: - Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method. - """ - if os.path.isdir(model_id): # Can either be a local directory - print("Loading dialogue template from local directory") - template_file = os.path.join(model_id, TEMPLATE_FILENAME) - else: # Or a template on the Hub - template_file = hf_hub_download( # Download from the hub, passing same input args - repo_id=model_id, - filename=TEMPLATE_FILENAME, - revision=revision, - cache_dir=cache_dir, - force_download=force_download, - proxies=proxies, - resume_download=resume_download, - token=token, - local_files_only=local_files_only, - ) - - # Load template - with open(template_file, "r") as f: - data = json.load(f) - return cls.from_dict(data=data) - - -# A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt -default_template = DialogueTemplate( - system="Below is a dialogue between a human user and an AI assistant. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.", -) - -# OpenAI and OpenAssistant train on few to no system messages. -# TODO: consider defining this as the `default` template -no_system_template = DialogueTemplate( - system="", -) - -alpaca_template = DialogueTemplate( - system="Below is an instruction that describes a task. Write a response that appropriately completes the request.", - user_token="### Instruction:", - assistant_token="### Response:", -) - -SUPPORTED_DIALOGUE_TEMPLATES = { - "default": default_template, - "no_system": no_system_template, - "alpaca": alpaca_template, -} - - -def get_dialogue_template(template: str) -> DialogueTemplate: - if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys(): - raise ValueError(f"Template {template} is not supported!") - return SUPPORTED_DIALOGUE_TEMPLATES[template].copy() - - -def prepare_dialogue(example, dialogue_template, is_train=True): - """Format example to single- or multi-turn dialogue.""" - # TODO: make this simpler by just ensuring every dataset has a messages column - if "messages" in example.keys() and example["messages"] is not None: - dialogue_template.messages = example["messages"] - elif all(k in example.keys() for k in ("prompt", "completion")): - # Construct single-turn dialogue from prompt and completion - dialogue_template.messages = [ - {"role": "user", "content": example["prompt"]}, - {"role": "assistant", "content": example["completion"]}, - ] - elif "prompt" in example.keys(): - # Construct single-turn dialogue from prompt (inference only) - dialogue_template.messages = [ - {"role": "user", "content": example["prompt"]}, - ] - else: - raise ValueError( - f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}" - ) - if is_train: - example["text"] = dialogue_template.get_training_prompt() - else: - example["text"] = dialogue_template.get_inference_prompt() - return example - - -def mask_user_labels(tokenizer, dialogue_template, labels): - """Masks the user turns of a dialogue from the loss""" - user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token) - assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token) - for idx, label_id in enumerate(labels): - if label_id == user_token_id: - current_idx = idx - while labels[current_idx] != assistant_token_id and current_idx < len(labels): - labels[current_idx] = IGNORE_INDEX - current_idx += 1 diff --git a/spaces/sarinam/speaker-anonymization/IMSToucan/Layers/LengthRegulator.py b/spaces/sarinam/speaker-anonymization/IMSToucan/Layers/LengthRegulator.py deleted file mode 100644 index f9ae4e06b7da19152fe1d9a14fc4098a64c8f39e..0000000000000000000000000000000000000000 --- a/spaces/sarinam/speaker-anonymization/IMSToucan/Layers/LengthRegulator.py +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright 2019 Tomoki Hayashi -# MIT License (https://opensource.org/licenses/MIT) -# Adapted by Florian Lux 2021 - -from abc import ABC - -import torch - -from ..Utility.utils import pad_list - - -class LengthRegulator(torch.nn.Module, ABC): - """ - Length regulator module for feed-forward Transformer. - - This is a module of length regulator described in - `FastSpeech: Fast, Robust and Controllable Text to Speech`_. - The length regulator expands char or - phoneme-level embedding features to frame-level by repeating each - feature based on the corresponding predicted durations. - - .. _`FastSpeech: Fast, Robust and Controllable Text to Speech`: - https://arxiv.org/pdf/1905.09263.pdf - - """ - - def __init__(self, pad_value=0.0): - """ - Initialize length regulator module. - - Args: - pad_value (float, optional): Value used for padding. - """ - super(LengthRegulator, self).__init__() - self.pad_value = pad_value - - def forward(self, xs, ds, alpha=1.0): - """ - Calculate forward propagation. - - Args: - xs (Tensor): Batch of sequences of char or phoneme embeddings (B, Tmax, D). - ds (LongTensor): Batch of durations of each frame (B, T). - alpha (float, optional): Alpha value to control speed of speech. - - Returns: - Tensor: replicated input tensor based on durations (B, T*, D). - """ - if alpha != 1.0: - assert alpha > 0 - ds = torch.round(ds.float() * alpha).long() - - if ds.sum() == 0: - ds[ds.sum(dim=1).eq(0)] = 1 - - return pad_list([self._repeat_one_sequence(x, d) for x, d in zip(xs, ds)], self.pad_value) - - def _repeat_one_sequence(self, x, d): - """ - Repeat each frame according to duration - """ - return torch.repeat_interleave(x, d, dim=0) diff --git a/spaces/sccstandardteam/ChuanhuChatGPT/chatgpt - windows.bat b/spaces/sccstandardteam/ChuanhuChatGPT/chatgpt - windows.bat deleted file mode 100644 index 0b78fdc3a559abd692e3a9e9af5e482124d13a99..0000000000000000000000000000000000000000 --- a/spaces/sccstandardteam/ChuanhuChatGPT/chatgpt - windows.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -echo Opening ChuanhuChatGPT... - -REM Open powershell via bat -start powershell.exe -NoExit -Command "python ./ChuanhuChatbot.py" - -REM The web page can be accessed with delayed start http://127.0.0.1:7860/ -ping -n 5 127.0.0.1>nul - -REM access chargpt via your default browser -start "" "http://127.0.0.1:7860/" - - -echo Finished opening ChuanhuChatGPT (http://127.0.0.1:7860/). \ No newline at end of file diff --git a/spaces/scedlatioru/img-to-music/Program Eliberari Buletine Sectia 9 Politie.md b/spaces/scedlatioru/img-to-music/Program Eliberari Buletine Sectia 9 Politie.md deleted file mode 100644 index 968ba36ba9d23b99ed4c2be0083bfc138f36cb49..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/Program Eliberari Buletine Sectia 9 Politie.md +++ /dev/null @@ -1,96 +0,0 @@ -## program eliberari buletine sectia 9 politie - - - - - - - - - -**CLICK HERE ---> [https://urlca.com/2txvQ9](https://urlca.com/2txvQ9)** - - - - - - - - - - - - - -# Programul de eliberare a buletinelor la Secția 9 Poliție din București - - - -Dacă locuiți în sectorul 2 al Bucureștiului și aveți nevoie să vă reînnoiți buletinul sau să solicitați unul nou, trebuie să vă adresați Secției 9 Poliție, care se ocupă de evidența persoanelor și actele de identitate. Secția 9 Poliție se află pe Șoseaua Pantelimon nr. 290 și are următorul program de lucru: - - - -- Luni: 8:00 - 16:00 - -- Marti: 8:00 - 16:00 - -- Miercuri: 8:00 - 16:00 - -- Joi: 8:00 - 16:00 - -- Vineri: 8:00 - 16:00 - -- Sambata: Închis - -- Duminica: Închis - - - -Pentru a vă elibera buletinul, trebuie să vă prezentați la ghișeul Secției 9 Poliție cu următoarele documente: - - - -1. Cererea tip pentru eliberarea actului de identitate; - -2. Actul de identitate expirat sau deteriorat; - -3. Actul de naștere în original și copie; - -4. Actul de căsătorie în original și copie, dacă este cazul; - -5. Dovada adresei de domiciliu (contract de închiriere, factură la utilități etc.); - -6. 2 fotografii tip buletin; - -7. Taxa de eliberare a actului de identitate. - - - -Pentru mai multe informații, puteți suna la numărul de telefon **021 255 2433** sau puteți accesa pagina de internet [https://b.politiaromana.ro/ro/structura/politia-sectorului-2/sectia-9-politie](https://b.politiaromana.ro/ro/structura/politia-sectorului-2/sectia-9-politie), unde puteți găsi și alte servicii oferite de Secția 9 Poliție, cum ar fi obținerea certificatului de cazier judiciar sau poliția de proximitate. - - - -Secția 9 Poliție este una dintre cele 22 de secții de poliție din București, care asigură ordinea și siguranța publică în sectorul 2 al capitalei. Secția 9 Poliție are în subordine patru posturi de poliție și un birou de poliție comunitară. Secția 9 Poliție are competență pe o suprafață de 31,6 km2 și o populație de aproximativ 350.000 de locuitori. - - - -Secția 9 Poliție are ca misiune prevenirea și combaterea infracțiunilor, protejarea drepturilor și libertăților cetățenilor, menținerea ordinii și liniștii publice, precum și asigurarea unui climat de siguranță pentru cetățeni și bunuri. Secția 9 Poliție desfășoară activități de investigații criminale, ordine publică, criminalistică, evidență operativă, poliție rutieră, poliție de proximitate și relații cu publicul. - - - -Secția 9 Poliție colaborează cu alte structuri ale Poliției Române, precum și cu alte instituții publice sau private, pentru a asigura un serviciu de calitate pentru cetățeni. Secția 9 Poliție își desfășoară activitatea în conformitate cu legislația în vigoare, respectând principiile legalității, imparțialității, profesionalismului și transparenței. - - - -Secția 9 Poliție își propune să îmbunătățească permanent calitatea serviciilor oferite cetățenilor și să răspundă eficient la nevoile și așteptările acestora. Secția 9 Poliție încurajează comunicarea și colaborarea cu cetățenii, prin intermediul unor canale diverse, cum ar fi telefonul, e-mailul, pagina de internet sau audiențele publice. Secția 9 Poliție primește și soluționează sesizările, reclamațiile sau sugestiile cetățenilor, în scopul înlăturării cauzelor care generează nemulțumiri sau nereguli. - - - -Secția 9 Poliție este deschisă dialogului și cooperării cu reprezentanții societății civile, mass-media, mediului de afaceri sau altor categorii de parteneri sociali. Secția 9 Poliție participă la acțiuni de prevenire și educare a populației în domeniul siguranței publice, precum și la campanii de informare și conștientizare a cetățenilor cu privire la riscurile și amenințările la adresa securității lor. Secția 9 Poliție sprijină inițiativele și proiectele care contribuie la dezvoltarea comunității și la creșterea gradului de siguranță al cetățenilor. - - dfd1c89656 - - - - - diff --git a/spaces/scedlatioru/img-to-music/The Girl Next Door Hindi Dubbed Movie.md b/spaces/scedlatioru/img-to-music/The Girl Next Door Hindi Dubbed Movie.md deleted file mode 100644 index 49d903db3a11ce53cb8b82064506ee3972c62212..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/The Girl Next Door Hindi Dubbed Movie.md +++ /dev/null @@ -1,62 +0,0 @@ -## the girl next door hindi dubbed movie - - - - - - ![The Girl Next Door Hindi Dubbed Movie](https://timesofindia.indiatimes.com/photo/91790778.cms) - - - - - -**Download >> [https://dropnobece.blogspot.com/?download=2tyq3J](https://dropnobece.blogspot.com/?download=2tyq3J)** - - - - - - - - - - - - - -# The Girl Next Door Hindi Dubbed Movie: A Romantic Comedy with a Twist - - - -The Girl Next Door is a 2004 American romantic comedy film directed by Luke Greenfield and starring Emile Hirsch, Elisha Cuthbert, Timothy Olyphant and James Remar. The film is loosely based on the 1987 novel of the same name by Jack Ketchum, which was inspired by the true story of the torture and murder of Sylvia Likens by Gertrude Baniszewski in 1965. - - - -The film follows Matthew Kidman (Hirsch), a high school senior who falls in love with his new neighbor Danielle (Cuthbert), who turns out to be a former porn star. Matthew's life takes a wild turn as he gets involved in Danielle's past and tries to help her escape from her abusive ex-boyfriend Kelly (Olyphant), who wants to force her back into the adult industry. - - - -The Girl Next Door Hindi Dubbed Movie is available for online streaming on various platforms, such as YouTube, Archive.org and IMDb. The film has been dubbed in Hindi by professional voice actors who have given a new flavor to the dialogues and jokes. The film has been praised for its humor, romance, soundtrack and performances, especially by Hirsch and Cuthbert, who have a great chemistry on screen. - - - -If you are looking for a fun and entertaining movie that will make you laugh and cry, then you should watch The Girl Next Door Hindi Dubbed Movie. It is a film that will appeal to both young and old audiences, as it has a mix of comedy, drama, action and romance. It is also a film that will make you think about the consequences of your choices and the importance of following your dreams. - - - -The Girl Next Door Hindi Dubbed Movie is not just a typical teen comedy, but also a film that explores the themes of morality, identity, friendship and love. The film shows how Matthew grows as a person and learns to stand up for what he believes in, even if it means going against the norms of society. The film also shows how Danielle struggles to leave behind her past and start a new life with Matthew, who accepts her for who she is. - - - -The film has received positive reviews from critics and audiences alike, who have praised its witty script, charming characters, heartfelt moments and unexpected twists. The film has a 47% rating on Rotten Tomatoes, based on 117 reviews, with an average score of 5.4/10[^3^]. The site's consensus reads: \"The movie borrows heavily from Risky Business, though Hirsch and Cuthbert are appealing leads.\" The film also has a 6.7/10 rating on IMDb, based on 229,000 votes[^1^] [^2^]. The film has been described as \"a creative delight with surprising insight and honesty\"[^3^], \"a smart film that resembled a John Hughes film of the early 1980's\"[^2^], and \"a fun and entertaining movie that will make you laugh and cry\"[^1^]. - - - -The Girl Next Door Hindi Dubbed Movie is a film that you should not miss if you are looking for a romantic comedy with a twist. It is a film that will make you root for the underdog, cheer for the lovers, and laugh at the absurdities of life. It is a film that will show you that sometimes, the juice is worth the squeeze. - - dfd1c89656 - - - - - diff --git a/spaces/sdpkjc/ChatPaper/optimizeOpenAI.py b/spaces/sdpkjc/ChatPaper/optimizeOpenAI.py deleted file mode 100644 index 754b50c6d911f9ba889800321e631591cf7daef8..0000000000000000000000000000000000000000 --- a/spaces/sdpkjc/ChatPaper/optimizeOpenAI.py +++ /dev/null @@ -1,226 +0,0 @@ -""" -A simple wrapper for the official ChatGPT API -""" -import json -import os -import threading -import time -import requests -import tiktoken -from typing import Generator -from queue import PriorityQueue as PQ -import json -import os -import time -ENCODER = tiktoken.get_encoding("gpt2") -class chatPaper: - """ - Official ChatGPT API - """ - def __init__( - self, - api_keys: list, - proxy = None, - api_proxy = None, - max_tokens: int = 4000, - temperature: float = 0.5, - top_p: float = 1.0, - model_name: str = "gpt-3.5-turbo", - reply_count: int = 1, - system_prompt = "You are ChatPaper, A paper reading bot", - lastAPICallTime = time.time()-100, - apiTimeInterval = 20, - ) -> None: - self.model_name = model_name - self.system_prompt = system_prompt - self.apiTimeInterval = apiTimeInterval - self.session = requests.Session() - self.api_keys = PQ() - for key in api_keys: - self.api_keys.put((lastAPICallTime,key)) - self.proxy = proxy - if self.proxy: - proxies = { - "http": self.proxy, - "https": self.proxy, - } - self.session.proxies = proxies - self.max_tokens = max_tokens - self.temperature = temperature - self.top_p = top_p - self.reply_count = reply_count - self.decrease_step = 250 - self.conversation = {} - if self.token_str(self.system_prompt) > self.max_tokens: - raise Exception("System prompt is too long") - self.lock = threading.Lock() - - def get_api_key(self): - with self.lock: - apiKey = self.api_keys.get() - delay = self._calculate_delay(apiKey) - time.sleep(delay) - self.api_keys.put((time.time(), apiKey[1])) - return apiKey[1] - - def _calculate_delay(self, apiKey): - elapsed_time = time.time() - apiKey[0] - if elapsed_time < self.apiTimeInterval: - return self.apiTimeInterval - elapsed_time - else: - return 0 - - def add_to_conversation(self, message: str, role: str, convo_id: str = "default"): - if(convo_id not in self.conversation): - self.reset(convo_id) - self.conversation[convo_id].append({"role": role, "content": message}) - - def __truncate_conversation(self, convo_id: str = "default"): - """ - Truncate the conversation - """ - last_dialog = self.conversation[convo_id][-1] - query = str(last_dialog['content']) - if(len(ENCODER.encode(str(query)))>self.max_tokens): - query = query[:int(1.5*self.max_tokens)] - while(len(ENCODER.encode(str(query)))>self.max_tokens): - query = query[:self.decrease_step] - self.conversation[convo_id] = self.conversation[convo_id][:-1] - full_conversation = "\n".join([str(x["content"]) for x in self.conversation[convo_id]],) - if len(ENCODER.encode(full_conversation)) > self.max_tokens: - self.conversation_summary(convo_id=convo_id) - full_conversation = "" - for x in self.conversation[convo_id]: - full_conversation = str(x["content"]) + "\n" + full_conversation - while True: - if (len(ENCODER.encode(full_conversation+query)) > self.max_tokens): - query = query[:self.decrease_step] - else: - break - last_dialog['content'] = str(query) - self.conversation[convo_id].append(last_dialog) - - def ask_stream( - self, - prompt: str, - role: str = "user", - convo_id: str = "default", - **kwargs, - ) -> Generator: - if convo_id not in self.conversation: - self.reset(convo_id=convo_id) - self.add_to_conversation(prompt, "user", convo_id=convo_id) - self.__truncate_conversation(convo_id=convo_id) - apiKey = self.get_api_key() - response = self.session.post( - "https://api.openai.com/v1/chat/completions", - headers={"Authorization": f"Bearer {kwargs.get('api_key', apiKey)}"}, - json={ - "model": self.model_name, - "messages": self.conversation[convo_id], - "stream": True, - # kwargs - "temperature": kwargs.get("temperature", self.temperature), - "top_p": kwargs.get("top_p", self.top_p), - "n": kwargs.get("n", self.reply_count), - "user": role, - }, - stream=True, - ) - if response.status_code != 200: - raise Exception( - f"Error: {response.status_code} {response.reason} {response.text}", - ) - for line in response.iter_lines(): - if not line: - continue - # Remove "data: " - line = line.decode("utf-8")[6:] - if line == "[DONE]": - break - resp: dict = json.loads(line) - choices = resp.get("choices") - if not choices: - continue - delta = choices[0].get("delta") - if not delta: - continue - if "content" in delta: - content = delta["content"] - yield content - def ask(self, prompt: str, role: str = "user", convo_id: str = "default", **kwargs): - """ - Non-streaming ask - """ - response = self.ask_stream( - prompt=prompt, - role=role, - convo_id=convo_id, - **kwargs, - ) - full_response: str = "".join(response) - self.add_to_conversation(full_response, role, convo_id=convo_id) - usage_token = self.token_str(prompt) - com_token = self.token_str(full_response) - total_token = self.token_cost(convo_id=convo_id) - return full_response, usage_token, com_token, total_token - - def check_api_available(self): - response = self.session.post( - "https://api.openai.com/v1/chat/completions", - headers={"Authorization": f"Bearer {self.get_api_key()}"}, - json={ - "model": self.model_name, - "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "print A"}], - "stream": True, - # kwargs - "temperature": self.temperature, - "top_p": self.top_p, - "n": self.reply_count, - "user": "user", - }, - stream=True, - ) - if response.status_code == 200: - return True - else: - return False - def reset(self, convo_id: str = "default", system_prompt = None): - """ - Reset the conversation - """ - self.conversation[convo_id] = [ - {"role": "system", "content": str(system_prompt or self.system_prompt)}, - ] - def conversation_summary(self, convo_id: str = "default"): - input = "" - role = "" - for conv in self.conversation[convo_id]: - if (conv["role"]=='user'): - role = 'User' - else: - role = 'ChatGpt' - input+=role+' : '+conv['content']+'\n' - prompt = "Your goal is to summarize the provided conversation in English. Your summary should be concise and focus on the key information to facilitate better dialogue for the large language model.Ensure that you include all necessary details and relevant information while still reducing the length of the conversation as much as possible. Your summary should be clear and easily understandable for the ChatGpt model providing a comprehensive and concise summary of the conversation." - if(self.token_str(str(input)+prompt)>self.max_tokens): - input = input[self.token_str(str(input))-self.max_tokens:] - while self.token_str(str(input)+prompt)>self.max_tokens: - input = input[self.decrease_step:] - prompt = prompt.replace("{conversation}", input) - self.reset(convo_id='conversationSummary') - response = self.ask(prompt,convo_id='conversationSummary') - while self.token_str(str(response))>self.max_tokens: - response = response[:-self.decrease_step] - self.reset(convo_id='conversationSummary',system_prompt='Summariaze our diaglog') - self.conversation[convo_id] = [ - {"role": "system", "content": self.system_prompt}, - {"role": "user", "content": "Summariaze our diaglog"}, - {"role": 'assistant', "content": response}, - ] - return self.conversation[convo_id] - def token_cost(self,convo_id: str = "default"): - return len(ENCODER.encode("\n".join([x["content"] for x in self.conversation[convo_id]]))) - def token_str(self,content:str): - return len(ENCODER.encode(content)) -def main(): - return diff --git a/spaces/seayao/lambdalabs-sd-pokemon-diffusers/app.py b/spaces/seayao/lambdalabs-sd-pokemon-diffusers/app.py deleted file mode 100644 index ba69d664f64f09c76d2a761d5c5de53c7da3a8ff..0000000000000000000000000000000000000000 --- a/spaces/seayao/lambdalabs-sd-pokemon-diffusers/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/lambdalabs/sd-pokemon-diffusers").launch() \ No newline at end of file diff --git a/spaces/segestic/COVIDPrediction/application/components/prediction/serve_model.py b/spaces/segestic/COVIDPrediction/application/components/prediction/serve_model.py deleted file mode 100644 index bcc9cf179023c41796942c89b339e8c014c6d36a..0000000000000000000000000000000000000000 --- a/spaces/segestic/COVIDPrediction/application/components/prediction/serve_model.py +++ /dev/null @@ -1,50 +0,0 @@ -from io import BytesIO - -import numpy as np -import tensorflow as tf -from PIL import Image -#from tensorflow.keras.applications.imagenet_utils import decode_predictions -from tensorflow.keras.models import load_model -import os - - -model = None - -def load_model2(): - model = load_model('application/models/resnet_ct.h5') - #model = load_model(os.path.join(modelpath, 'resnet_ct.h5')) - print("Model loaded") - return model - - -def predict(image: Image.Image): - global model - if model is None: - model = load_model2() - - image = np.asarray(image.resize((224, 224)))[..., :3] - image = np.expand_dims(image, 0) - image = image / 127.5 - 1.0 - - result = model.predict(image) - probability = result[0] - #print("Resnet Predictions:") - if probability[0] > 0.5: - resnet_chest_pred = str('%.2f' % (probability[0]*100) + '% COVID') - else: - resnet_chest_pred = str('%.2f' % ((1-probability[0])*100) + '% NonCOVID') - - response = [] - for i, res in enumerate(result): - resp = {} - resp["prediction"] = resnet_chest_pred - #resp["confidence"] = f"{res[2]*100:0.2f} %" - - response.append(resp) - - return response - - -def read_imagefile(file) -> Image.Image: - image = Image.open(BytesIO(file)) - return image diff --git a/spaces/segments-tobias/conex/espnet/nets/chainer_backend/rnn/decoders.py b/spaces/segments-tobias/conex/espnet/nets/chainer_backend/rnn/decoders.py deleted file mode 100644 index e4a94a33dd243c98441bc29bce9ed7c7876b3459..0000000000000000000000000000000000000000 --- a/spaces/segments-tobias/conex/espnet/nets/chainer_backend/rnn/decoders.py +++ /dev/null @@ -1,528 +0,0 @@ -import logging -import random -import six - -import chainer -import chainer.functions as F -import chainer.links as L -import numpy as np - -import espnet.nets.chainer_backend.deterministic_embed_id as DL - -from argparse import Namespace - -from espnet.nets.ctc_prefix_score import CTCPrefixScore -from espnet.nets.e2e_asr_common import end_detect - -CTC_SCORING_RATIO = 1.5 -MAX_DECODER_OUTPUT = 5 - - -class Decoder(chainer.Chain): - """Decoder layer. - - Args: - eprojs (int): Dimension of input variables from encoder. - odim (int): The output dimension. - dtype (str): Decoder type. - dlayers (int): Number of layers for decoder. - dunits (int): Dimension of input vector of decoder. - sos (int): Number to indicate the start of sequences. - eos (int): Number to indicate the end of sequences. - att (Module): Attention module defined at - `espnet.espnet.nets.chainer_backend.attentions`. - verbose (int): Verbosity level. - char_list (List[str]): List of all charactors. - labeldist (numpy.array): Distributed array of counted transcript length. - lsm_weight (float): Weight to use when calculating the training loss. - sampling_probability (float): Threshold for scheduled sampling. - - """ - - def __init__( - self, - eprojs, - odim, - dtype, - dlayers, - dunits, - sos, - eos, - att, - verbose=0, - char_list=None, - labeldist=None, - lsm_weight=0.0, - sampling_probability=0.0, - ): - super(Decoder, self).__init__() - with self.init_scope(): - self.embed = DL.EmbedID(odim, dunits) - self.rnn0 = ( - L.StatelessLSTM(dunits + eprojs, dunits) - if dtype == "lstm" - else L.StatelessGRU(dunits + eprojs, dunits) - ) - for i in six.moves.range(1, dlayers): - setattr( - self, - "rnn%d" % i, - L.StatelessLSTM(dunits, dunits) - if dtype == "lstm" - else L.StatelessGRU(dunits, dunits), - ) - self.output = L.Linear(dunits, odim) - self.dtype = dtype - self.loss = None - self.att = att - self.dlayers = dlayers - self.dunits = dunits - self.sos = sos - self.eos = eos - self.verbose = verbose - self.char_list = char_list - # for label smoothing - self.labeldist = labeldist - self.vlabeldist = None - self.lsm_weight = lsm_weight - self.sampling_probability = sampling_probability - - def rnn_forward(self, ey, z_list, c_list, z_prev, c_prev): - if self.dtype == "lstm": - c_list[0], z_list[0] = self.rnn0(c_prev[0], z_prev[0], ey) - for i in six.moves.range(1, self.dlayers): - c_list[i], z_list[i] = self["rnn%d" % i]( - c_prev[i], z_prev[i], z_list[i - 1] - ) - else: - if z_prev[0] is None: - xp = self.xp - with chainer.backends.cuda.get_device_from_id(self._device_id): - z_prev[0] = chainer.Variable( - xp.zeros((ey.shape[0], self.dunits), dtype=ey.dtype) - ) - z_list[0] = self.rnn0(z_prev[0], ey) - for i in six.moves.range(1, self.dlayers): - if z_prev[i] is None: - xp = self.xp - with chainer.backends.cuda.get_device_from_id(self._device_id): - z_prev[i] = chainer.Variable( - xp.zeros( - (z_list[i - 1].shape[0], self.dunits), - dtype=z_list[i - 1].dtype, - ) - ) - z_list[i] = self["rnn%d" % i](z_prev[i], z_list[i - 1]) - return z_list, c_list - - def __call__(self, hs, ys): - """Core function of Decoder layer. - - Args: - hs (list of chainer.Variable | N-dimension array): - Input variable from encoder. - ys (list of chainer.Variable | N-dimension array): - Input variable of decoder. - - Returns: - chainer.Variable: A variable holding a scalar array of the training loss. - chainer.Variable: A variable holding a scalar array of the accuracy. - - """ - self.loss = None - # prepare input and output word sequences with sos/eos IDs - eos = self.xp.array([self.eos], "i") - sos = self.xp.array([self.sos], "i") - ys_in = [F.concat([sos, y], axis=0) for y in ys] - ys_out = [F.concat([y, eos], axis=0) for y in ys] - - # padding for ys with -1 - # pys: utt x olen - pad_ys_in = F.pad_sequence(ys_in, padding=self.eos) - pad_ys_out = F.pad_sequence(ys_out, padding=-1) - - # get dim, length info - batch = pad_ys_out.shape[0] - olength = pad_ys_out.shape[1] - logging.info( - self.__class__.__name__ - + " input lengths: " - + str(self.xp.array([h.shape[0] for h in hs])) - ) - logging.info( - self.__class__.__name__ - + " output lengths: " - + str(self.xp.array([y.shape[0] for y in ys_out])) - ) - - # initialization - c_list = [None] # list of cell state of each layer - z_list = [None] # list of hidden state of each layer - for _ in six.moves.range(1, self.dlayers): - c_list.append(None) - z_list.append(None) - att_w = None - z_all = [] - self.att.reset() # reset pre-computation of h - - # pre-computation of embedding - eys = self.embed(pad_ys_in) # utt x olen x zdim - eys = F.separate(eys, axis=1) - - # loop for an output sequence - for i in six.moves.range(olength): - att_c, att_w = self.att(hs, z_list[0], att_w) - if i > 0 and random.random() < self.sampling_probability: - logging.info(" scheduled sampling ") - z_out = self.output(z_all[-1]) - z_out = F.argmax(F.log_softmax(z_out), axis=1) - z_out = self.embed(z_out) - ey = F.hstack((z_out, att_c)) # utt x (zdim + hdim) - else: - ey = F.hstack((eys[i], att_c)) # utt x (zdim + hdim) - z_list, c_list = self.rnn_forward(ey, z_list, c_list, z_list, c_list) - z_all.append(z_list[-1]) - - z_all = F.stack(z_all, axis=1).reshape(batch * olength, self.dunits) - # compute loss - y_all = self.output(z_all) - self.loss = F.softmax_cross_entropy(y_all, F.flatten(pad_ys_out)) - # -1: eos, which is removed in the loss computation - self.loss *= np.mean([len(x) for x in ys_in]) - 1 - acc = F.accuracy(y_all, F.flatten(pad_ys_out), ignore_label=-1) - logging.info("att loss:" + str(self.loss.data)) - - # show predicted character sequence for debug - if self.verbose > 0 and self.char_list is not None: - y_hat = y_all.reshape(batch, olength, -1) - y_true = pad_ys_out - for (i, y_hat_), y_true_ in zip(enumerate(y_hat.data), y_true.data): - if i == MAX_DECODER_OUTPUT: - break - idx_hat = self.xp.argmax(y_hat_[y_true_ != -1], axis=1) - idx_true = y_true_[y_true_ != -1] - seq_hat = [self.char_list[int(idx)] for idx in idx_hat] - seq_true = [self.char_list[int(idx)] for idx in idx_true] - seq_hat = "".join(seq_hat).replace("", " ") - seq_true = "".join(seq_true).replace("", " ") - logging.info("groundtruth[%d]: " % i + seq_true) - logging.info("prediction [%d]: " % i + seq_hat) - - if self.labeldist is not None: - if self.vlabeldist is None: - self.vlabeldist = chainer.Variable(self.xp.asarray(self.labeldist)) - loss_reg = -F.sum( - F.scale(F.log_softmax(y_all), self.vlabeldist, axis=1) - ) / len(ys_in) - self.loss = (1.0 - self.lsm_weight) * self.loss + self.lsm_weight * loss_reg - - return self.loss, acc - - def recognize_beam(self, h, lpz, recog_args, char_list, rnnlm=None): - """Beam search implementation. - - Args: - h (chainer.Variable): One of the output from the encoder. - lpz (chainer.Variable | None): Result of net propagation. - recog_args (Namespace): The argument. - char_list (List[str]): List of all charactors. - rnnlm (Module): RNNLM module. Defined at `espnet.lm.chainer_backend.lm` - - Returns: - List[Dict[str,Any]]: Result of recognition. - - """ - logging.info("input lengths: " + str(h.shape[0])) - # initialization - c_list = [None] # list of cell state of each layer - z_list = [None] # list of hidden state of each layer - for _ in six.moves.range(1, self.dlayers): - c_list.append(None) - z_list.append(None) - a = None - self.att.reset() # reset pre-computation of h - - # search parms - beam = recog_args.beam_size - penalty = recog_args.penalty - ctc_weight = recog_args.ctc_weight - - # preprate sos - y = self.xp.full(1, self.sos, "i") - if recog_args.maxlenratio == 0: - maxlen = h.shape[0] - else: - # maxlen >= 1 - maxlen = max(1, int(recog_args.maxlenratio * h.shape[0])) - minlen = int(recog_args.minlenratio * h.shape[0]) - logging.info("max output length: " + str(maxlen)) - logging.info("min output length: " + str(minlen)) - - # initialize hypothesis - if rnnlm: - hyp = { - "score": 0.0, - "yseq": [y], - "c_prev": c_list, - "z_prev": z_list, - "a_prev": a, - "rnnlm_prev": None, - } - else: - hyp = { - "score": 0.0, - "yseq": [y], - "c_prev": c_list, - "z_prev": z_list, - "a_prev": a, - } - if lpz is not None: - ctc_prefix_score = CTCPrefixScore(lpz, 0, self.eos, self.xp) - hyp["ctc_state_prev"] = ctc_prefix_score.initial_state() - hyp["ctc_score_prev"] = 0.0 - if ctc_weight != 1.0: - # pre-pruning based on attention scores - ctc_beam = min(lpz.shape[-1], int(beam * CTC_SCORING_RATIO)) - else: - ctc_beam = lpz.shape[-1] - hyps = [hyp] - ended_hyps = [] - - for i in six.moves.range(maxlen): - logging.debug("position " + str(i)) - - hyps_best_kept = [] - for hyp in hyps: - ey = self.embed(hyp["yseq"][i]) # utt list (1) x zdim - att_c, att_w = self.att([h], hyp["z_prev"][0], hyp["a_prev"]) - ey = F.hstack((ey, att_c)) # utt(1) x (zdim + hdim) - - z_list, c_list = self.rnn_forward( - ey, z_list, c_list, hyp["z_prev"], hyp["c_prev"] - ) - - # get nbest local scores and their ids - local_att_scores = F.log_softmax(self.output(z_list[-1])).data - if rnnlm: - rnnlm_state, local_lm_scores = rnnlm.predict( - hyp["rnnlm_prev"], hyp["yseq"][i] - ) - local_scores = ( - local_att_scores + recog_args.lm_weight * local_lm_scores - ) - else: - local_scores = local_att_scores - - if lpz is not None: - local_best_ids = self.xp.argsort(local_scores, axis=1)[0, ::-1][ - :ctc_beam - ] - ctc_scores, ctc_states = ctc_prefix_score( - hyp["yseq"], local_best_ids, hyp["ctc_state_prev"] - ) - local_scores = (1.0 - ctc_weight) * local_att_scores[ - :, local_best_ids - ] + ctc_weight * (ctc_scores - hyp["ctc_score_prev"]) - if rnnlm: - local_scores += ( - recog_args.lm_weight * local_lm_scores[:, local_best_ids] - ) - joint_best_ids = self.xp.argsort(local_scores, axis=1)[0, ::-1][ - :beam - ] - local_best_scores = local_scores[:, joint_best_ids] - local_best_ids = local_best_ids[joint_best_ids] - else: - local_best_ids = self.xp.argsort(local_scores, axis=1)[0, ::-1][ - :beam - ] - local_best_scores = local_scores[:, local_best_ids] - - for j in six.moves.range(beam): - new_hyp = {} - # do not copy {z,c}_list directly - new_hyp["z_prev"] = z_list[:] - new_hyp["c_prev"] = c_list[:] - new_hyp["a_prev"] = att_w - new_hyp["score"] = hyp["score"] + local_best_scores[0, j] - new_hyp["yseq"] = [0] * (1 + len(hyp["yseq"])) - new_hyp["yseq"][: len(hyp["yseq"])] = hyp["yseq"] - new_hyp["yseq"][len(hyp["yseq"])] = self.xp.full( - 1, local_best_ids[j], "i" - ) - if rnnlm: - new_hyp["rnnlm_prev"] = rnnlm_state - if lpz is not None: - new_hyp["ctc_state_prev"] = ctc_states[joint_best_ids[j]] - new_hyp["ctc_score_prev"] = ctc_scores[joint_best_ids[j]] - # will be (2 x beam) hyps at most - hyps_best_kept.append(new_hyp) - - hyps_best_kept = sorted( - hyps_best_kept, key=lambda x: x["score"], reverse=True - )[:beam] - - # sort and get nbest - hyps = hyps_best_kept - logging.debug("number of pruned hypotheses: " + str(len(hyps))) - logging.debug( - "best hypo: " - + "".join([char_list[int(x)] for x in hyps[0]["yseq"][1:]]).replace( - "", " " - ) - ) - - # add eos in the final loop to avoid that there are no ended hyps - if i == maxlen - 1: - logging.info("adding in the last position in the loop") - for hyp in hyps: - hyp["yseq"].append(self.xp.full(1, self.eos, "i")) - - # add ended hypotheses to a final list, - # and removed them from current hypotheses - # (this will be a problem, number of hyps < beam) - remained_hyps = [] - for hyp in hyps: - if hyp["yseq"][-1] == self.eos: - # only store the sequence that has more than minlen outputs - # also add penalty - if len(hyp["yseq"]) > minlen: - hyp["score"] += (i + 1) * penalty - if rnnlm: # Word LM needs to add final score - hyp["score"] += recog_args.lm_weight * rnnlm.final( - hyp["rnnlm_prev"] - ) - ended_hyps.append(hyp) - else: - remained_hyps.append(hyp) - - # end detection - if end_detect(ended_hyps, i) and recog_args.maxlenratio == 0.0: - logging.info("end detected at %d", i) - break - - hyps = remained_hyps - if len(hyps) > 0: - logging.debug("remaining hypotheses: " + str(len(hyps))) - else: - logging.info("no hypothesis. Finish decoding.") - break - - for hyp in hyps: - logging.debug( - "hypo: " - + "".join([char_list[int(x)] for x in hyp["yseq"][1:]]).replace( - "", " " - ) - ) - - logging.debug("number of ended hypotheses: " + str(len(ended_hyps))) - - nbest_hyps = sorted(ended_hyps, key=lambda x: x["score"], reverse=True)[ - : min(len(ended_hyps), recog_args.nbest) - ] - - # check number of hypotheses - if len(nbest_hyps) == 0: - logging.warning( - "there is no N-best results, " - "perform recognition again with smaller minlenratio." - ) - # should copy because Namespace will be overwritten globally - recog_args = Namespace(**vars(recog_args)) - recog_args.minlenratio = max(0.0, recog_args.minlenratio - 0.1) - return self.recognize_beam(h, lpz, recog_args, char_list, rnnlm) - - logging.info("total log probability: " + str(nbest_hyps[0]["score"])) - logging.info( - "normalized log probability: " - + str(nbest_hyps[0]["score"] / len(nbest_hyps[0]["yseq"])) - ) - - return nbest_hyps - - def calculate_all_attentions(self, hs, ys): - """Calculate all of attentions. - - Args: - hs (list of chainer.Variable | N-dimensional array): - Input variable from encoder. - ys (list of chainer.Variable | N-dimensional array): - Input variable of decoder. - - Returns: - chainer.Variable: List of attention weights. - - """ - # prepare input and output word sequences with sos/eos IDs - eos = self.xp.array([self.eos], "i") - sos = self.xp.array([self.sos], "i") - ys_in = [F.concat([sos, y], axis=0) for y in ys] - ys_out = [F.concat([y, eos], axis=0) for y in ys] - - # padding for ys with -1 - # pys: utt x olen - pad_ys_in = F.pad_sequence(ys_in, padding=self.eos) - pad_ys_out = F.pad_sequence(ys_out, padding=-1) - - # get length info - olength = pad_ys_out.shape[1] - - # initialization - c_list = [None] # list of cell state of each layer - z_list = [None] # list of hidden state of each layer - for _ in six.moves.range(1, self.dlayers): - c_list.append(None) - z_list.append(None) - att_w = None - att_ws = [] - self.att.reset() # reset pre-computation of h - - # pre-computation of embedding - eys = self.embed(pad_ys_in) # utt x olen x zdim - eys = F.separate(eys, axis=1) - - # loop for an output sequence - for i in six.moves.range(olength): - att_c, att_w = self.att(hs, z_list[0], att_w) - ey = F.hstack((eys[i], att_c)) # utt x (zdim + hdim) - z_list, c_list = self.rnn_forward(ey, z_list, c_list, z_list, c_list) - att_ws.append(att_w) # for debugging - - att_ws = F.stack(att_ws, axis=1) - att_ws.to_cpu() - - return att_ws.data - - -def decoder_for(args, odim, sos, eos, att, labeldist): - """Return the decoding layer corresponding to the args. - - Args: - args (Namespace): The program arguments. - odim (int): The output dimension. - sos (int): Number to indicate the start of sequences. - eos (int) Number to indicate the end of sequences. - att (Module): - Attention module defined at `espnet.nets.chainer_backend.attentions`. - labeldist (numpy.array): Distributed array of length od transcript. - - Returns: - chainer.Chain: The decoder module. - - """ - return Decoder( - args.eprojs, - odim, - args.dtype, - args.dlayers, - args.dunits, - sos, - eos, - att, - args.verbose, - args.char_list, - labeldist, - args.lsm_weight, - args.sampling_probability, - ) diff --git a/spaces/segments-tobias/conex/espnet2/tts/feats_extract/energy.py b/spaces/segments-tobias/conex/espnet2/tts/feats_extract/energy.py deleted file mode 100644 index d80f3af53b5e59f44b427b3b0f9189ee20861baf..0000000000000000000000000000000000000000 --- a/spaces/segments-tobias/conex/espnet2/tts/feats_extract/energy.py +++ /dev/null @@ -1,143 +0,0 @@ -# Copyright 2020 Nagoya University (Tomoki Hayashi) -# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - -"""Energy extractor.""" - -from typing import Any -from typing import Dict -from typing import Tuple -from typing import Union - -import humanfriendly -import torch -import torch.nn.functional as F - -from typeguard import check_argument_types - -from espnet.nets.pytorch_backend.nets_utils import pad_list -from espnet2.layers.stft import Stft -from espnet2.tts.feats_extract.abs_feats_extract import AbsFeatsExtract - - -class Energy(AbsFeatsExtract): - """Energy extractor.""" - - def __init__( - self, - fs: Union[int, str] = 22050, - n_fft: int = 1024, - win_length: int = None, - hop_length: int = 256, - window: str = "hann", - center: bool = True, - normalized: bool = False, - onesided: bool = True, - use_token_averaged_energy: bool = True, - reduction_factor: int = None, - ): - assert check_argument_types() - super().__init__() - if isinstance(fs, str): - fs = humanfriendly.parse_size(fs) - - self.fs = fs - self.n_fft = n_fft - self.hop_length = hop_length - self.win_length = win_length - self.window = window - self.use_token_averaged_energy = use_token_averaged_energy - if use_token_averaged_energy: - assert reduction_factor >= 1 - self.reduction_factor = reduction_factor - - self.stft = Stft( - n_fft=n_fft, - win_length=win_length, - hop_length=hop_length, - window=window, - center=center, - normalized=normalized, - onesided=onesided, - ) - - def output_size(self) -> int: - return 1 - - def get_parameters(self) -> Dict[str, Any]: - return dict( - fs=self.fs, - n_fft=self.n_fft, - hop_length=self.hop_length, - window=self.window, - win_length=self.win_length, - center=self.stft.center, - normalized=self.stft.normalized, - use_token_averaged_energy=self.use_token_averaged_energy, - reduction_factor=self.reduction_factor, - ) - - def forward( - self, - input: torch.Tensor, - input_lengths: torch.Tensor = None, - feats_lengths: torch.Tensor = None, - durations: torch.Tensor = None, - durations_lengths: torch.Tensor = None, - ) -> Tuple[torch.Tensor, torch.Tensor]: - # If not provide, we assume that the inputs have the same length - if input_lengths is None: - input_lengths = ( - input.new_ones(input.shape[0], dtype=torch.long) * input.shape[1] - ) - - # Domain-conversion: e.g. Stft: time -> time-freq - input_stft, energy_lengths = self.stft(input, input_lengths) - - assert input_stft.dim() >= 4, input_stft.shape - assert input_stft.shape[-1] == 2, input_stft.shape - - # input_stft: (..., F, 2) -> (..., F) - input_power = input_stft[..., 0] ** 2 + input_stft[..., 1] ** 2 - # sum over frequency (B, N, F) -> (B, N) - energy = torch.sqrt(torch.clamp(input_power.sum(dim=2), min=1.0e-10)) - - # (Optional): Adjust length to match with the mel-spectrogram - if feats_lengths is not None: - energy = [ - self._adjust_num_frames(e[:el].view(-1), fl) - for e, el, fl in zip(energy, energy_lengths, feats_lengths) - ] - energy_lengths = feats_lengths - - # (Optional): Average by duration to calculate token-wise energy - if self.use_token_averaged_energy: - durations = durations * self.reduction_factor - energy = [ - self._average_by_duration(e[:el].view(-1), d) - for e, el, d in zip(energy, energy_lengths, durations) - ] - energy_lengths = durations_lengths - - # Padding - if isinstance(energy, list): - energy = pad_list(energy, 0.0) - - # Return with the shape (B, T, 1) - return energy.unsqueeze(-1), energy_lengths - - def _average_by_duration(self, x: torch.Tensor, d: torch.Tensor) -> torch.Tensor: - assert 0 <= len(x) - d.sum() < self.reduction_factor - d_cumsum = F.pad(d.cumsum(dim=0), (1, 0)) - x_avg = [ - x[start:end].mean() if len(x[start:end]) != 0 else x.new_tensor(0.0) - for start, end in zip(d_cumsum[:-1], d_cumsum[1:]) - ] - return torch.stack(x_avg) - - @staticmethod - def _adjust_num_frames(x: torch.Tensor, num_frames: torch.Tensor) -> torch.Tensor: - if num_frames > len(x): - x = F.pad(x, (0, num_frames - len(x))) - elif num_frames < len(x): - x = x[:num_frames] - return x diff --git a/spaces/senfu/tiny_gaze/README.md b/spaces/senfu/tiny_gaze/README.md deleted file mode 100644 index 7682ea62457ba5f1a73d93a03e4be45d116eed35..0000000000000000000000000000000000000000 --- a/spaces/senfu/tiny_gaze/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Tiny Gaze -emoji: 📈 -colorFrom: gray -colorTo: pink -sdk: gradio -sdk_version: 3.0.24 -app_file: app.py -pinned: false -license: gpl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/shabnam91/Sanskrit-TTS/installation_instructions.md b/spaces/shabnam91/Sanskrit-TTS/installation_instructions.md deleted file mode 100644 index cbc8f7cd69cb19efb0debbe2451fc8321db659cb..0000000000000000000000000000000000000000 --- a/spaces/shabnam91/Sanskrit-TTS/installation_instructions.md +++ /dev/null @@ -1,21 +0,0 @@ -## 1. Install dependencies. -```bash -pip install -r requirements.txt -``` - -## 2. Run the application. -After successful installation of the required libraries, execute the script below to run the web application. - -```bash -python app.py -``` -## 3. Usage. -The first tab is used for text cleaning. - -The second tab is used for converting grapheme text to its phoneme equivalent. - -Once the grapheme is synthesized, it is saved automatically in the **audio_outputs** folder. - -The third tab is used for performing text to speech synthesis. Once the audi`o is synthesized, it is automatically saved in the **audio_outputs** folder. - - diff --git a/spaces/sham-ml/crack_detection_classifier/app.py b/spaces/sham-ml/crack_detection_classifier/app.py deleted file mode 100644 index ccddde2cd2ccef8da38b7223428311a58e8ba1b8..0000000000000000000000000000000000000000 --- a/spaces/sham-ml/crack_detection_classifier/app.py +++ /dev/null @@ -1,19 +0,0 @@ -import gradio as gr -from fastai.vision.all import * - -learn = load_learner('export.pkl') - -labels = learn.dls.vocab -def predict(img): - img = PILImage.create(img) - pred,pred_idx,probs = learn.predict(img) - return {labels[i]: float(probs[i]) for i in range(len(labels))} - -title = "Ceramic Crack Detection Classifier" -description = "A crack detection classifier trained on the kThis dataset is taken from the website Mendeley Data - Crack Detection, contributed by Çağlar Fırat Özgenel." -article="

      Blog post

      " -examples = ['siamese.jpg'] -interpretation='default' -enable_queue=True - -gr.Interface(fn=predict, inputs=gr.inputs.Image(shape=(512, 512)), outputs=gr.outputs.Label(num_top_classes=3)).launch() \ No newline at end of file diff --git a/spaces/shencc/gpt/check_proxy.py b/spaces/shencc/gpt/check_proxy.py deleted file mode 100644 index 754b5d36b0c39d29eb6f4dcb8ed88355bcb6335f..0000000000000000000000000000000000000000 --- a/spaces/shencc/gpt/check_proxy.py +++ /dev/null @@ -1,151 +0,0 @@ - -def check_proxy(proxies): - import requests - proxies_https = proxies['https'] if proxies is not None else '无' - try: - response = requests.get("https://ipapi.co/json/", - proxies=proxies, timeout=4) - data = response.json() - print(f'查询代理的地理位置,返回的结果是{data}') - if 'country_name' in data: - country = data['country_name'] - result = f"代理配置 {proxies_https}, 代理所在地:{country}" - elif 'error' in data: - result = f"代理配置 {proxies_https}, 代理所在地:未知,IP查询频率受限" - print(result) - return result - except: - result = f"代理配置 {proxies_https}, 代理所在地查询超时,代理可能无效" - print(result) - return result - - -def backup_and_download(current_version, remote_version): - """ - 一键更新协议:备份和下载 - """ - from toolbox import get_conf - import shutil - import os - import requests - import zipfile - os.makedirs(f'./history', exist_ok=True) - backup_dir = f'./history/backup-{current_version}/' - new_version_dir = f'./history/new-version-{remote_version}/' - if os.path.exists(new_version_dir): - return new_version_dir - os.makedirs(new_version_dir) - shutil.copytree('./', backup_dir, ignore=lambda x, y: ['history']) - proxies, = get_conf('proxies') - r = requests.get( - 'https://github.com/binary-husky/chatgpt_academic/archive/refs/heads/master.zip', proxies=proxies, stream=True) - zip_file_path = backup_dir+'/master.zip' - with open(zip_file_path, 'wb+') as f: - f.write(r.content) - dst_path = new_version_dir - with zipfile.ZipFile(zip_file_path, "r") as zip_ref: - for zip_info in zip_ref.infolist(): - dst_file_path = os.path.join(dst_path, zip_info.filename) - if os.path.exists(dst_file_path): - os.remove(dst_file_path) - zip_ref.extract(zip_info, dst_path) - return new_version_dir - - -def patch_and_restart(path): - """ - 一键更新协议:覆盖和重启 - """ - from distutils import dir_util - import shutil - import os - import sys - import time - import glob - from colorful import print亮黄, print亮绿, print亮红 - # if not using config_private, move origin config.py as config_private.py - if not os.path.exists('config_private.py'): - print亮黄('由于您没有设置config_private.py私密配置,现将您的现有配置移动至config_private.py以防止配置丢失,', - '另外您可以随时在history子文件夹下找回旧版的程序。') - shutil.copyfile('config.py', 'config_private.py') - path_new_version = glob.glob(path + '/*-master')[0] - dir_util.copy_tree(path_new_version, './') - print亮绿('代码已经更新,即将更新pip包依赖……') - for i in reversed(range(5)): time.sleep(1); print(i) - try: - import subprocess - subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt']) - except: - print亮红('pip包依赖安装出现问题,需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。') - print亮绿('更新完成,您可以随时在history子文件夹下找回旧版的程序,5s之后重启') - print亮红('假如重启失败,您可能需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。') - print(' ------------------------------ -----------------------------------') - for i in reversed(range(8)): time.sleep(1); print(i) - os.execl(sys.executable, sys.executable, *sys.argv) - - -def get_current_version(): - import json - try: - with open('./version', 'r', encoding='utf8') as f: - current_version = json.loads(f.read())['version'] - except: - current_version = "" - return current_version - - -def auto_update(): - """ - 一键更新协议:查询版本和用户意见 - """ - try: - from toolbox import get_conf - import requests - import time - import json - proxies, = get_conf('proxies') - response = requests.get( - "https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=5) - remote_json_data = json.loads(response.text) - remote_version = remote_json_data['version'] - if remote_json_data["show_feature"]: - new_feature = "新功能:" + remote_json_data["new_feature"] - else: - new_feature = "" - with open('./version', 'r', encoding='utf8') as f: - current_version = f.read() - current_version = json.loads(current_version)['version'] - if (remote_version - current_version) >= 0.01: - from colorful import print亮黄 - print亮黄( - f'\n新版本可用。新版本:{remote_version},当前版本:{current_version}。{new_feature}') - print('(1)Github更新地址:\nhttps://github.com/binary-husky/chatgpt_academic\n') - user_instruction = input('(2)是否一键更新代码(Y+回车=确认,输入其他/无输入+回车=不更新)?') - if user_instruction in ['Y', 'y']: - path = backup_and_download(current_version, remote_version) - try: - patch_and_restart(path) - except: - print('更新失败。') - else: - print('自动更新程序:已禁用') - return - else: - return - except: - print('自动更新程序:已禁用') - -def warm_up_modules(): - print('正在执行一些模块的预热...') - from request_llm.bridge_all import model_info - enc = model_info["gpt-3.5-turbo"]['tokenizer'] - enc.encode("模块预热", disallowed_special=()) - enc = model_info["gpt-4"]['tokenizer'] - enc.encode("模块预热", disallowed_special=()) - -if __name__ == '__main__': - import os - os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染 - from toolbox import get_conf - proxies, = get_conf('proxies') - check_proxy(proxies) diff --git a/spaces/shenfangqi/Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/docs/README.ja.md b/spaces/shenfangqi/Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/docs/README.ja.md deleted file mode 100644 index 492af2c454890f0e6e14e5c21f7b15052631e57a..0000000000000000000000000000000000000000 --- a/spaces/shenfangqi/Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/docs/README.ja.md +++ /dev/null @@ -1,106 +0,0 @@ -
      - -

      Retrieval-based-Voice-Conversion-WebUI

      -VITSに基づく使いやすい音声変換(voice changer)framework

      - -[![madewithlove](https://forthebadge.com/images/badges/built-with-love.svg)](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI) - -
      - -[![Open In Colab](https://img.shields.io/badge/Colab-F9AB00?style=for-the-badge&logo=googlecolab&color=525252)](https://colab.research.google.com/github/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/Retrieval_based_Voice_Conversion_WebUI.ipynb) -[![Licence](https://img.shields.io/github/license/liujing04/Retrieval-based-Voice-Conversion-WebUI?style=for-the-badge)](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/%E4%BD%BF%E7%94%A8%E9%9C%80%E9%81%B5%E5%AE%88%E7%9A%84%E5%8D%8F%E8%AE%AE-LICENSE.txt) -[![Huggingface](https://img.shields.io/badge/🤗%20-Spaces-yellow.svg?style=for-the-badge)](https://huggingface.co/lj1995/VoiceConversionWebUI/tree/main/) - -[![Discord](https://img.shields.io/badge/RVC%20Developers-Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/HcsmBBGyVk) - -
      - ------- - -[**更新日誌**](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/Changelog_CN.md) - -[**English**](./README.en.md) | [**中文简体**](../README.md) | [**日本語**](./README.ja.md) | [**한국어**](./README.ko.md) ([**韓國語**](./README.ko.han.md)) - -> デモ動画は[こちら](https://www.bilibili.com/video/BV1pm4y1z7Gm/)でご覧ください。 - -> RVCによるリアルタイム音声変換: [w-okada/voice-changer](https://github.com/w-okada/voice-changer) - -> 著作権侵害を心配することなく使用できるように、基底モデルは約50時間の高品質なオープンソースデータセットで訓練されています。 - -> 今後も、次々と使用許可のある高品質な歌声の資料集を追加し、基底モデルを訓練する予定です。 - -## はじめに -本リポジトリには下記の特徴があります。 - -+ Top1検索を用いることで、生の特徴量を訓練用データセット特徴量に変換し、トーンリーケージを削減します。 -+ 比較的貧弱なGPUでも、高速かつ簡単に訓練できます。 -+ 少量のデータセットからでも、比較的良い結果を得ることができます。(10分以上のノイズの少ない音声を推奨します。) -+ モデルを融合することで、音声を混ぜることができます。(ckpt processingタブの、ckpt mergeを使用します。) -+ 使いやすいWebUI。 -+ UVR5 Modelも含んでいるため、人の声とBGMを素早く分離できます。 - -## 環境構築 -Poetryで依存関係をインストールすることをお勧めします。 - -下記のコマンドは、Python3.8以上の環境で実行する必要があります: -```bash -# PyTorch関連の依存関係をインストール。インストール済の場合は省略。 -# 参照先: https://pytorch.org/get-started/locally/ -pip install torch torchvision torchaudio - -#Windows+ Nvidia Ampere Architecture(RTX30xx)の場合、 #21 に従い、pytorchに対応するcuda versionを指定する必要があります。 -#pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117 - -# PyTorch関連の依存関係をインストール。インストール済の場合は省略。 -# 参照先: https://python-poetry.org/docs/#installation -curl -sSL https://install.python-poetry.org | python3 - - -# Poetry経由で依存関係をインストール -poetry install -``` - -pipでも依存関係のインストールが可能です: - -**注意**:`faiss 1.7.2`は`macOS`で`Segmentation Fault: 11`を起こすので、マニュアルインストールする場合は、 `pip install faiss-cpu==1.7.0`を実行してください。 - -```bash -pip install -r requirements.txt -``` - -## 基底modelsを準備 -RVCは推論/訓練のために、様々な事前訓練を行った基底モデルを必要とします。 - -modelsは[Hugging Face space](https://huggingface.co/lj1995/VoiceConversionWebUI/tree/main/)からダウンロードできます。 - -以下は、RVCに必要な基底モデルやその他のファイルの一覧です。 -```bash -hubert_base.pt - -./pretrained - -./uvr5_weights - -# ffmpegがすでにinstallされている場合は省略 -./ffmpeg -``` -その後、下記のコマンドでWebUIを起動します。 -```bash -python infer-web.py -``` -Windowsをお使いの方は、直接`RVC-beta.7z`をダウンロード後に展開し、`go-web.bat`をクリックすることで、WebUIを起動することができます。(7zipが必要です。) - -また、リポジトリに[小白简易教程.doc](./小白简易教程.doc)がありますので、参考にしてください(中国語版のみ)。 - -## 参考プロジェクト -+ [ContentVec](https://github.com/auspicious3000/contentvec/) -+ [VITS](https://github.com/jaywalnut310/vits) -+ [HIFIGAN](https://github.com/jik876/hifi-gan) -+ [Gradio](https://github.com/gradio-app/gradio) -+ [FFmpeg](https://github.com/FFmpeg/FFmpeg) -+ [Ultimate Vocal Remover](https://github.com/Anjok07/ultimatevocalremovergui) -+ [audio-slicer](https://github.com/openvpi/audio-slicer) - -## 貢献者(contributor)の皆様の尽力に感謝します - - - diff --git a/spaces/shivammehta25/Diff-TTSG/diff_ttsg/__init__.py b/spaces/shivammehta25/Diff-TTSG/diff_ttsg/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/silencewing/server/youyou/.history/math_20230613231519.html b/spaces/silencewing/server/youyou/.history/math_20230613231519.html deleted file mode 100644 index dcc17750248558768725723ed2181a016e46293f..0000000000000000000000000000000000000000 --- a/spaces/silencewing/server/youyou/.history/math_20230613231519.html +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - Document - - - - -
      - - - - - - - - - - - - - - - - - - - - - - - - -
      题目
      答案
      正误
      得分
      -
      - - - - diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/Dishonored-The-Knife-Of-Dunwall-Dlc-Free-Download-Fixed.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/Dishonored-The-Knife-Of-Dunwall-Dlc-Free-Download-Fixed.md deleted file mode 100644 index 4e02d5b2aff05f222c1ce9cf532562d990cbb097..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/Dishonored-The-Knife-Of-Dunwall-Dlc-Free-Download-Fixed.md +++ /dev/null @@ -1,94 +0,0 @@ -## Dishonored The Knife Of Dunwall Dlc Free Download - - - - - - ![Dishonored The Knife Of Dunwall Dlc Free Download Fixed](https://cdn.shopify.com/s/files/1/0269/9467/1709/products/ll_full_pack_recto_3e4fbe15-962c-45fd-9764-2b9dd7096c90.jpg?v\u003d1643947490) - - - - - -**Download ->>->>->> [https://vercupalo.blogspot.com/?d=2txP3M](https://vercupalo.blogspot.com/?d=2txP3M)** - - - - - - - - - - - - Here is a possible title and article with html formatting for the keyword "Dishonored The Knife Of Dunwall Dlc Free Download": - -# Dishonored The Knife Of Dunwall Dlc Free Download: Play As The Legendary Assassin Daud - - - -If you enjoyed the award-winning first person action game Dishonored, you might want to check out its second add-on pack, The Knife Of Dunwall. This DLC gives you a new perspective on the story, as you take on the role of Daud, the legendary assassin who killed the Empress and changed the fate of Dunwall. - - - -In The Knife Of Dunwall, you will explore new areas of the city, face new enemies, and wield new powers, weapons and gadgets. You will also encounter a mysterious figure named Delilah, who holds the key to your redemption. Will you find a way to atone for your sins, or will you sink deeper into darkness? - - - -The Knife Of Dunwall is available for download on Steam, PlayStation 3 and Xbox 360 for $9.99 or 800 Microsoft Points. However, if you want to get it for free, you can try one of these methods: - - - -- Use a VPN service to access a region where the DLC is free or discounted. - -- Search for a torrent or a direct download link from a trusted source. - -- Wait for a sale or a giveaway from Steam or other platforms. - - - -Before you download The Knife Of Dunwall, make sure you have the base game Dishonored installed on your device. You will also need about 2 GB of free space on your hard drive. The DLC is compatible with Windows XP/Vista/7/8/10, PlayStation 3 and Xbox 360. - - - -Are you ready to play as Daud and uncover his secrets? Download The Knife Of Dunwall today and enjoy this thrilling DLC for Dishonored! - - - -If you want to continue Daud's story after The Knife Of Dunwall, you can also download the final DLC for Dishonored, The Brigmore Witches. This DLC will let you carry over your existing chaos levels, powers, weapons and upgrades from The Knife Of Dunwall, and face new challenges and enemies. - - - -In The Brigmore Witches, you will have to stop Delilah from completing a powerful ritual that will spell your doom. You will also have to deal with warring gangs, the Dead Eels and the Hatters, who can help or hinder you in your quest. And finally, you will have to confront Corvo Attano, the Royal Bodyguard and Assassin who is hunting you down for killing the Empress. - - - -The Brigmore Witches is available for download on Steam, PlayStation 3 and Xbox 360 for $9.99 or 800 Microsoft Points. You can also get it for free by using the same methods as mentioned above. However, you will need The Knife Of Dunwall DLC installed on your device before you can play The Brigmore Witches. - - - -Are you ready to face your fate as Daud and discover the truth about Delilah? Download The Brigmore Witches today and enjoy this epic conclusion to Daud's saga! - - - -Dishonored is a game that offers you a lot of choices and consequences. You can play as a stealthy assassin or a brutal fighter, you can spare or kill your targets, you can influence the fate of Dunwall and its people. With the DLCs, The Knife Of Dunwall and The Brigmore Witches, you can experience a different side of the story, as you play as Daud, the man who started it all. - - - -These DLCs will give you new powers, weapons and gadgets to use in your missions, as well as new locations to explore and new enemies to face. You will also learn more about the mysterious Outsider and his gifts, and the secrets of the witch Delilah and her cult. Your actions will determine the outcome of your story, and whether you will find redemption or damnation. - - - -If you are a fan of Dishonored, you should not miss these DLCs. They will add hours of gameplay and enjoyment to your experience, and they will make you appreciate the rich and immersive world of Dishonored even more. You can download them for free or for a reasonable price from various platforms, and play them on your PC or console. - - - -Dishonored is a game that will stay with you long after you finish it. And with these DLCs, you will have even more reasons to revisit it and discover new things. So what are you waiting for? Download The Knife Of Dunwall and The Brigmore Witches today and become Daud, the legendary assassin! - - dfd1c89656 - - - - - diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/APK Lite FB Download The Lighter Version of Facebook for Android.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/APK Lite FB Download The Lighter Version of Facebook for Android.md deleted file mode 100644 index 8e888c0bc95f929979654fc10b49c37e6b0f5bb0..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/APK Lite FB Download The Lighter Version of Facebook for Android.md +++ /dev/null @@ -1,117 +0,0 @@ -
      -

      Download APK Lite FB: A Faster and Lighter Facebook Experience

      -

      If you are looking for a way to enjoy Facebook without draining your battery, data, or storage, you might want to try APK Lite FB. This is a smaller, lighter version of the Facebook app that is designed to work on slow networks, save mobile data, and take up less space on your phone. In this article, we will explain what APK Lite FB is, how to download it, what are its benefits and drawbacks, and what are some alternatives to it.

      -

      download apk lite fb


      DOWNLOADhttps://ssurll.com/2uNYdD



      -

      What is APK Lite FB?

      -

      APK Lite FB is an official Facebook client that lets you use this popular social network through a much lighter app that's better suited for low-power Android devices or ones with limited Internet connections. It has all the essential features of Facebook, such as messages, reels, stories, videos, groups, marketplace, and news.

      -

      A smaller, lighter version of the Facebook app

      -

      The main difference between APK Lite FB and the regular Facebook app is its size. APK Lite FB's download is under 10MB. On my device, it only takes up 2.19MB of space. Compare that to the amount of space regular Facebook takes up, which is 167MB. This is a substantial difference.

      -

      Designed to work on slow networks, save mobile data, and take up less space

      -

      APK Lite FB is also designed to work on slow networks, such as 2G or 3G networks. It uses less data than the regular Facebook app by compressing images and videos. It also loads quickly and uploads photos faster. You can save even more data by choosing the photo quality that APK Lite FB will display. You can opt for low-resolution photos to reduce data usage.

      -

      Has all the essential features of Facebook

      -

      Despite being smaller and lighter than the regular Facebook app, APK Lite FB still has all the essential features of Facebook that you need. You can send and receive messages without needing a separate messenger app. You can watch, create, and share fun reels with your friends on Facebook or other platforms. You can enjoy and share everyday moments with stories. You can discover and watch tons of shows and videos from creators and pages you care about. You can find communities of people with similar interests and connect with them in groups. You can buy and sell locally on marketplace. You can also know what's happening locally and globally with news.

      -

      download facebook lite apk for android
      -download facebook lite apk latest version
      -download facebook lite apk free
      -download facebook lite apk from uptodown
      -download facebook lite apk from apkcombo
      -download facebook lite apk without play store
      -download facebook lite apk for low-end devices
      -download facebook lite apk for 2g network
      -download facebook lite apk for old android phones
      -download facebook lite apk and install
      -how to download facebook lite apk
      -where to download facebook lite apk
      -why download facebook lite apk
      -benefits of downloading facebook lite apk
      -disadvantages of downloading facebook lite apk
      -alternatives to downloading facebook lite apk
      -reviews of downloading facebook lite apk
      -tips for downloading facebook lite apk
      -problems with downloading facebook lite apk
      -solutions for downloading facebook lite apk
      -download fb lite mod apk
      -download fb lite transparent apk
      -download fb lite dark mode apk
      -download fb lite clone apk
      -download fb lite messenger apk
      -download fb lite video downloader apk
      -download fb lite app lock apk
      -download fb lite no ads apk
      -download fb lite unlimited likes apk
      -download fb lite auto followers apk
      -how to download fb lite mod apk
      -where to download fb lite mod apk
      -why download fb lite mod apk
      -benefits of downloading fb lite mod apk
      -disadvantages of downloading fb lite mod apk
      -alternatives to downloading fb lite mod apk
      -reviews of downloading fb lite mod apk
      -tips for downloading fb lite mod apk
      -problems with downloading fb lite mod apk
      -solutions for downloading fb lite mod apk

      -

      How to Download APK Lite FB?

      -

      There are several ways to download APK Lite FB on your Android device. Here are some of them:

      -

      From Google Play Store

      -

      The easiest way to download APK Lite FB is from Google Play Store. Just search for "Facebook Lite" in the store and tap on the install button. The app will be downloaded and installed on your device automatically.

      -

      From APKPure.com

      -

      If you don't have access to Google Play Store or want to download an older version of APK Lite FB, you can use a website called APKPure.com. This is a platform that offers free and pure APK files for Android devices. You can search for "Facebook Lite" on the website and download the latest version of the app. You will need to enable the installation of apps from unknown sources on your device settings before you can install the APK file.

      From Uptodown.com

      -

      Another website that you can use to download APK Lite FB is Uptodown.com. This is a popular app store that provides safe and fast downloads of APK files for Android devices. You can find "Facebook Lite" on the website and download the app with one click. You will also need to enable the installation of apps from unknown sources on your device settings before you can install the APK file.

      -

      Benefits of APK Lite FB

      -

      APK Lite FB has many benefits for users who want to enjoy Facebook without compromising their device performance or data usage. Here are some of them:

      -

      Installs fast and uses less storage space

      -

      As mentioned earlier, APK Lite FB is much smaller than the regular Facebook app. It installs fast and uses less storage space on your device. This means that you can save more space for other apps, photos, videos, and music on your phone.

      -

      Works on old Android phones and all networks

      -

      APK Lite FB is also compatible with old Android phones that may not support the regular Facebook app. It works on all Android devices running Android 4.0 or higher. It also works on all networks, including 2G, 3G, 4G, and Wi-Fi. You don't have to worry about your phone model or network speed when using APK Lite FB.

      -

      Saves mobile data and loads quickly

      -

      Another benefit of APK Lite FB is that it saves mobile data and loads quickly. It uses less data than the regular Facebook app by compressing images and videos. It also loads faster and uploads photos faster. You can save even more data by choosing the photo quality that APK Lite FB will display. You can opt for low-resolution photos to reduce data usage.

      -

      Drawbacks of APK Lite FB

      -

      However, APK Lite FB is not perfect. It has some drawbacks that you should be aware of before downloading it. Here are some of them:

      -

      Lacks some features of the regular Facebook app

      -

      The main drawback of APK Lite FB is that it lacks some features of the regular Facebook app, such as live streaming, gaming, dating, and marketplace shipping. If you want to use these features, you will need to download the regular Facebook app or use the web browser version of Facebook.

      -

      Has lower quality photos and videos

      -

      Another drawback of APK Lite FB is that it has lower quality photos and videos than the regular Facebook app. This is because it compresses images and videos to save data and load faster. If you want to see high-quality photos and videos on Facebook, you will need to use the regular Facebook app or the web browser version of Facebook.

      -

      Requires a separate messenger app for voice and video calls

      -

      The last drawback of APK Lite FB is that it requires a separate messenger app for voice and video calls. Unlike the regular Facebook app, which has a built-in messenger feature, APK Lite FB does not support voice and video calls within the app. You will need to download another app called Messenger Lite if you want to make voice and video calls with your Facebook friends.

      -

      Alternatives to APK Lite FB

      -

      If you are not satisfied with APK Lite FB or want to try something different, there are some alternatives to it that you can use. Here are some of them:

      -

      Frost for Facebook

      -

      Frost for Facebook is a third-party Facebook client that lets you use this popular social network through a much lighter and faster app that's better suited for low-power Android devices or ones with limited Internet connections. It has many features, such as:

      -
        -
      • True multi-user support, with account switcher in the drawer
      • -
      • Better multitasking, with overlaying browser to read posts and get back to your previous task
      • -
      • Contextual awareness, with notifications based on keywords or users
      • -
      • Material design, with beautiful themes and customizable colors
      • -
      • Fully opened, with source code available on GitHub
      • -
      • Fixes the little things, such as hiding sponsored posts and stories
      • -
      -

      Friendly Social Browser

      -

      Friendly Social Browser is another third-party Facebook client that lets you access multiple social accounts in one place.[^

      Hermit

      -

      Hermit is a third-party browser that lets you create lite apps from any website. It has many features, such as:

      -
        -
      • Sandbox: Multiple Profiles / Containers. Hermit is the only Android browser with Sandboxes: completely separate Containers that let you use Multiple Profiles. With the Sandbox feature, you can separate work accounts from personal accounts, create a separate sandboxed environment for privacy-invasive sites like Facebook, use multiple Google accounts, all active at the same time, in the same browser, and use Incognito Mode for sites that offer preferential treatment to first-time users.
      • -
      • Custom Block Lists in Content Blocker. With Premium, you can individually select the block lists that should be active for the Content Blocker. You can block ads, trackers, malware, phishing, cryptojacking, and more.
      • -
      • Tracking Parameter Remover. Many advertisers and data brokers add extra parameters to Web addresses that are only used to track users’ browsing habits. Turn on Tracking Parameter Removal in Hermit to safeguard your privacy.
      • -
      • Scriptlets. Run your own custom scripts on any page, or pick from Hermit's own innovative features that are built entirely as Scriptlets. You can add night mode, QR code scanner, article mode, and more.
      • -
      • Reader App. Distraction-free reading on the Web, with Hermit: no ads, no navigation bars, no clutter. From any other browser or app, share articles to the Reader app, which utilizes Hermit’s custom article parsing technology to provide you a cleaned-up reader view.
      • -
      • Printing & Save to PDF. Printing is fully-supported in Hermit, allowing you to generate PDFs from any Web page as well.
      • -
      • Tags. Tags are a great way to organize all your Lite Apps. Especially useful if you’ve created tons of them!
      • -
      • Custom User Agent. Besides the standard “Mobile” and “Desktop” user agents, you can configure a custom User Agent for every Lite App individually to see a different browsing experience than the default.
      • -
      • Backup and Restore. You can backup all your manually-configured Lite Apps and restore them later on the same or another device.
      • -
      -

      Conclusion

      -

      In conclusion, APK Lite FB is a faster and lighter Facebook experience that you can download on your Android device. It has many benefits, such as saving space, data, and battery, working on old phones and slow networks, and having all the essential features of Facebook. However, it also has some drawbacks, such as lacking some features of the regular Facebook app, having lower quality photos and videos, and requiring a separate messenger app for voice and video calls. If you are not satisfied with APK Lite FB or want to try something different, there are some alternatives to it that you can use, such as Frost for Facebook, Friendly Social Browser, and Hermit.

      -

      FAQs

      -

      Here are some frequently asked questions about APK Lite FB:

      -

      Is APK Lite FB safe?

      -

      Yes, APK Lite FB is safe to use. It is an official Facebook client that does not contain any malware or viruses. However, if you download it from third-party websites, make sure they are trustworthy and scan the APK file before installing it.

      -

      Can I use APK Lite FB on my PC?

      -

      No, APK Lite FB is only available for Android devices. If you want to use Facebook on your PC, you can use the web browser version of Facebook or download the regular Facebook app from the Microsoft Store.

      -

      How do I update APK Lite FB?

      -

      If you downloaded APK Lite FB from Google Play Store, you can update it automatically or manually from the store. If you downloaded it from other websites, you will need to check for updates on those websites and download the latest version of the app.

      -

      How do I delete APK Lite FB?

      -

      If you want to delete APK Lite FB from your device, you can go to your device settings > apps > APK Lite FB > uninstall. Alternatively, you can long-press on the app icon and drag it to the uninstall option.

      -

      How do I contact APK Lite FB support?

      -

      If you have any issues or feedback about APK Lite FB, you can contact its support team by going to the app settings > help & feedback > report a problem or send feedback.

      197e85843d
      -
      -
      \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/CarX Street 0.8.1 APK Customize Your Car and Dominate the Streets.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/CarX Street 0.8.1 APK Customize Your Car and Dominate the Streets.md deleted file mode 100644 index c6cc98f5ee4e1531f926e19bc645bbe5d80c1023..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/CarX Street 0.8.1 APK Customize Your Car and Dominate the Streets.md +++ /dev/null @@ -1,120 +0,0 @@ -
      -

      CarX Street 0.8.1 APK: A Free and Realistic Street Racing Game for Android

      |

      If you are a fan of street racing games, you might want to check out CarX Street, a free and realistic racing game from CarX Technology for Android devices. CarX Street is the latest game from the makers of CarX Drift Racing 2, and it offers you an exciting and immersive experience of open world street racing, car tuning, and drifting.

      -

      car x street 0.8.1 apk


      Download Zip 🆗 https://ssurll.com/2uNTn3



      -

      In this article, we will tell you everything you need to know about CarX Street 0.8.1 APK, including what it is, what features it has, how to download and install it, and how to play it. We will also answer some frequently asked questions about the game.

      -

      What is CarX Street?

      -

      CarX Street is a mobile racing game that lets you embrace the freedom of being a street racer in the dynamic open world of Sunset City. You can choose from a variety of cars, customize them to your liking, and race against other players or AI opponents in different modes.

      -

      CarX Street is powered by CarX Technology, which is a physics engine that simulates realistic car behavior and dynamics. This means that you can feel every nuance of your car's performance, such as acceleration, braking, steering, traction, suspension, and more.

      -

      car x street racing apk download
      -car x street mod apk unlimited money
      -car x street open world apk
      -car x street latest version apk
      -car x street android game apk
      -car x street drift racing apk
      -car x street 0.8.1 apk obb
      -car x street 0.8.1 apk mod
      -car x street 0.8.1 apk free
      -car x street 0.8.1 apk offline
      -car x street 0.8.1 apk data
      -car x street 0.8.1 apk hack
      -car x street 0.8.1 apk full
      -car x street 0.8.1 apk revdl
      -car x street 0.8.1 apk rexdl
      -car x street 0.9.2 apk download
      -car x street 0.9.2 apk mod money
      -car x street 0.9.2 apk free download
      -car x street 0.9.2 apk obb download
      -car x street 0.9.2 apk data download
      -car x street 0.9.2 apk hack download
      -car x street 0.9.2 apk full download
      -car x street 0.9.2 apk revdl download
      -car x street 0.9.2 apk rexdl download
      -car x street game download for android apk
      -car x street game mod apk download for android
      -car x street game latest version apk download for android
      -car x street game free download for android apk
      -car x street game offline download for android apk
      -car x street game hack download for android apk
      -how to download car x street on android apk
      -how to install car x street on android apk
      -how to play car x street on android apk
      -how to update car x street on android apk
      -how to mod car x street on android apk
      -how to hack car x street on android apk
      -best settings for car x street on android apk
      -best cars for car x street on android apk
      -best tips for car x street on android apk
      -best tricks for car x street on android apk
      -what is new in car x street 0.8.1 apk update
      -what is new in car x street 0.9.2 apk update
      -what is the size of car x street 0.8.1 apk file
      -what is the size of car x street 0.9.2 apk file
      -what are the features of car x street 0.8.1 apk
      -what are the features of car x street 0.9.2 apk
      -what are the requirements for car x street 0.8.1 apk
      -what are the requirements for car x street 0.9.2 apk
      -what are the reviews of car x street 0.8.1 apk

      -

      Features of CarX Street

      -

      CarX Street has many features that make it one of the best street racing games on Android. Here are some of them:

      -

      Open world street racing

      -

      You can explore every corner of the enormous world of CarX Street, which has highways, city streets, industrial zones, suburbs, and more. You can find various events and challenges to participate in, such as drag races, circuit races, time trials, drift races, and more.

      -

      You can also join clubs, defeat bosses, and prove to everyone that you are the best driver in the city. You can buy houses for your cars and assemble collections for every race mode.

      -

      Improved car tuning

      -

      You can build the car of your dreams using part tuning that unlocks all the physics of CarX Technology car behavior. You can swap parts and trick out your car for a specific race. You can upgrade the engine, transmission, body, suspension, tires, and more.

      -

      You can also swap the engine of your unique car. For example, you can put a V8 engine in a hatchback or a rotary engine in a muscle car.

      -

      Visual car tuning

      -

      You can customize the appearance of your car using visual tuning. You can change the mirrors, headlights, lights, skirt, bumper, rims, and much more. You can create a unique look for your car that reflects your personality and style.

      -

      The most realistic mobile racing game

      -

      You can enjoy the impressive physics and controls that make you the master of your car. You can feel the difference between front-wheel drive, rear-wheel drive, and all-wheel drive cars. You can also adjust the steering sensitivity, brake force distribution, traction control system, ABS system,

      and other settings to suit your driving style and preferences. You can also switch between different camera views, such as cockpit, hood, bumper, or third-person.

      -

      How to download and install CarX Street APK?

      -

      If you want to play CarX Street on your Android device, you will need to download and install the APK file, which is a package file that contains the game data and installation instructions. Here are the requirements and steps to do so:

      -

      Requirements for CarX Street APK

      -

      Before you download and install CarX Street APK, you will need to make sure that your device meets the following requirements:

      -
        -
      • Your device must have Android 6.0 or higher.
      • -
      • Your device must have at least 2 GB of RAM and 4 GB of free storage space.
      • -
      • Your device must have a stable internet connection.
      • -
      • You must enable the installation of apps from unknown sources in your device settings.
      • -
      -

      Steps to download and install CarX Street APK

      -

      Once you have checked the requirements, you can follow these steps to download and install CarX Street APK:

      -
        -
      1. Go to the official website of CarX Technology and find the download link for CarX Street APK. Alternatively, you can use a trusted third-party source that provides the latest version of the APK file.
      2. -
      3. Tap on the download link and wait for the file to be downloaded to your device.
      4. -
      5. Locate the downloaded file in your device's file manager and tap on it to start the installation process.
      6. -
      7. Follow the on-screen instructions and grant the necessary permissions to complete the installation.
      8. -
      9. Launch the game from your app drawer and enjoy!
      10. -
      -

      How to play CarX Street?

      -

      CarX Street is easy to play but hard to master. You will need to learn how to control your car, how to tune it, and how to compete with other racers. Here are some tips on how to play CarX Street:

      -

      Career mode

      -

      In career mode, you will start as a rookie racer and work your way up to become a legend. You will need to complete various missions and events, such as races, drifts, time trials, and more. You will also need to join clubs, defeat bosses, and earn money and reputation.

      -

      You can use the money and reputation to buy new cars, upgrade them, and customize them. You can also unlock new locations, modes, and features as you progress in your career.

      -

      Part tuning mode

      -

      In part tuning mode, you can fine-tune your car's performance by swapping parts and adjusting settings. You can change the engine, transmission, body, suspension, tires, brakes, and more. You can also test your car's performance on different tracks and conditions.

      -

      You can use part tuning mode to optimize your car for a specific race or mode. For example, you can increase the power and speed for drag races, or improve the handling and stability for drift races.

      -

      Drift mode

      -

      In drift mode, you can show off your skills and style by drifting around corners and curves. You can earn points by maintaining a high speed, angle, and distance while drifting. You can also perform combos by chaining multiple drifts together.

      -

      You can use drift mode to earn money and reputation, as well as unlock new cars and parts. You can also compete with other players or AI opponents in drift events and challenges.

      -

      Conclusion

      -

      CarX Street is a free and realistic street racing game for Android devices that offers you an exciting and immersive experience of open world street racing, car tuning, and drifting. You can choose from a variety of cars, customize them to your liking, and race against other players or AI opponents in different modes.

      -

      You can download and install CarX Street APK from the official website of CarX Technology or a trusted third-party source. You will need to have Android 6.0 or higher, 2 GB of RAM, 4 GB of free storage space, a stable internet connection, and enable the installation of apps from unknown sources.

      -

      You can play CarX Street in career mode, part tuning mode, or drift mode. You can also explore the dynamic open world of Sunset City, join clubs, defeat bosses, buy houses for your cars, assemble collections for every race mode, and more.

      -

      If you are looking for a fun and realistic street racing game on Android, you should definitely give CarX Street a try!

      -

      FAQs

      -

      Here are some frequently asked questions about CarX Street

      Here are some frequently asked questions about CarX Street:

      -
        -
      • Q: Is CarX Street free to play?
      • -
      • A: Yes, CarX Street is free to play, but it also offers in-app purchases for some items and features.
      • -
      • Q: Is CarX Street available on iOS and PC?
      • -
      • A: CarX Street is currently available on iOS devices, and it is planned to be released on PC in the future. You can follow the official website of CarX Technology or their social media accounts for updates and news.
      • -
      • Q: How can I connect with other players in CarX Street?
      • -
      • A: You can connect with other players in CarX Street by joining clubs, chatting with them, sending them gifts, and challenging them to races. You can also join the online community of CarX Street on Discord, Facebook, Instagram, YouTube, and other platforms.
      • -
      • Q: What are the best cars in CarX Street?
      • -
      • A: There is no definitive answer to this question, as different cars have different strengths and weaknesses, and it also depends on your personal preference and play style. However, some of the popular cars in CarX Street are the RX-7, the Mustang GT, the Supra, the Skyline GT-R, and the Evo X.
      • -
      • Q: How can I get more money and reputation in CarX Street?
      • -
      • A: You can get more money and reputation in CarX Street by completing missions and events, winning races and drifts, performing stunts and tricks, collecting bonuses and rewards, and buying houses for your cars.
      • -
      -

      I hope you enjoyed reading this article about CarX Street 0.8.1 APK. If you have any questions or feedback, please leave a comment below. Thank you for your time and attention!

      197e85843d
      -
      -
      \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Discover New Features and Updates with Minecraft Trial APK for Windows 10.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Discover New Features and Updates with Minecraft Trial APK for Windows 10.md deleted file mode 100644 index 7ded49cc9bb8a6ef89b4e60368e33e4c91087cc9..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Discover New Features and Updates with Minecraft Trial APK for Windows 10.md +++ /dev/null @@ -1,136 +0,0 @@ -
      -

      How to Download and Play Minecraft Trial APK for Windows 10

      -

      Minecraft is one of the most popular and creative games in the world. It allows you to explore, build, and survive in a randomly generated world of blocks, animals, and monsters. You can play it solo or with your friends, and customize it with mods, skins, and texture packs.

      -

      minecraft trial apk windows 10


      Downloadhttps://ssurll.com/2uNYmy



      -

      But what if you want to try Minecraft before buying it? Or what if you want to play it on your Windows 10 device without installing it? That's where Minecraft Trial APK comes in handy. In this article, we will show you what is Minecraft Trial APK, how to download it, and how to play it on your Windows 10 device.

      -

      What is Minecraft Trial APK?

      -

      A brief introduction to Minecraft and its features

      -

      Minecraft is a sandbox game that was created by Mojang Studios in 2009. It has two main game modes: creative and survival. In creative mode, you have unlimited resources and can build anything you want. In survival mode, you have to gather resources, craft tools and weapons, and fight against enemies and hunger.

      -

      Minecraft also has a multiplayer mode, where you can join servers and play with other players online. You can also create your own server and invite your friends to join. There are many types of servers, such as mini-games, adventure maps, role-playing, and more.

      -

      Minecraft is also very customizable. You can change the look and feel of the game by downloading and applying different mods, skins, and texture packs. Mods are modifications that add new features, items, blocks, or mechanics to the game. Skins are cosmetic changes that alter the appearance of your character. Texture packs are collections of images that change the graphics of the game.

      -

      minecraft free trial for windows 10
      -minecraft trial download for windows 10
      -minecraft trial edition for windows 10
      -minecraft trial version for windows 10
      -minecraft trial mode for windows 10
      -minecraft trial app for windows 10
      -minecraft trial game for windows 10
      -minecraft trial online for windows 10
      -minecraft trial play for windows 10
      -minecraft trial install for windows 10
      -minecraft trial pc for windows 10
      -minecraft trial microsoft store for windows 10
      -minecraft trial bedrock edition for windows 10
      -minecraft trial java edition for windows 10
      -minecraft trial ray tracing for windows 10
      -minecraft trial realms for windows 10
      -minecraft trial servers for windows 10
      -minecraft trial skins for windows 10
      -minecraft trial texture packs for windows 10
      -minecraft trial mods for windows 10
      -minecraft trial cheats for windows 10
      -minecraft trial commands for windows 10
      -minecraft trial seeds for windows 10
      -minecraft trial maps for windows 10
      -minecraft trial worlds for windows 10
      -minecraft trial creative mode for windows 10
      -minecraft trial survival mode for windows 10
      -minecraft trial adventure mode for windows 10
      -minecraft trial hardcore mode for windows 10
      -minecraft trial spectator mode for windows 10
      -minecraft trial multiplayer for windows 10
      -minecraft trial cross-platform for windows 10
      -minecraft trial xbox game pass for windows 10
      -minecraft trial oculus rift for windows 10
      -minecraft trial mixed reality for windows 10
      -how to get minecraft trial apk on windows 10
      -how to play minecraft trial apk on windows 10
      -how to download minecraft trial apk on windows 10
      -how to install minecraft trial apk on windows 10
      -how to update minecraft trial apk on windows 10
      -how to uninstall minecraft trial apk on windows 10
      -how to run minecraft trial apk on windows 10
      -how to fix minecraft trial apk on windows 10
      -how to hack minecraft trial apk on windows 10
      -how to mod minecraft trial apk on windows 10
      -how to extend minecraft trial apk on windows 10
      -how to activate minecraft trial apk on windows 10
      -how to buy minecraft after trial apk on windows 10
      -how to convert minecraft trial apk to full version on windows 10

      -

      The difference between Minecraft Trial APK and other versions of Minecraft

      -

      Minecraft has several versions for different platforms, such as Java Edition for PC, Bedrock Edition for mobile devices and consoles, Education Edition for schools, and more. Each version has its own advantages and disadvantages, such as compatibility, performance, updates, etc.

      -

      Minecraft Trial APK is a special version of Minecraft Bedrock Edition that is designed for Android devices. It allows you to play a limited version of Minecraft for free without installing it on your device. You can download it from the official website or from third-party sources.

      -

      The main difference between Minecraft Trial APK and other versions of Minecraft is that it has some restrictions and limitations. For example:

      -
        -
      • You can only play in survival mode with a fixed difficulty level.
      • -
      • You can only play in one world that is randomly generated each time you start the game.
      • -
      • You can only play for a limited time (usually around 90 minutes) before the game ends.
      • -
      • You cannot save your progress or resume your game later.
      • -
      • You cannot access multiplayer mode or join servers.
      • -
      • You cannot customize the game with mods, skins, or texture packs.
      • -
      -

      However, despite these limitations , Minecraft Trial APK still offers a fun and exciting way to experience Minecraft on your Windows 10 device. You can explore, build, and survive in a new world every time you play, and enjoy the amazing graphics and sounds of Minecraft.

      -

      How to Download Minecraft Trial APK for Windows 10

      -

      The steps to download and install Minecraft Trial APK from the official website

      -

      If you want to download and play Minecraft Trial APK for Windows 10, you need to follow these steps:

      -
        -
      1. Go to the official website of Minecraft Trial APK at https://www.minecraft.net/en-us/trial.
      2. -
      3. Click on the "Download" button and choose the option "Download for Android".
      4. -
      5. Save the file to your Windows 10 device. The file name should be something like "MinecraftTrial_1.16.221.01_x86.apk".
      6. -
      7. Install an Android emulator on your Windows 10 device. An Android emulator is a software that allows you to run Android apps on your PC. There are many Android emulators available, such as BlueStacks, NoxPlayer, LDPlayer, etc. You can choose the one that suits your preferences and system requirements.
      8. -
      9. Launch the Android emulator and sign in with your Google account.
      10. -
      11. Drag and drop the Minecraft Trial APK file into the emulator or use the "Install APK" option to locate and install it.
      12. -
      13. Once the installation is complete, you can find the Minecraft Trial APK icon on the emulator's home screen or app drawer.
      14. -
      15. Click on the icon and start playing Minecraft Trial APK for Windows 10.
      16. -
      -

      The requirements and limitations of Minecraft Trial APK for Windows 10

      -

      Before you download and play Minecraft Trial APK for Windows 10, you need to be aware of some requirements and limitations:

      -
        -
      • You need to have a Windows 10 device that meets the minimum system requirements of the Android emulator you choose. For example, BlueStacks requires at least 4 GB of RAM, 5 GB of disk space, and a graphics card that supports OpenGL 2.0 or higher.
      • -
      • You need to have a stable internet connection to download and install Minecraft Trial APK and the Android emulator.
      • -
      • You need to have a Google account to sign in to the Android emulator and access the Google Play Store.
      • -
      • You need to have enough storage space on your Windows 10 device and the Android emulator to install and run Minecraft Trial APK.
      • -
      • You need to accept the terms and conditions of Minecraft Trial APK and the Android emulator before using them.
      • -
      • You need to understand that Minecraft Trial APK is not an official version of Minecraft for Windows 10, and it may have some bugs, errors, or compatibility issues.
      • -
      • You need to respect the intellectual property rights of Mojang Studios and other parties involved in creating Minecraft Trial APK, and not use it for any illegal or unethical purposes.
      • -
      -

      How to Play Minecraft Trial APK for Windows 10

      -

      The game modes and options available in Minecraft Trial APK

      -

      When you launch Minecraft Trial APK for Windows 10, you will see a menu screen with several options. You can choose one of these options:

      -
        -
      • "Play": This option allows you to start a new game in survival mode with a randomly generated world. You can choose between two difficulty levels: easy or normal. You can also adjust some settings, such as sound, controls, language, etc.
      • -
      • "Store": This option allows you to access the Google Play Store from within the game. You can browse and purchase different items, such as skins, texture packs, maps, etc. However, these items will not work in Minecraft Trial APK, and you will need to buy the full version of Minecraft to use them.
      • -
      • "Achievements": This option allows you to view your achievements in the game. Achievements are goals that you can complete by performing certain actions or tasks in the game. For example, getting wood, crafting a bed, killing a mob, etc. You can earn points and badges for completing achievements.
      • -
      • "Feedback": This option allows you to send feedback about the game to Mojang Studios. You can rate the game, write a review, report a bug, or suggest an improvement.
      • -
      • "Settings": This option allows you to change some settings of the game, such as sound, controls, language, etc.
      • -
      -

      The tips and tricks to enjoy Minecraft Trial APK for Windows 10

      -

      Minecraft Trial APK for Windows 10 is a fun and exciting way to experience Minecraft on your PC. However, it can also be challenging and frustrating at times. Here are some tips and tricks to help you enjoy Minecraft Trial APK for Windows 10:

      -
        -
      • Use the mouse and keyboard to control the game. You can move with the WASD keys, jump with the spacebar, sneak with the shift key, and sprint with the control key. You can also use the mouse to look around, left-click to break blocks or attack, and right-click to place blocks or interact.
      • -
      • Collect resources as soon as possible. You will need wood, stone, food, and other materials to survive and craft items. You can find them in different biomes, such as forests, plains, mountains, deserts, etc. You can also use your crafting table to make more advanced items, such as tools, weapons, armor, etc.
      • -
      • Build a shelter before nightfall. The night is dangerous in Minecraft, as hostile mobs such as zombies, skeletons, spiders, and creepers will spawn and attack you. You can build a simple house out of dirt, wood, or stone, and light it up with torches. You can also make a bed out of wool and wood, and sleep in it to skip the night.
      • -
      • Explore the world and discover new things. Minecraft Trial APK for Windows 10 has a lot of secrets and surprises to offer. You can find caves, dungeons, villages, temples, monuments, and more. You can also encounter friendly mobs such as cows, pigs, chickens, sheep, etc., and tame some of them as pets.
      • -
      • Have fun and be creative. Minecraft Trial APK for Windows 10 is a game that lets you express your imagination and creativity. You can build anything you want, from simple houses to complex machines. You can also experiment with different blocks, items, and mechanics, and see what happens.
      • -
      -

      Conclusion

      -

      A summary of the main points and benefits of Minecraft Trial APK for Windows 10

      -

      Minecraft Trial APK for Windows 10 is a great way to try Minecraft for free without installing it on your PC. It allows you to play in survival mode with a randomly generated world for a limited time. You can explore, build, and survive in a world of blocks, animals, and monsters.

      -

      Minecraft Trial APK for Windows 10 has some limitations and restrictions compared to other versions of Minecraft. However, it still offers a fun and exciting experience that showcases the beauty and creativity of Minecraft. You can enjoy the amazing graphics and sounds of Minecraft on your Windows 10 device.

      -

      A call to action to try Minecraft Trial APK for Windows 10

      -

      If you are interested in playing Minecraft Trial APK for Windows 10, you can download it from the official website or from third-party sources. You will also need an Android emulator to run it on your PC. You can follow the steps we provided above to download and install Minecraft Trial APK for Windows 10.

      -

      Minecraft Trial APK for Windows 10 is a great opportunity to test Minecraft before buying it. It is also a great alternative to play Minecraft on your PC without installing it. You can have a lot of fun and adventure in Minecraft Trial APK for Windows 10.

      -

      So what are you waiting for? Download Minecraft Trial APK for Windows 10 today and start playing!

      -

      FAQs

      -

      How long is the Minecraft Trial APK for Windows 10?

      -

      The Minecraft Trial APK for Windows 10 usually lasts for about 90 minutes. However, this may vary depending on your device performance and internet connection. After the trial period ends, the game will stop and you will not be able to resume it.

      -

      Can I play multiplayer in Minecraft Trial APK for Windows 10?

      -

      No, you cannot play multiplayer in Minecraft Trial APK for Windows 10. The trial version does not support multiplayer mode or joining servers. You can only play solo in survival mode with a randomly generated world.

      -

      Can I save my progress in Minecraft Trial APK for Windows 10?

      -

      No, you cannot save your progress in Minecraft Trial APK for Windows 10. The trial version does not allow you to save or load your game. You will lose your progress when you exit or restart the game.

      -

      Can I upgrade to the full version of Minecraft from Minecraft Trial APK for Windows 10?

      -

      Yes, you can upgrade to the full version of Minecraft from Minecraft Trial APK for Windows 10. You can do this by purchasing the game from the Google Play Store or from the official website of Minecraft. However, you will need to install the full version separately on your device or emulator.

      -

      Is Minecraft Trial APK for Windows 10 safe and legal?

      -

      Yes, Minecraft Trial APK for Windows 10 is safe and legal. It is an official version of Minecraft that is provided by Mojang Studios for free. It does not contain any viruses, malware, or illegal content. However, you should always download it from the official website or from trusted sources, and not from unknown or suspicious websites.

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/simsantonioii/MusicGen-Continuation/tests/common_utils/wav_utils.py b/spaces/simsantonioii/MusicGen-Continuation/tests/common_utils/wav_utils.py deleted file mode 100644 index d3a563ee1749a58217ece55c9a08b8d93c0fc386..0000000000000000000000000000000000000000 --- a/spaces/simsantonioii/MusicGen-Continuation/tests/common_utils/wav_utils.py +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -from pathlib import Path -import typing as tp - -import torch -import torchaudio - - -def get_white_noise(chs: int = 1, num_frames: int = 1): - wav = torch.randn(chs, num_frames) - return wav - - -def get_batch_white_noise(bs: int = 1, chs: int = 1, num_frames: int = 1): - wav = torch.randn(bs, chs, num_frames) - return wav - - -def save_wav(path: str, wav: torch.Tensor, sample_rate: int): - fp = Path(path) - kwargs: tp.Dict[str, tp.Any] = {} - if fp.suffix == '.wav': - kwargs['encoding'] = 'PCM_S' - kwargs['bits_per_sample'] = 16 - elif fp.suffix == '.mp3': - kwargs['compression'] = 320 - torchaudio.save(str(fp), wav, sample_rate, **kwargs) diff --git a/spaces/sirfindcent/skimlit/LabelEncoder.py b/spaces/sirfindcent/skimlit/LabelEncoder.py deleted file mode 100644 index 5953c1e571627440c5ebc4a24bd544e6bdcbe031..0000000000000000000000000000000000000000 --- a/spaces/sirfindcent/skimlit/LabelEncoder.py +++ /dev/null @@ -1,52 +0,0 @@ -# Citing code from VishalRK1 (2022): -# LabelEncoder.py. -# (Version 1.0) [Source code]. -# https://github.com/vishalrk1/SkimLit/blob/main/LabelEncoder.py - - -import numpy as np -import json - -class LabelEncoder(object): - """Label encoder for tag labels.""" - def __init__(self, class_to_index={}): - self.class_to_index = class_to_index - self.index_to_class = {v: k for k, v in self.class_to_index.items()} - self.classes = list(self.class_to_index.keys()) - - def __len__(self): - return len(self.class_to_index) - - def __str__(self): - return f"" - - def fit(self, y): - classes = np.unique(y) - for i, class_ in enumerate(classes): - self.class_to_index[class_] = i - self.index_to_class = {v: k for k, v in self.class_to_index.items()} - self.classes = list(self.class_to_index.keys()) - return self - - def encode(self, y): - encoded = np.zeros((len(y)), dtype=int) - for i, item in enumerate(y): - encoded[i] = self.class_to_index[item] - return encoded - - def decode(self, y): - classes = [] - for i, item in enumerate(y): - classes.append(self.index_to_class[item]) - return classes - - def save(self, fp): - with open(fp, "w") as fp: - contents = {'class_to_index': self.class_to_index} - json.dump(contents, fp, indent=4, sort_keys=False) - - @classmethod - def load(cls, fp): - with open(fp, "r") as fp: - kwargs = json.load(fp=fp) - return cls(**kwargs) \ No newline at end of file diff --git a/spaces/sklearn-docs/SVM-Kernels/README.md b/spaces/sklearn-docs/SVM-Kernels/README.md deleted file mode 100644 index a017427bc75f06ede3abad734893345a9a937198..0000000000000000000000000000000000000000 --- a/spaces/sklearn-docs/SVM-Kernels/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: SVM Kernels -emoji: 💻 -colorFrom: purple -colorTo: red -sdk: gradio -sdk_version: 3.28.3 -app_file: app.py -pinned: false -license: bsd-3-clause ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/skytnt/moe-tts/mel_processing.py b/spaces/skytnt/moe-tts/mel_processing.py deleted file mode 100644 index 3e252e76320522a8a4195a60665168f22769aec2..0000000000000000000000000000000000000000 --- a/spaces/skytnt/moe-tts/mel_processing.py +++ /dev/null @@ -1,101 +0,0 @@ -import torch -import torch.utils.data -from librosa.filters import mel as librosa_mel_fn - -MAX_WAV_VALUE = 32768.0 - - -def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): - """ - PARAMS - ------ - C: compression factor - """ - return torch.log(torch.clamp(x, min=clip_val) * C) - - -def dynamic_range_decompression_torch(x, C=1): - """ - PARAMS - ------ - C: compression factor used to compress - """ - return torch.exp(x) / C - - -def spectral_normalize_torch(magnitudes): - output = dynamic_range_compression_torch(magnitudes) - return output - - -def spectral_de_normalize_torch(magnitudes): - output = dynamic_range_decompression_torch(magnitudes) - return output - - -mel_basis = {} -hann_window = {} - - -def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False): - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - global hann_window - dtype_device = str(y.dtype) + '_' + str(y.device) - wnsize_dtype_device = str(win_size) + '_' + dtype_device - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], - center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - return spec - - -def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax): - global mel_basis - dtype_device = str(spec.dtype) + '_' + str(spec.device) - fmax_dtype_device = str(fmax) + '_' + dtype_device - if fmax_dtype_device not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device) - spec = torch.matmul(mel_basis[fmax_dtype_device], spec) - spec = spectral_normalize_torch(spec) - return spec - - -def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False): - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - global mel_basis, hann_window - dtype_device = str(y.dtype) + '_' + str(y.device) - fmax_dtype_device = str(fmax) + '_' + dtype_device - wnsize_dtype_device = str(win_size) + '_' + dtype_device - if fmax_dtype_device not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device) - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], - center=center, pad_mode='reflect', normalized=False, onesided=True) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - - spec = torch.matmul(mel_basis[fmax_dtype_device], spec) - spec = spectral_normalize_torch(spec) - - return spec diff --git a/spaces/softcatala/whisper-demo-catalan/README.md b/spaces/softcatala/whisper-demo-catalan/README.md deleted file mode 100644 index 7843cbfd85cf6bb73dfbef2f8863bb01aed27aa2..0000000000000000000000000000000000000000 --- a/spaces/softcatala/whisper-demo-catalan/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Whisper Demo -emoji: 🤫 -colorFrom: indigo -colorTo: red -sdk: gradio -sdk_version: 3.9.1 -app_file: app.py -pinned: false -tags: -- whisper-event -duplicated_from: whisper-event/whisper-demo ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/solara-dev/wanderlust/style.css b/spaces/solara-dev/wanderlust/style.css deleted file mode 100644 index 99dec705485e90697ffa33ba9a69f620d89f6867..0000000000000000000000000000000000000000 --- a/spaces/solara-dev/wanderlust/style.css +++ /dev/null @@ -1,80 +0,0 @@ -.jupyter-widgets.leaflet-widgets { - height: 100%; - border-radius: 20px; -} - -.solara-autorouter-content { - display: flex; - flex-direction: column; - justify-content: stretch; -} - -.v-toolbar__title { - display: flex; - align-items: center; - column-gap: 0.5rem; -} - -.ui-container { - height: 95vh; - justify-content: center; - padding: 45px 50px 75px 50px; -} - -.chat-interface { - height: 100%; - width: 38vw; - justify-content: center; - position: relative; -} - -.chat-interface:after { - content: ""; - position: absolute; - z-index: 1; - top: 0; - left: 0; - pointer-events: none; - background-image: linear-gradient(to top, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 100%); - width: 100%; - height: 15%; -} - -.map-container { - width: 50vw; - height: 100%; - justify-content: center; -} - -.v-application--wrap > div:nth-child(2) > div:nth-child(2){ - display: none !important; -} - -@media screen and (max-aspect-ratio: 1/1) { - .ui-container { - padding: 30px; - height: 100vh; - } - - .container-row { - flex-direction: column-reverse !important; - width: 100% !important; - } - - .chat-interface { - width: unset; - justify-content: flex-end; - } - - .map-container { - width: unset; - } - - .link-container{ - position: absolute; - bottom: 0; - left: 0; - width: 100%; - padding: 0 30px; - } -} diff --git a/spaces/somosnlp/somos-alpaca-es/Dockerfile b/spaces/somosnlp/somos-alpaca-es/Dockerfile deleted file mode 100644 index a98814b1a6a7949eb8cb8fbf2c90c65a8c0c1005..0000000000000000000000000000000000000000 --- a/spaces/somosnlp/somos-alpaca-es/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM argilla/argilla-quickstart:latest - -COPY load_data.py / - -RUN pip install argilla[listeners] - -CMD whoami && /start_quickstart_argilla.sh \ No newline at end of file diff --git a/spaces/sqc1729/bingi/src/components/tone-selector.tsx b/spaces/sqc1729/bingi/src/components/tone-selector.tsx deleted file mode 100644 index 5c6e464c91f564b895acd121f0a4a79ed9c5c356..0000000000000000000000000000000000000000 --- a/spaces/sqc1729/bingi/src/components/tone-selector.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import React from 'react' -import { BingConversationStyle } from '@/lib/bots/bing/types' -import { cn } from '@/lib/utils' - -type ToneItem = { - type: BingConversationStyle, - name: string -} - -const ToneList: ToneItem[] = [ - { name: '有创造力', type: BingConversationStyle.Creative }, - { name: '更平衡', type: BingConversationStyle.Balanced }, - { name: '更精确', type: BingConversationStyle.Precise } -] - -interface ToneSelectorProps { - type: BingConversationStyle | '' - onChange?: (type: BingConversationStyle) => void -} - -export function ToneSelector({ type, onChange }: ToneSelectorProps) { - return ( -
      -
      - 选择对话样式 -
      -
      -
        - { - ToneList.map(tone => ( -
      • onChange?.(tone.type)}> - -
      • - )) - } -
      -
      -
      - ) -} diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/model_parallel/modules/multihead_attention.py b/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/model_parallel/modules/multihead_attention.py deleted file mode 100644 index 8eb9d09dad37ab132295166d691873beec63eaf1..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/model_parallel/modules/multihead_attention.py +++ /dev/null @@ -1,349 +0,0 @@ -# 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. - -from typing import Dict, Optional, Tuple - -import torch -import torch.nn.functional as F -from fairseq import utils -from fairseq.incremental_decoding_utils import with_incremental_state -from fairseq.modules.fairseq_dropout import FairseqDropout -from torch import Tensor, nn - - -try: - from fairseq.model_parallel.megatron.mpu import ( - get_cuda_rng_tracker, - get_model_parallel_world_size, - ColumnParallelLinear, - RowParallelLinear, - ) - - has_megatron_submodule = True -except (ImportError, ModuleNotFoundError): - has_megatron_submodule = False - - -@with_incremental_state -class ModelParallelMultiheadAttention(nn.Module): - """Model parallel Multi-headed attention. - This performs the Multi-headed attention over multiple gpus. - - See "Megatron-LM: https://arxiv.org/pdf/1909.08053.pdf" for more details. - """ - - def __init__( - self, - embed_dim, - num_heads, - kdim=None, - vdim=None, - dropout=0.0, - bias=True, - self_attention=False, - encoder_decoder_attention=False, - ): - super().__init__() - if not has_megatron_submodule: - raise ImportError( - "\n\nPlease install the megatron submodule:" - "\n\n git submodule update --init " - "fairseq/model_parallel/megatron" - ) - self.embed_dim = embed_dim - self.kdim = kdim if kdim is not None else embed_dim - self.vdim = vdim if vdim is not None else embed_dim - self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim - - self.model_parallel_size = get_model_parallel_world_size() - - self.num_heads_partition = num_heads // self.model_parallel_size - assert ( - self.num_heads_partition * self.model_parallel_size == num_heads - ), "Number of heads must be divisible by model parallel size" - - self.dropout_module = FairseqDropout( - dropout, module_name=self.__class__.__name__ - ) - self.head_dim = embed_dim // num_heads - assert ( - self.head_dim * num_heads == self.embed_dim - ), "embed_dim must be divisible by num_heads" - self.scaling = self.head_dim ** -0.5 - - self.self_attention = self_attention - self.encoder_decoder_attention = encoder_decoder_attention - - assert ( - not self.self_attention or self.qkv_same_dim - ), "Self-attention requires query, key and value to be of the same size" - - self.k_proj = ColumnParallelLinear( - self.kdim, embed_dim, bias=bias, gather_output=False - ) - self.v_proj = ColumnParallelLinear( - self.vdim, embed_dim, bias=bias, gather_output=False - ) - self.q_proj = ColumnParallelLinear( - embed_dim, embed_dim, bias=bias, gather_output=False - ) - self.out_proj = RowParallelLinear( - embed_dim, embed_dim, bias=bias, input_is_parallel=True - ) - - def forward( - self, - query, - key: Optional[Tensor], - value: Optional[Tensor], - key_padding_mask: Optional[Tensor] = None, - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - static_kv: bool = False, - attn_mask: Optional[Tensor] = None, - **unused_kwargs, - ) -> Tuple[Tensor, Optional[Tensor]]: - """Input shape: Time x Batch x Channel - - Args: - key_padding_mask (ByteTensor, optional): mask to exclude - keys that are pads, of shape `(batch, src_len)`, where - padding elements are indicated by 1s. - attn_mask (ByteTensor, optional): typically used to - implement causal attention, where the mask prevents the - attention from looking forward in time (default: None). - """ - tgt_len, bsz, embed_dim = query.size() - assert embed_dim == self.embed_dim - assert list(query.size()) == [tgt_len, bsz, embed_dim] - - is_tpu = query.device.type == "xla" - - if incremental_state is not None: - saved_state = self._get_input_buffer(incremental_state) - if saved_state is not None and "prev_key" in saved_state: - # previous time steps are cached - no need to recompute - # key and value if they are static - if static_kv: - assert self.encoder_decoder_attention and not self.self_attention - key = value = None - else: - saved_state = None - - if self.self_attention: - q = self.q_proj(query) - k = self.k_proj(query) - v = self.v_proj(query) - elif self.encoder_decoder_attention: - # encoder-decoder attention - q = self.q_proj(query) - if key is None: - assert value is None - k = v = None - else: - k = self.k_proj(key) - v = self.v_proj(key) - - else: - assert key is not None and value is not None - q = self.q_proj(query) - k = self.k_proj(key) - v = self.v_proj(value) - q *= self.scaling - - q = ( - q.contiguous() - .view(tgt_len, bsz * self.num_heads_partition, self.head_dim) - .transpose(0, 1) - ) - if k is not None: - k = ( - k.contiguous() - .view(-1, bsz * self.num_heads_partition, self.head_dim) - .transpose(0, 1) - ) - if v is not None: - v = ( - v.contiguous() - .view(-1, bsz * self.num_heads_partition, self.head_dim) - .transpose(0, 1) - ) - - if saved_state is not None: - # saved states are stored with shape (bsz, num_heads_partition, seq_len, head_dim) - if "prev_key" in saved_state: - _prev_key = saved_state["prev_key"] - assert _prev_key is not None - prev_key = _prev_key.view( - bsz * self.num_heads_partition, -1, self.head_dim - ) - if static_kv: - k = prev_key - else: - assert k is not None - k = torch.cat([prev_key, k], dim=1) - if "prev_value" in saved_state: - _prev_value = saved_state["prev_value"] - assert _prev_value is not None - prev_value = _prev_value.view( - bsz * self.num_heads_partition, -1, self.head_dim - ) - if static_kv: - v = prev_value - else: - assert v is not None - v = torch.cat([prev_value, v], dim=1) - prev_key_padding_mask: Optional[Tensor] = None - if "prev_key_padding_mask" in saved_state: - prev_key_padding_mask = saved_state["prev_key_padding_mask"] - assert k is not None and v is not None - key_padding_mask = ( - ModelParallelMultiheadAttention._append_prev_key_padding_mask( - key_padding_mask=key_padding_mask, - prev_key_padding_mask=prev_key_padding_mask, - batch_size=bsz, - src_len=k.size(1), - static_kv=static_kv, - ) - ) - - saved_state["prev_key"] = k.view( - bsz, self.num_heads_partition, -1, self.head_dim - ) - saved_state["prev_value"] = v.view( - bsz, self.num_heads_partition, -1, self.head_dim - ) - saved_state["prev_key_padding_mask"] = key_padding_mask - # In this branch incremental_state is never None - assert incremental_state is not None - incremental_state = self._set_input_buffer(incremental_state, saved_state) - assert k is not None - src_len = k.size(1) - - # This is part of a workaround to get around fork/join parallelism - # not supporting Optional types. - if key_padding_mask is not None and key_padding_mask.dim() == 0: - key_padding_mask = None - - if key_padding_mask is not None: - assert key_padding_mask.size(0) == bsz - assert key_padding_mask.size(1) == src_len - - attn_weights = torch.bmm(q, k.transpose(1, 2)) - - assert list(attn_weights.size()) == [ - bsz * self.num_heads_partition, - tgt_len, - src_len, - ] - - if attn_mask is not None: - attn_mask = attn_mask.unsqueeze(0) - attn_weights += attn_mask - - if key_padding_mask is not None: - # don't attend to padding symbols - attn_weights = attn_weights.view( - bsz, self.num_heads_partition, tgt_len, src_len - ) - if not is_tpu: - attn_weights = attn_weights.masked_fill( - key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), - float("-inf"), - ) - else: - attn_weights = attn_weights.transpose(0, 2) - attn_weights = attn_weights.masked_fill(key_padding_mask, float("-inf")) - attn_weights = attn_weights.transpose(0, 2) - attn_weights = attn_weights.view( - bsz * self.num_heads_partition, tgt_len, src_len - ) - - attn_weights_float = utils.softmax(attn_weights, dim=-1) - attn_weights = attn_weights_float.type_as(attn_weights) - - with get_cuda_rng_tracker().fork(): - attn_probs = self.dropout_module(attn_weights) - - assert v is not None - attn = torch.bmm(attn_probs, v) - assert list(attn.size()) == [ - bsz * self.num_heads_partition, - tgt_len, - self.head_dim, - ] - embed_dim_partition = embed_dim // self.model_parallel_size - attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim_partition) - attn = self.out_proj(attn) - # return attn_weights None to keep the return type same as single gpu multihead attention - # This will be deprecated. - attn_weights: Optional[Tensor] = None - - return attn, attn_weights - - @staticmethod - def _append_prev_key_padding_mask( - key_padding_mask: Optional[Tensor], - prev_key_padding_mask: Optional[Tensor], - batch_size: int, - src_len: int, - static_kv: bool, - ) -> Optional[Tensor]: - # saved key padding masks have shape (bsz, seq_len) - if prev_key_padding_mask is not None and static_kv: - new_key_padding_mask = prev_key_padding_mask - elif prev_key_padding_mask is not None and key_padding_mask is not None: - new_key_padding_mask = torch.cat( - [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1 - ) - # During incremental decoding, as the padding token enters and - # leaves the frame, there will be a time when prev or current - # is None - elif prev_key_padding_mask is not None: - - filler = torch.zeros(batch_size, src_len - prev_key_padding_mask.size(1)) - if prev_key_padding_mask.is_cuda: - filler = filler.cuda() - new_key_padding_mask = torch.cat( - [prev_key_padding_mask.float(), filler.float()], dim=1 - ) - elif key_padding_mask is not None: - filler = torch.zeros(batch_size, src_len - key_padding_mask.size(1)) - if key_padding_mask.is_cuda: - filler = filler.cuda() - new_key_padding_mask = torch.cat( - [filler.float(), key_padding_mask.float()], dim=1 - ) - else: - new_key_padding_mask = prev_key_padding_mask - return new_key_padding_mask - - def reorder_incremental_state( - self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], new_order - ): - """Reorder buffered internal state (for incremental generation).""" - input_buffer = self._get_input_buffer(incremental_state) - if input_buffer is not None: - for k in input_buffer.keys(): - if input_buffer[k] is not None: - input_buffer[k] = input_buffer[k].index_select(0, new_order) - incremental_state = self._set_input_buffer(incremental_state, input_buffer) - return incremental_state - - def _get_input_buffer( - self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] - ) -> Dict[str, Optional[Tensor]]: - result = self.get_incremental_state(incremental_state, "attn_state") - if result is not None: - return result - else: - empty_result: Dict[str, Optional[Tensor]] = {} - return empty_result - - def _set_input_buffer( - self, - incremental_state: Dict[str, Dict[str, Optional[Tensor]]], - buffer: Dict[str, Optional[Tensor]], - ): - return self.set_incremental_state(incremental_state, "attn_state", buffer) diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/modules/lightconv_layer/__init__.py b/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/modules/lightconv_layer/__init__.py deleted file mode 100644 index 3b2a99c1227f827768911e5e22e79f6865ffbfd3..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/modules/lightconv_layer/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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. - -from .lightconv_layer import LightconvLayer # noqa diff --git a/spaces/sriramelango/Social_Classification_Public/utils/transforms.py b/spaces/sriramelango/Social_Classification_Public/utils/transforms.py deleted file mode 100644 index 0a9edf6c3da3052758cb36bcfe1f50ba69cc6f32..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/utils/transforms.py +++ /dev/null @@ -1,508 +0,0 @@ -import random - -import torch -import torchvision.transforms as T -import torchvision.transforms.functional as F -import numpy as np -from PIL import Image - - -def crop(image, target, region, delete=True): - cropped_image = F.crop(image, *region) - - target = target.copy() - i, j, h, w = region - - # should we do something wrt the original size? - target["size"] = torch.tensor([h, w]) - - fields = ["labels", "area"] - - if "boxes" in target: - boxes = target["boxes"] - max_size = torch.as_tensor([w, h], dtype=torch.float32) - cropped_boxes = boxes - torch.as_tensor([j, i, j, i]) - cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) - cropped_boxes = cropped_boxes.clamp(min=0) - area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1) - target["boxes"] = cropped_boxes.reshape(-1, 4) - target["area"] = area - fields.append("boxes") - - if "polygons" in target: - polygons = target["polygons"] - num_polygons = polygons.shape[0] - max_size = torch.as_tensor([w, h], dtype=torch.float32) - start_coord = torch.cat([torch.tensor([j, i], dtype=torch.float32) - for _ in range(polygons.shape[1] // 2)], dim=0) - cropped_boxes = polygons - start_coord - cropped_boxes = torch.min(cropped_boxes.reshape(num_polygons, -1, 2), max_size) - cropped_boxes = cropped_boxes.clamp(min=0) - target["polygons"] = cropped_boxes.reshape(num_polygons, -1) - fields.append("polygons") - - if "masks" in target: - # FIXME should we update the area here if there are no boxes? - target['masks'] = target['masks'][:, i:i + h, j:j + w] - fields.append("masks") - - # remove elements for which the boxes or masks that have zero area - if delete and ("boxes" in target or "masks" in target): - # favor boxes selection when defining which elements to keep - # this is compatible with previous implementation - if "boxes" in target: - cropped_boxes = target['boxes'].reshape(-1, 2, 2) - keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1) - else: - keep = target['masks'].flatten(1).any(1) - - for field in fields: - target[field] = target[field][keep.tolist()] - - return cropped_image, target - - -def hflip(image, target): - flipped_image = F.hflip(image) - - w, h = image.size - - target = target.copy() - if "boxes" in target: - boxes = target["boxes"] - boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor([w, 0, w, 0]) - target["boxes"] = boxes - - if "polygons" in target: - polygons = target["polygons"] - num_polygons = polygons.shape[0] - polygons = polygons.reshape(num_polygons, -1, 2) * torch.as_tensor([-1, 1]) + torch.as_tensor([w, 0]) - target["polygons"] = polygons - - if "masks" in target: - target['masks'] = target['masks'].flip(-1) - - return flipped_image, target - - -def resize(image, target, size, max_size=None): - # size can be min_size (scalar) or (w, h) tuple - - def get_size_with_aspect_ratio(image_size, size, max_size=None): - w, h = image_size - - if (w <= h and w == size) or (h <= w and h == size): - if max_size is not None: - max_size = int(max_size) - h = min(h, max_size) - w = min(w, max_size) - return (h, w) - - if w < h: - ow = size - oh = int(size * h / w) - else: - oh = size - ow = int(size * w / h) - - if max_size is not None: - max_size = int(max_size) - oh = min(oh, max_size) - ow = min(ow, max_size) - - return (oh, ow) - - def get_size(image_size, size, max_size=None): - if isinstance(size, (list, tuple)): - return size[::-1] - else: - return get_size_with_aspect_ratio(image_size, size, max_size) - - size = get_size(image.size, size, max_size) - rescaled_image = F.resize(image, size, interpolation=Image.BICUBIC) - - if target is None: - return rescaled_image - - ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size)) - ratio_width, ratio_height = ratios - - target = target.copy() - if "boxes" in target: - boxes = target["boxes"] - scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height]) - target["boxes"] = scaled_boxes - - if "polygons" in target: - polygons = target["polygons"] - scaled_ratio = torch.cat([torch.tensor([ratio_width, ratio_height]) - for _ in range(polygons.shape[1] // 2)], dim=0) - scaled_polygons = polygons * scaled_ratio - target["polygons"] = scaled_polygons - - if "area" in target: - area = target["area"] - scaled_area = area * (ratio_width * ratio_height) - target["area"] = scaled_area - - h, w = size - target["size"] = torch.tensor([h, w]) - - if "masks" in target: - assert False - # target['masks'] = interpolate( - # target['masks'][:, None].float(), size, mode="nearest")[:, 0] > 0.5 - - return rescaled_image, target - - -class CenterCrop(object): - def __init__(self, size): - self.size = size - - def __call__(self, img, target): - image_width, image_height = img.size - crop_height, crop_width = self.size - crop_top = int(round((image_height - crop_height) / 2.)) - crop_left = int(round((image_width - crop_width) / 2.)) - return crop(img, target, (crop_top, crop_left, crop_height, crop_width)) - - -class ObjectCenterCrop(object): - def __init__(self, size): - self.size = size - - def __call__(self, img, target): - image_width, image_height = img.size - crop_height, crop_width = self.size - - x0 = float(target['boxes'][0][0]) - y0 = float(target['boxes'][0][1]) - x1 = float(target['boxes'][0][2]) - y1 = float(target['boxes'][0][3]) - - center_x = (x0 + x1) / 2 - center_y = (y0 + y1) / 2 - crop_left = max(center_x-crop_width/2 + min(image_width-center_x-crop_width/2, 0), 0) - crop_top = max(center_y-crop_height/2 + min(image_height-center_y-crop_height/2, 0), 0) - - return crop(img, target, (crop_top, crop_left, crop_height, crop_width), delete=False) - - -class RandomHorizontalFlip(object): - def __init__(self, p=0.5): - self.p = p - - def __call__(self, img, target): - if random.random() < self.p: - return hflip(img, target) - return img, target - - -class RandomResize(object): - def __init__(self, sizes, max_size=None, equal=False): - assert isinstance(sizes, (list, tuple)) - self.sizes = sizes - self.max_size = max_size - self.equal = equal - - def __call__(self, img, target=None): - size = random.choice(self.sizes) - if self.equal: - return resize(img, target, size, size) - else: - return resize(img, target, size, self.max_size) - - -class ToTensor(object): - def __call__(self, img, target): - return F.to_tensor(img), target - - -class Normalize(object): - def __init__(self, mean, std, max_image_size=512): - self.mean = mean - self.std = std - self.max_image_size = max_image_size - - def __call__(self, image, target=None): - image = F.normalize(image, mean=self.mean, std=self.std) - if target is None: - return image, None - target = target.copy() - # h, w = image.shape[-2:] - h, w = target["size"][0], target["size"][1] - if "boxes" in target: - boxes = target["boxes"] - boxes = boxes / self.max_image_size - target["boxes"] = boxes - if "polygons" in target: - polygons = target["polygons"] - scale = torch.cat([torch.tensor([w, h], dtype=torch.float32) - for _ in range(polygons.shape[1] // 2)], dim=0) - polygons = polygons / scale - target["polygons"] = polygons - return image, target - - -class Compose(object): - def __init__(self, transforms): - self.transforms = transforms - - def __call__(self, image, target): - for t in self.transforms: - image, target = t(image, target) - return image, target - - def __repr__(self): - format_string = self.__class__.__name__ + "(" - for t in self.transforms: - format_string += "\n" - format_string += " {0}".format(t) - format_string += "\n)" - return format_string - - -class LargeScaleJitter(object): - """ - implementation of large scale jitter from copy_paste - """ - - def __init__(self, output_size=512, aug_scale_min=0.3, aug_scale_max=2.0): - self.desired_size = torch.tensor([output_size]) - self.aug_scale_min = aug_scale_min - self.aug_scale_max = aug_scale_max - - def rescale_target(self, scaled_size, image_size, target): - # compute rescaled targets - image_scale = scaled_size / image_size - ratio_height, ratio_width = image_scale - - target = target.copy() - target["size"] = scaled_size - - if "boxes" in target: - boxes = target["boxes"] - scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height]) - target["boxes"] = scaled_boxes - - if "area" in target: - area = target["area"] - scaled_area = area * (ratio_width * ratio_height) - target["area"] = scaled_area - - if "masks" in target: - assert False - masks = target['masks'] - # masks = interpolate( - # masks[:, None].float(), scaled_size, mode="nearest")[:, 0] > 0.5 - target['masks'] = masks - return target - - def crop_target(self, region, target): - i, j, h, w = region - fields = ["labels", "area"] - - target = target.copy() - target["size"] = torch.tensor([h, w]) - - if "boxes" in target: - boxes = target["boxes"] - max_size = torch.as_tensor([w, h], dtype=torch.float32) - cropped_boxes = boxes - torch.as_tensor([j, i, j, i]) - cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) - cropped_boxes = cropped_boxes.clamp(min=0) - area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1) - target["boxes"] = cropped_boxes.reshape(-1, 4) - target["area"] = area - fields.append("boxes") - - if "masks" in target: - # FIXME should we update the area here if there are no boxes? - target['masks'] = target['masks'][:, i:i + h, j:j + w] - fields.append("masks") - - # remove elements for which the boxes or masks that have zero area - if "boxes" in target or "masks" in target: - # favor boxes selection when defining which elements to keep - # this is compatible with previous implementation - if "boxes" in target: - cropped_boxes = target['boxes'].reshape(-1, 2, 2) - keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1) - else: - keep = target['masks'].flatten(1).any(1) - - for field in fields: - target[field] = target[field][keep.tolist()] - return target - - def pad_target(self, padding, target): - target = target.copy() - if "masks" in target: - target['masks'] = torch.nn.functional.pad(target['masks'], (0, padding[1], 0, padding[0])) - return target - - def __call__(self, image, target=None): - image_size = image.size - image_size = torch.tensor(image_size[::-1]) - - random_scale = torch.rand(1) * (self.aug_scale_max - self.aug_scale_min) + self.aug_scale_min - scaled_size = (random_scale * self.desired_size).round() - - scale = torch.maximum(scaled_size / image_size[0], scaled_size / image_size[1]) - scaled_size = (image_size * scale).round().int() - - scaled_image = F.resize(image, scaled_size.tolist(), interpolation=Image.BICUBIC) - - if target is not None: - target = self.rescale_target(scaled_size, image_size, target) - - # randomly crop or pad images - if random_scale >= 1: - # Selects non-zero random offset (x, y) if scaled image is larger than desired_size. - max_offset = scaled_size - self.desired_size - offset = (max_offset * torch.rand(2)).floor().int() - region = (offset[0].item(), offset[1].item(), - self.desired_size[0].item(), self.desired_size[0].item()) - output_image = F.crop(scaled_image, *region) - if target is not None: - target = self.crop_target(region, target) - else: - assert False - padding = self.desired_size - scaled_size - output_image = F.pad(scaled_image, [0, 0, padding[1].item(), padding[0].item()]) - if target is not None: - target = self.pad_target(padding, target) - - return output_image, target - - -class OriginLargeScaleJitter(object): - """ - implementation of large scale jitter from copy_paste - """ - - def __init__(self, output_size=512, aug_scale_min=0.3, aug_scale_max=2.0): - self.desired_size = torch.tensor(output_size) - self.aug_scale_min = aug_scale_min - self.aug_scale_max = aug_scale_max - - def rescale_target(self, scaled_size, image_size, target): - # compute rescaled targets - image_scale = scaled_size / image_size - ratio_height, ratio_width = image_scale - - target = target.copy() - target["size"] = scaled_size - - if "boxes" in target: - boxes = target["boxes"] - scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height]) - target["boxes"] = scaled_boxes - - if "area" in target: - area = target["area"] - scaled_area = area * (ratio_width * ratio_height) - target["area"] = scaled_area - - if "masks" in target: - assert False - masks = target['masks'] - # masks = interpolate( - # masks[:, None].float(), scaled_size, mode="nearest")[:, 0] > 0.5 - target['masks'] = masks - return target - - def crop_target(self, region, target): - i, j, h, w = region - fields = ["labels", "area"] - - target = target.copy() - target["size"] = torch.tensor([h, w]) - - if "boxes" in target: - boxes = target["boxes"] - max_size = torch.as_tensor([w, h], dtype=torch.float32) - cropped_boxes = boxes - torch.as_tensor([j, i, j, i]) - cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) - cropped_boxes = cropped_boxes.clamp(min=0) - area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1) - target["boxes"] = cropped_boxes.reshape(-1, 4) - target["area"] = area - fields.append("boxes") - - if "masks" in target: - # FIXME should we update the area here if there are no boxes? - target['masks'] = target['masks'][:, i:i + h, j:j + w] - fields.append("masks") - - # remove elements for which the boxes or masks that have zero area - if "boxes" in target or "masks" in target: - # favor boxes selection when defining which elements to keep - # this is compatible with previous implementation - if "boxes" in target: - cropped_boxes = target['boxes'].reshape(-1, 2, 2) - keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1) - else: - keep = target['masks'].flatten(1).any(1) - - for field in fields: - target[field] = target[field][keep.tolist()] - return target - - def pad_target(self, padding, target): - target = target.copy() - if "masks" in target: - target['masks'] = torch.nn.functional.pad(target['masks'], (0, padding[1], 0, padding[0])) - return target - - def __call__(self, image, target=None): - image_size = image.size - image_size = torch.tensor(image_size[::-1]) - - out_desired_size = (self.desired_size * image_size / max(image_size)).round().int() - - random_scale = torch.rand(1) * (self.aug_scale_max - self.aug_scale_min) + self.aug_scale_min - scaled_size = (random_scale * self.desired_size).round() - - scale = torch.minimum(scaled_size / image_size[0], scaled_size / image_size[1]) - scaled_size = (image_size * scale).round().int() - - scaled_image = F.resize(image, scaled_size.tolist()) - - if target is not None: - target = self.rescale_target(scaled_size, image_size, target) - - # randomly crop or pad images - if random_scale > 1: - # Selects non-zero random offset (x, y) if scaled image is larger than desired_size. - max_offset = scaled_size - out_desired_size - offset = (max_offset * torch.rand(2)).floor().int() - region = (offset[0].item(), offset[1].item(), - out_desired_size[0].item(), out_desired_size[1].item()) - output_image = F.crop(scaled_image, *region) - if target is not None: - target = self.crop_target(region, target) - else: - padding = out_desired_size - scaled_size - output_image = F.pad(scaled_image, [0, 0, padding[1].item(), padding[0].item()]) - if target is not None: - target = self.pad_target(padding, target) - - return output_image, target - - -class RandomDistortion(object): - """ - Distort image w.r.t hue, saturation and exposure. - """ - - def __init__(self, brightness=0, contrast=0, saturation=0, hue=0, prob=0.5): - self.prob = prob - self.tfm = T.ColorJitter(brightness, contrast, saturation, hue) - - def __call__(self, img, target=None): - if np.random.random() < self.prob: - return self.tfm(img), target - else: - return img, target diff --git a/spaces/stomexserde/gpt4-ui/Examples/Forex Killer 4.12 Keygenl.md b/spaces/stomexserde/gpt4-ui/Examples/Forex Killer 4.12 Keygenl.md deleted file mode 100644 index e5846ea07772cd9ec1c2d6e49cc15da8169e20ef..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Forex Killer 4.12 Keygenl.md +++ /dev/null @@ -1,72 +0,0 @@ -
      -

      Forex Killer 4.12 Keygen: How to Crack the Forex Trading Software

      -

      Introduction

      -

      If you are looking for a way to unlock the full potential of Forex Killer, a popular forex trading software that generates signals for trading on the forex market and other financial markets, you might be interested in using a keygen to get a free serial number. But what is a keygen and how does it work? And what are the benefits and risks of using one for Forex Killer? In this article, we will answer these questions and show you how to download, install, and use Forex Killer 4.12 Keygen to trade on the forex market.

      -

      What is Forex Killer and why do you need it?

      -

      Forex Killer is a stand-alone program that was developed by Andreas Kirchberger, a former forex advisor of Deutsche Bank. It is designed to help traders of all levels to make profitable trades on the forex market and other financial markets, such as stocks, commodities, and indices. Forex Killer works by analyzing the market data and generating signals that indicate when to buy or sell a currency pair. It also provides tools for managing your trades, such as stop loss, take profit, and trailing stop. Forex Killer claims to have a success rate of over 90% and to be able to generate up to $1000 per day.

      -

      Forex Killer 4.12 Keygenl


      Download Ziphttps://urlgoal.com/2uI9MH



      -

      Forex Killer is not a free software, however. It costs $89 to purchase and requires a serial number to activate. Without a valid serial number, you will not be able to use all the features of Forex Killer and you will be limited to a trial version that expires after 30 days. This is why some people look for ways to crack the software and get a free serial number.

      -

      What is a keygen and how does it work?

      -

      A keygen is a program that generates serial numbers or activation codes for software products that require them. A keygen works by mimicking the algorithm or formula that the original software uses to create valid serial numbers. By using a keygen, you can bypass the registration or activation process of the software and use it without paying for it.

      -

      -

      A keygen is usually created by hackers or crackers who reverse engineer the software code and find out how it generates serial numbers. They then write their own program that replicates this process and share it online for others to use. A keygen can be downloaded as a standalone file or as part of a crack package that also includes other tools for cracking software, such as patches, loaders, or cracks.

      -

      What are the benefits and risks of using a keygen for Forex Killer?

      -

      The main benefit of using a keygen for Forex Killer is that you can save money by not having to buy the software. You can also use all the features of Forex Killer without any limitations or expiration dates. You can enjoy the benefits of having a powerful forex trading software that can help you make money on the forex market.

      -

      However, using a keygen for Forex Killer also comes with some risks. First of all, using a keygen is illegal and unethical, as it violates the intellectual property rights of the software developer. You are essentially stealing their product and depriving them of their rightful income. You could face legal consequences if you are caught using a keygen for Forex Killer or any other software. Secondly, using a keygen is risky, as it could expose your computer to viruses, malware, or spyware. Keygens are often distributed by shady websites or sources that may contain malicious code or links. Downloading and running a keygen could infect your computer with harmful programs that could damage your system, steal your personal information, or compromise your security. You should always scan any file you download with a reliable antivirus software before opening it. Thirdly, using a keygen is unreliable, as it could cause problems with the software functionality or performance. Keygens are not guaranteed to work properly or to generate valid serial numbers. Sometimes, the keygen may fail to generate a serial number or generate an invalid one that the software rejects. Sometimes, the keygen may generate a serial number that works at first but stops working later due to updates or checks by the software. Sometimes, the keygen may generate a serial number that conflicts with another user's serial number and causes errors or crashes. Using a keygen could result in a poor user experience or even loss of data. Therefore, you should weigh the pros and cons of using a keygen for Forex Killer before deciding to use one. You should also be aware of the alternatives to using a keygen, such as buying the software legally, using a free trial version, or using a free or open source forex trading software.

      How to download and install Forex Killer 4.12 Keygen

      -

      If you have decided to use a keygen for Forex Killer, you will need to follow these steps to download and install it on your computer.

      -

      Step 1: Find a reliable source for the keygen

      -

      The first step is to find a reliable source for the keygen. As mentioned earlier, keygens are often distributed by shady websites or sources that may contain viruses or malware. You should avoid downloading keygens from unknown or untrusted sources. You should also avoid clicking on pop-up ads or banners that claim to offer free keygens or cracks for Forex Killer or any other software.

      -

      Instead, you should look for reputable websites or forums that specialize in software cracking or hacking. These websites or forums usually have reviews, ratings, comments, or feedback from other users who have used the keygens or cracks they offer. You should read these reviews carefully and look for positive feedback, high ratings, and verified downloads. You should also look for recent updates or versions of the keygens or cracks, as they may be more compatible with the latest version of Forex Killer.

      -

      Some examples of reliable sources for Forex Killer 4.12 Keygen are: - [Crack4Download]: This website offers various cracks and keygens for different software products, including Forex Killer 4.12 Keygen. It has a rating system and comments section where users can share their experiences and opinions about the cracks and keygens they download. - [CrackInn]: This website also offers various cracks and keygens for different software products, including Forex Killer 4.12 Keygen. It has a search function and categories where users can find the cracks and keygens they need. - [CrackSerialCodes]: This website provides serial numbers and activation codes for different software products, including Forex Killer 4.12 Keygen. It has a simple interface and easy navigation where users can find the serial numbers and activation codes they need.

      -

      These are just some examples of reliable sources for Forex Killer 4.12 Keygen. You can also search online for other sources that may suit your needs better.

      -

      Step 2: Download the keygen file and scan it for viruses

      -

      The next step is to download the keygen file from the source you have chosen. The keygen file is usually a small executable file (.exe) that you can run on your computer to generate a serial number for Forex Killer. The file name may vary depending on the source, but it usually contains the words "Forex Killer" and "Keygen" in some form.

      -

      Before you download the keygen file, you should make sure that you have enough space on your hard drive and that you have a stable internet connection. You should also disable any antivirus software or firewall that may block or interfere with the download process.

      -

      After you download the keygen file, you should scan it with a reliable antivirus software before opening it. As mentioned earlier, keygens may contain viruses or malware that could harm your computer or steal your information. You should never open a file that you have not scanned first.

      -

      If your antivirus software detects any threats in the keygen file, you should delete it immediately and look for another source. If your antivirus software does not detect any threats, you can proceed to the next step.

      -

      Step 3: Run the keygen program and generate a serial number

      -

      The third step is to run the keygen program and generate a serial number for Forex Killer. To do this, you should double-click on the keygen file or right-click on it and select "Run as administrator". This will open a window that shows the keygen interface.

      -

      The keygen interface may vary depending on the source, but it usually has a button or a field that says "Generate" or "Create". You should click on this button or field to generate a serial number for Forex Killer. The serial number will appear on the screen or on a text file that the keygen creates. You should copy this serial number and save it somewhere safe, such as a notepad or a word document.

      -

      You should also check if the keygen has any other options or features that you can use, such as changing the language, selecting the version, or checking for updates. You should use these options or features if they are available and if they suit your needs.

      -

      Step 4: Enter the serial number into Forex Killer and activate it

      -

      The final step is to enter the serial number into Forex Killer and activate it. To do this, you should first download and install Forex Killer from its official website or from another source. You should follow the instructions on how to install Forex Killer on your computer.

      -

      After you install Forex Killer, you should launch it and go to the registration or activation page. This page will ask you to enter your name, email address, and serial number. You should enter your name and email address as you wish, but you should enter the serial number that you generated from the keygen. You should then click on the button that says "Register" or "Activate".

      -

      This will activate Forex Killer and allow you to use all its features without any limitations or expiration dates. You should see a confirmation message that says "Registration successful" or "Activation successful". You can now start using Forex Killer to trade on the forex market.

      -

      How to use Forex Killer 4.12 to trade on the forex market

      -

      Now that you have activated Forex Killer with a keygen, you can use it to trade on the forex market and make money. Here are some steps on how to use Forex Killer 4.12 to trade on the forex market.

      -

      Step 1: Set up your trading account and preferences

      -

      The first step is to set up your trading account and preferences. Forex Killer is not a broker, but a signal generator. This means that you need to have a trading account with a broker that allows you to trade on the forex market. You can choose any broker that you prefer, as long as it is compatible with Forex Killer.

      -

      You should also set up your preferences in Forex Killer, such as your risk level, your trading style, your currency pairs, your time frame, and your stop loss and take profit levels. You can find these preferences in the settings or options menu of Forex Killer. You should adjust these preferences according to your goals, experience, and strategy.

      -

      Step 2: Analyze the market data and signals

      -

      The second step is to analyze the market data and signals. Forex Killer works by analyzing the market data and generating signals that indicate when to buy or sell a currency pair. You can get the market data from your broker or from another source, such as an online platform or a charting software.

      -

      You should import the market data into Forex Killer by clicking on the button that says "Import Data" or "Load Data". This will open a window that allows you to select the source, format, and period of the market data. You should select the appropriate options and click on "OK". This will load the market data into Forex Killer.

      -

      After loading the market data, you should click on the button that says "Calculate" or "Generate Signals". This will make Forex Killer analyze the market data and generate signals for trading. The signals will appear on the screen or on a text file that Forex Killer creates. The signals will show you the currency pair, the direction (buy or sell), the entry price, the stop loss price, and the take profit price. The signals will also show you the expected profit or loss per trade and the success rate of the signal.

      -

      You should analyze the signals and decide whether to follow them or not. You should consider factors such as the market conditions, the trend, the volatility, the news, and your own analysis. You should also compare the signals with other sources of information, such as indicators, patterns, or strategies. You should not blindly follow the signals, but use them as a guide or a confirmation for your own trading decisions.

      -

      Step 3: Place your orders and manage your trades

      -

      The third step is to place your orders and manage your trades. After deciding which signals to follow, you should place your orders with your broker. You can do this manually or automatically, depending on your preference and your broker's platform. You should enter the currency pair, the direction, the entry price, the stop loss price, and the take profit price as shown by the signal. You should also enter the amount or size of your trade, which depends on your risk management and money management rules.

      -

      After placing your orders, you should manage your trades according to the signal and your own judgment. You should monitor the market movements and the performance of your trades. You should also adjust your stop loss and take profit levels if necessary, to protect your profits or minimize your losses. You can use tools such as trailing stop or breakeven to automate this process. You should also close your trades when the signal changes or when you reach your target or limit.

      -

      Step 4: Review your performance and adjust your strategy

      -

      The final step is to review your performance and adjust your strategy. After closing your trades, you should evaluate the results and analyze the outcomes. You should record your trades and keep track of your profits and losses. You should also calculate your return on investment (ROI), your win rate, your risk-reward ratio, and other performance indicators.

      -

      You should review your performance and identify what worked well and what did not. You should also identify any mistakes or errors that you made and learn from them. You should also look for any patterns or trends that you can exploit or avoid in the future.

      -

      You should adjust your strategy based on your performance and feedback. You should fine-tune your preferences in Forex Killer, such as your risk level, your trading style, your currency pairs, your time frame, and your stop loss and take profit levels. You should also test different settings and options to see which ones work best for you. You should also update Forex Killer regularly to get the latest version and features.

      -

      Conclusion

      -

      Summary of the main points

      -

      In this article, we have shown you how to download, install, and use Forex Killer 4.12 Keygen to trade on the forex market. We have explained what Forex Killer is and why you need it, what a keygen is and how it works, what are the benefits and risks of using a keygen for Forex Killer, how to download and install Forex Killer 4.12 Keygen, how to use Forex Killer 4.12 to trade on the forex market, and how to review your performance and adjust your strategy.

      -

      Call to action and disclaimer

      -

      If you are interested in using Forex Killer 4.12 Keygen to trade on the forex market, you can follow the steps we have outlined in this article. However, you should be aware of the legal, ethical, and technical implications of using a keygen for Forex Killer or any other software. You should also be aware of the alternatives to using a keygen, such as buying Forex Killer legally, using a free trial version, or using a free or open source forex trading software.

      -

      We hope that this article has been helpful and informative for you. However, we do not endorse or recommend using a keygen for Forex Killer or any other software. We do not take any responsibility for any consequences that may arise from using a keygen for Forex Killer or any other software. Trading on the forex market involves high risks and is not suitable for everyone. You should only trade with money that you can afford to lose. You should also do your own research and analysis before making any trading decisions.

      -

      FAQs

      -

      What is Forex Killer?

      -

      Forex Killer is a stand-alone program that generates signals for trading on the forex market and other financial markets.

      -

      What is a keygen?

      -

      A keygen is a program that generates serial numbers or activation codes for software products that require them.

      -

      What are the benefits of using a keygen for Forex Killer?

      -

      The benefits of using a keygen for Forex Killer are that you can save money by not having to buy the software, and you can use all the features of Forex Killer without any limitations or expiration dates.

      -

      What are the risks of using a keygen for Forex Killer?

      -

      The risks of using a keygen for Forex Killer are that you could face legal consequences, expose your computer to viruses or malware, or cause problems with the software functionality or performance.

      -

      How to download and install Forex Killer 4.12 Keygen?

      -

      To download and install Forex Killer 4.12 Keygen, you need to find a reliable source for the keygen, download the keygen file and scan it for viruses, run the keygen program and generate a serial number, and enter the serial number into Forex Killer and activate it.

      -

      How to use Forex Killer 4.12 to trade on the forex market?

      -

      To use Forex Killer 4.12 to trade on the forex market, you need to set up your trading account and preferences, analyze the market data and signals, place your orders and manage your trades, and review your performance and adjust your strategy.

      b2dd77e56b
      -
      -
      \ No newline at end of file diff --git a/spaces/subwayman/btc-chat-bot/document_processor.py b/spaces/subwayman/btc-chat-bot/document_processor.py deleted file mode 100644 index ee4b88f9a27ea8337f70f1b32879cd950d214ae5..0000000000000000000000000000000000000000 --- a/spaces/subwayman/btc-chat-bot/document_processor.py +++ /dev/null @@ -1,48 +0,0 @@ -import os -import re - - -def is_jang(line): - pattern = r"제\d{1,2}장" - match = re.search(pattern, line) - if match: - return line - return None - - -def is_jo(line): - pattern = r"제\d{1,2}조" - match = re.search(pattern, line) - if match: - return match.group() - return None - - -def process_text_document(filepath): - jang_info = '' - result = '***' - delim = '*****\n' - filename = os.path.basename(filepath).split('.')[0] - dirname = 'docs' - - with open(filepath, "r") as f: - for line in f: - jang_info = is_jang(line) if is_jang(line) else jang_info - # 새로운 장이면 기억하고 있다가 조 앞에 붙인다. - # 이번 줄이 새로운 조항이면 앞에 델림을 삽입하고, 장 정보를 삽입한 뒤 - # 리절트에 이어붙인다. - if is_jo(line): - result += delim + jang_info - # 노이즈가 될수 있는 괄호안의 정보는 제거한다. - result += re.sub(r"<.*?>|\[.*?\]", "", line) - - with open(os.path.join(dirname, 'processed', filename + '_processed.txt'), 'w') as f: - f.write(result) - - -if __name__ == '__main__': - # potential path bug exists - for f in os.listdir(os.getcwd() + '/docs'): - if f.endswith('.txt'): - print(f) - process_text_document(os.path.join(os.getcwd() + '/docs', f)) diff --git a/spaces/supertori/files/stable-diffusion-webui/modules/interrogate.py b/spaces/supertori/files/stable-diffusion-webui/modules/interrogate.py deleted file mode 100644 index 236abe516c8783824b6aecaae188a31cfa17f75c..0000000000000000000000000000000000000000 --- a/spaces/supertori/files/stable-diffusion-webui/modules/interrogate.py +++ /dev/null @@ -1,227 +0,0 @@ -import os -import sys -import traceback -from collections import namedtuple -from pathlib import Path -import re - -import torch -import torch.hub - -from torchvision import transforms -from torchvision.transforms.functional import InterpolationMode - -import modules.shared as shared -from modules import devices, paths, shared, lowvram, modelloader, errors - -blip_image_eval_size = 384 -clip_model_name = 'ViT-L/14' - -Category = namedtuple("Category", ["name", "topn", "items"]) - -re_topn = re.compile(r"\.top(\d+)\.") - -def category_types(): - return [f.stem for f in Path(shared.interrogator.content_dir).glob('*.txt')] - - -def download_default_clip_interrogate_categories(content_dir): - print("Downloading CLIP categories...") - - tmpdir = content_dir + "_tmp" - category_types = ["artists", "flavors", "mediums", "movements"] - - try: - os.makedirs(tmpdir) - for category_type in category_types: - torch.hub.download_url_to_file(f"https://raw.githubusercontent.com/pharmapsychotic/clip-interrogator/main/clip_interrogator/data/{category_type}.txt", os.path.join(tmpdir, f"{category_type}.txt")) - os.rename(tmpdir, content_dir) - - except Exception as e: - errors.display(e, "downloading default CLIP interrogate categories") - finally: - if os.path.exists(tmpdir): - os.remove(tmpdir) - - -class InterrogateModels: - blip_model = None - clip_model = None - clip_preprocess = None - dtype = None - running_on_cpu = None - - def __init__(self, content_dir): - self.loaded_categories = None - self.skip_categories = [] - self.content_dir = content_dir - self.running_on_cpu = devices.device_interrogate == torch.device("cpu") - - def categories(self): - if not os.path.exists(self.content_dir): - download_default_clip_interrogate_categories(self.content_dir) - - if self.loaded_categories is not None and self.skip_categories == shared.opts.interrogate_clip_skip_categories: - return self.loaded_categories - - self.loaded_categories = [] - - if os.path.exists(self.content_dir): - self.skip_categories = shared.opts.interrogate_clip_skip_categories - category_types = [] - for filename in Path(self.content_dir).glob('*.txt'): - category_types.append(filename.stem) - if filename.stem in self.skip_categories: - continue - m = re_topn.search(filename.stem) - topn = 1 if m is None else int(m.group(1)) - with open(filename, "r", encoding="utf8") as file: - lines = [x.strip() for x in file.readlines()] - - self.loaded_categories.append(Category(name=filename.stem, topn=topn, items=lines)) - - return self.loaded_categories - - def create_fake_fairscale(self): - class FakeFairscale: - def checkpoint_wrapper(self): - pass - - sys.modules["fairscale.nn.checkpoint.checkpoint_activations"] = FakeFairscale - - def load_blip_model(self): - self.create_fake_fairscale() - import models.blip - - files = modelloader.load_models( - model_path=os.path.join(paths.models_path, "BLIP"), - model_url='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth', - ext_filter=[".pth"], - download_name='model_base_caption_capfilt_large.pth', - ) - - blip_model = models.blip.blip_decoder(pretrained=files[0], image_size=blip_image_eval_size, vit='base', med_config=os.path.join(paths.paths["BLIP"], "configs", "med_config.json")) - blip_model.eval() - - return blip_model - - def load_clip_model(self): - import clip - - if self.running_on_cpu: - model, preprocess = clip.load(clip_model_name, device="cpu", download_root=shared.cmd_opts.clip_models_path) - else: - model, preprocess = clip.load(clip_model_name, download_root=shared.cmd_opts.clip_models_path) - - model.eval() - model = model.to(devices.device_interrogate) - - return model, preprocess - - def load(self): - if self.blip_model is None: - self.blip_model = self.load_blip_model() - if not shared.cmd_opts.no_half and not self.running_on_cpu: - self.blip_model = self.blip_model.half() - - self.blip_model = self.blip_model.to(devices.device_interrogate) - - if self.clip_model is None: - self.clip_model, self.clip_preprocess = self.load_clip_model() - if not shared.cmd_opts.no_half and not self.running_on_cpu: - self.clip_model = self.clip_model.half() - - self.clip_model = self.clip_model.to(devices.device_interrogate) - - self.dtype = next(self.clip_model.parameters()).dtype - - def send_clip_to_ram(self): - if not shared.opts.interrogate_keep_models_in_memory: - if self.clip_model is not None: - self.clip_model = self.clip_model.to(devices.cpu) - - def send_blip_to_ram(self): - if not shared.opts.interrogate_keep_models_in_memory: - if self.blip_model is not None: - self.blip_model = self.blip_model.to(devices.cpu) - - def unload(self): - self.send_clip_to_ram() - self.send_blip_to_ram() - - devices.torch_gc() - - def rank(self, image_features, text_array, top_count=1): - import clip - - devices.torch_gc() - - if shared.opts.interrogate_clip_dict_limit != 0: - text_array = text_array[0:int(shared.opts.interrogate_clip_dict_limit)] - - top_count = min(top_count, len(text_array)) - text_tokens = clip.tokenize([text for text in text_array], truncate=True).to(devices.device_interrogate) - text_features = self.clip_model.encode_text(text_tokens).type(self.dtype) - text_features /= text_features.norm(dim=-1, keepdim=True) - - similarity = torch.zeros((1, len(text_array))).to(devices.device_interrogate) - for i in range(image_features.shape[0]): - similarity += (100.0 * image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1) - similarity /= image_features.shape[0] - - top_probs, top_labels = similarity.cpu().topk(top_count, dim=-1) - return [(text_array[top_labels[0][i].numpy()], (top_probs[0][i].numpy()*100)) for i in range(top_count)] - - def generate_caption(self, pil_image): - gpu_image = transforms.Compose([ - transforms.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=InterpolationMode.BICUBIC), - transforms.ToTensor(), - transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) - ])(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate) - - with torch.no_grad(): - caption = self.blip_model.generate(gpu_image, sample=False, num_beams=shared.opts.interrogate_clip_num_beams, min_length=shared.opts.interrogate_clip_min_length, max_length=shared.opts.interrogate_clip_max_length) - - return caption[0] - - def interrogate(self, pil_image): - res = "" - shared.state.begin() - shared.state.job = 'interrogate' - try: - if shared.cmd_opts.lowvram or shared.cmd_opts.medvram: - lowvram.send_everything_to_cpu() - devices.torch_gc() - - self.load() - - caption = self.generate_caption(pil_image) - self.send_blip_to_ram() - devices.torch_gc() - - res = caption - - clip_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate) - - with torch.no_grad(), devices.autocast(): - image_features = self.clip_model.encode_image(clip_image).type(self.dtype) - - image_features /= image_features.norm(dim=-1, keepdim=True) - - for name, topn, items in self.categories(): - matches = self.rank(image_features, items, top_count=topn) - for match, score in matches: - if shared.opts.interrogate_return_ranks: - res += f", ({match}:{score/100:.3f})" - else: - res += ", " + match - - except Exception: - print("Error interrogating", file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - res += "" - - self.unload() - shared.state.end() - - return res diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Photoscore Ultimate 7 Crack Keygen Microsoft EXCLUSIVE.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Photoscore Ultimate 7 Crack Keygen Microsoft EXCLUSIVE.md deleted file mode 100644 index 8d5a8cabfcf92c61d5c4c3dd418223aeae4ce41b..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Photoscore Ultimate 7 Crack Keygen Microsoft EXCLUSIVE.md +++ /dev/null @@ -1,6 +0,0 @@ -

      photoscore ultimate 7 crack keygen microsoft


      Download Zip ✫✫✫ https://cinurl.com/2uEXuy



      - -Click Title for torrent norCTrack Korg Kronos [KONTAKT] | 76. 94 offers ... plus licensed Sibelius-style editing interfaces, PhotoScore & NotateMe Ultimate even. 4d29de3e1b
      -
      -
      -

      diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Resident Evil 6 Pc Game Full Cracked Password _BEST_.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Resident Evil 6 Pc Game Full Cracked Password _BEST_.md deleted file mode 100644 index 7c5ca57f3ebcd27e2a8c89c179f4c02269bc0235..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Resident Evil 6 Pc Game Full Cracked Password _BEST_.md +++ /dev/null @@ -1,8 +0,0 @@ -
      -

      resident evil 6 is an action adventure horror video game that was developed by capcom and was released on september 2014 for microsoft windows, playstation 3, and xbox 360. this game is an evolution of the popular resident evil series, and adds an element of a realistic open world gameplay, as well as several new elements.

      -

      this game takes place in an authentic depiction of raccoon city, an area in the southeastern region of the united states of america, in which a series of bizarre and deadly events occurred. the game is set in the year 2027, after the events of the main series resident evil 5 and resident evil: the mercenaries 3d, but several years before those of the resident evil 4.

      -

      Resident Evil 6 Pc Game Full Cracked Password


      Download File ✒ ✒ ✒ https://cinurl.com/2uEX4f



      -

      in a world infected by the t-virus, a man named leon s. kennedy, becomes the leader of a special unit called “biohazard,” responsible for dealing with the outbreak of the t-virus in raccoon city. in resident evil 6, resident evil fans will experience all the horror, action and fear of the popular resident evil series in a completely new way. this is a game for people who are not afraid to explore a scary world. this game lets you face your fears in a terrifyingly alive way.

      -

      resident evil 6 is the sixth main installment in the popular resident evil series. raccoon city is still in a state of panic after the events of resident evil 5, but leon s. kennedy, a former special forces agent, is still running the biohazard unit. as leon, you will be leading your team, called biohazard, to find the t-virus. along the way, you will encounter new and familiar enemies.

      899543212b
      -
      -
      \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/[PC-Game] Nina Agent Chronicles 2003 Download For Computer.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/[PC-Game] Nina Agent Chronicles 2003 Download For Computer.md deleted file mode 100644 index 20a7204d9104aa921ad5c9ded6d6a4b5572755a7..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/[PC-Game] Nina Agent Chronicles 2003 Download For Computer.md +++ /dev/null @@ -1,13 +0,0 @@ - -

      Nina Agent Chronicles 2003: A Classic Action-Adventure Game for PC

      -

      If you are looking for a retro game that combines brainpower and firepower, you might want to check out Nina Agent Chronicles 2003, a first-person shooter game developed by Polish studio Detalion and released by Lemon Interactive in 2002. In this game, you play as Nina, a top model who works for an anti-terrorist organization and has the paranormal ability to take over the minds of other people. You will face many puzzles and tasks as you guide Nina on her missions in a hidden city in the mountains of Afghanistan.

      -

      [PC-Game] Nina Agent Chronicles 2003 download for computer


      Download Filehttps://cinurl.com/2uEYYz



      -

      Nina Agent Chronicles 2003 is a low-budget game that features eye-catching graphics created with Lithtech Talon engine, an absorbing adventure plot and storyline, and a special ethnic and adrenaline rush techno music. The game was praised by some critics for its originality and atmosphere, but criticized by others for its poor gameplay, voice acting, and difficulty. The game has a cult following among some fans of old-school action-adventure games.

      -

      If you want to download Nina Agent Chronicles 2003 for your computer, you can find it on several websites that offer DRM-free games for PC. Some of these websites are My Abandonware[^1^], Gamepressure[^2^], Archive[^4^], and GamersGate[^5^]. You can also watch a walkthrough of the game on YouTube[^3^] to get a glimpse of what the game is like. Nina Agent Chronicles 2003 is a game that might not appeal to everyone, but it is definitely worth a try if you are looking for something different and challenging.

      - -

      Nina Agent Chronicles 2003 is not a typical first-person shooter game. It has some elements of stealth, puzzle-solving, and exploration that make it more varied and interesting. You can use Nina's mind control ability to take over enemies and use their weapons and skills. You can also interact with various objects and devices in the environment to solve puzzles and unlock new areas. The game has four levels, each with a different setting and theme. You will encounter different enemies, such as terrorists, mutants, robots, and ninjas.

      -

      -

      However, Nina Agent Chronicles 2003 also has some flaws that might frustrate some players. The game has a low level of polish and quality, with some bugs, glitches, and crashes. The game also has a very high difficulty level, with limited save points, scarce ammo and health packs, and unforgiving enemies. The game does not have a tutorial or a manual, so you have to figure out everything by yourself. The game also has some cheesy voice acting and dialogues that might make you cringe or laugh.

      -

      Nina Agent Chronicles 2003 is a game that has some potential and charm, but also some problems and limitations. It is a game that you might love or hate, depending on your taste and patience. It is a game that offers a unique and challenging experience, but also a frustrating and disappointing one. It is a game that deserves some recognition and respect, but also some criticism and improvement. It is a game that you should try at your own risk.

      d5da3c52bf
      -
      -
      \ No newline at end of file diff --git a/spaces/suvradip2000/space1/app/templates/face_recognition.html b/spaces/suvradip2000/space1/app/templates/face_recognition.html deleted file mode 100644 index 415e8deb0ed5e694df75477163c87e1f47752e90..0000000000000000000000000000000000000000 --- a/spaces/suvradip2000/space1/app/templates/face_recognition.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - Index - - -
      -

      -
      Face Recognition
      -

      -
      -
      -
      -
        - -
        -
        - Upload Image:

        - -


        - -
        - -

        -
        - -
        -
      -
      -
      - - diff --git a/spaces/szzzzz/sentiment_classification/README.md b/spaces/szzzzz/sentiment_classification/README.md deleted file mode 100644 index 03a482cbb128e798a49fb7f8cee6a1ffea128133..0000000000000000000000000000000000000000 --- a/spaces/szzzzz/sentiment_classification/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Sentiment Classification -emoji: 👀 -colorFrom: blue -colorTo: purple -sdk: gradio -sdk_version: 3.21.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/tarun52/sentiment/app.py b/spaces/tarun52/sentiment/app.py deleted file mode 100644 index daeb69ca5ad08c4b16a1e2ae4726340568bb04da..0000000000000000000000000000000000000000 --- a/spaces/tarun52/sentiment/app.py +++ /dev/null @@ -1,40 +0,0 @@ -import gradio as gr -from transformers import AutoModelForSequenceClassification -from transformers import AutoTokenizer, AutoConfig -from scipy.special import softmax - - -def check_sentiment(text): - - task='sentiment' - MODEL = f"cardiffnlp/twitter-roberta-base-{task}" - - tokenizer = AutoTokenizer.from_pretrained(MODEL) - model = AutoModelForSequenceClassification.from_pretrained(MODEL) - model.save_pretrained(MODEL) - tokenizer.save_pretrained(MODEL) - - encoded_input = tokenizer(text, return_tensors='pt') - output = model(**encoded_input) - scores = output[0][0].detach().numpy() - scores = softmax(scores) - - - d = {} - lbl = ["Negative", "Neutral","Positive"] - for i in range(3): - d[lbl[i]] = scores[i] - - Keymax = max(zip(d.values(), d.keys()))[1] - return Keymax - - - -def main(): - iface = gr.Interface(fn=check_sentiment, inputs="text", outputs="text") - iface.launch() - - -if __name__ == "__main__": - main() - diff --git a/spaces/tellview/suno-bark/README.md b/spaces/tellview/suno-bark/README.md deleted file mode 100644 index ec109958a21cc613fbc4341ffb52956120bb1458..0000000000000000000000000000000000000000 --- a/spaces/tellview/suno-bark/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Suno Bark -emoji: 👁 -colorFrom: gray -colorTo: indigo -sdk: gradio -sdk_version: 3.37.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/terfces0erbo/CollegeProjectV2/Constantine 2005 720P Bluray X264 Mgb.md b/spaces/terfces0erbo/CollegeProjectV2/Constantine 2005 720P Bluray X264 Mgb.md deleted file mode 100644 index 71b5719871cde35e7964ca853862f593d55df849..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Constantine 2005 720P Bluray X264 Mgb.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Constantine 2005 720P Bluray X264 Mgb


      Download > https://bytlly.com/2uGk4F



      -
      -Farsi/Persian Constantine.2005.All.BluRay.480p.720p.1080p, M0H4MM4D.A.H ... BluRay.x264.-MgB; aConstantine.2005.720p.BluRay.DTS.x264-CtrlHD ... 1fdad05405
      -
      -
      -

      diff --git a/spaces/terfces0erbo/CollegeProjectV2/CyberGhost VPN 7.3.9 Crack Keygen Full Version 2020 !EXCLUSIVE!.md b/spaces/terfces0erbo/CollegeProjectV2/CyberGhost VPN 7.3.9 Crack Keygen Full Version 2020 !EXCLUSIVE!.md deleted file mode 100644 index d865bfd9fda503b6c478caac2a77130e9651f50b..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/CyberGhost VPN 7.3.9 Crack Keygen Full Version 2020 !EXCLUSIVE!.md +++ /dev/null @@ -1,6 +0,0 @@ -

      CyberGhost VPN 7.3.9 Crack Keygen Full Version 2020


      Download ►►►►► https://bytlly.com/2uGlmU



      -
      -9/10 (17 valutazioni) - Download Cyberghost VPN gratis. Cyberghost VPN ti offre un servizio di VPN che ti permette di navigare in anonimato, con la tua privacy ... Tuttavia, è consigliabile ottenere la versione full dell'applicazione, con tutte le caratteristiche che non troverai in quella gratuita. ... Copyright 2020 Malavida. 4d29de3e1b
      -
      -
      -

      diff --git a/spaces/terfces0erbo/CollegeProjectV2/Dasardasarekonometrikapdf.md b/spaces/terfces0erbo/CollegeProjectV2/Dasardasarekonometrikapdf.md deleted file mode 100644 index d6e121e3e26057837fcf0635b2571cd907c2a295..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Dasardasarekonometrikapdf.md +++ /dev/null @@ -1,6 +0,0 @@ -

      dasardasarekonometrikapdf


      Download Filehttps://bytlly.com/2uGk6G



      - - 3cee63e6c2
      -
      -
      -

      diff --git a/spaces/tharunayak14/Text-Summarization/README.md b/spaces/tharunayak14/Text-Summarization/README.md deleted file mode 100644 index e9954ec0f34b6789acc0ab28444ba5e8d3851769..0000000000000000000000000000000000000000 --- a/spaces/tharunayak14/Text-Summarization/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Text Summarization -emoji: 👁 -colorFrom: gray -colorTo: red -sdk: gradio -sdk_version: 3.38.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/thejagstudio/procom/croma/__init__.py b/spaces/thejagstudio/procom/croma/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/themanas021/falcon-legal/app.py b/spaces/themanas021/falcon-legal/app.py deleted file mode 100644 index 668b19e4220ccdea5dbe5c20e6b1962fba0b1d9f..0000000000000000000000000000000000000000 --- a/spaces/themanas021/falcon-legal/app.py +++ /dev/null @@ -1,58 +0,0 @@ -import streamlit as st -from langchain import PromptTemplate -from langchain.chains import LLMChain -from langchain.llms import HuggingFaceHub -import os - -os.environ['OPENAI_API_KEY'] = '' -os.environ['HUGGINGFACEHUB_API_TOKEN'] = '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' -# Import your model and template -llm_hf = HuggingFaceHub( - repo_id="tiiuae/falcon-7b-instruct", - model_kwargs={"temperature": 0.3} -) - -restaurant_template = """ -I want you to become an indian lawyer and enlist me the acts and rights with a one liner description, for every issue i'll raise, you've to only give me relevant acts and rights coving from that issue for example: -The Indian Contract Act, 1872: This act governs the basic principles of contract law, which includes rent agreements. It sets the legal framework for agreements and their enforceability. - -The Rent Control Act (varies by state): Different Indian states have their own Rent Control Acts that regulate rent agreements, rent control, and tenant-landlord relationships. You should consult the specific Rent Control Act relevant to your location for details. - -Right to Property: As per the Indian Constitution, the right to property is a fundamental right, but it's not absolute. You have the right to enjoy your property and enter into agreements, including rent agreements, as long as it is in compliance with the law. - -Tenant's Rights: Tenants in India also have rights, such as the right to peaceful enjoyment of the rented premises, right to a fair and reasonable rent, and right to notice for eviction. These rights may vary by state. -etc. -you've to answer me like this for every issue i'll raise, -here's the example issue: -{issue} -""" - -# Define the Streamlit app -def main(): - st.title("Indian Legal Consultation") - - # Input for the user's issue - description = st.text_area("Please describe your issue:") - - if st.button("Get Legal Advice"): - if description: - # Create a PromptTemplate - prompt = PromptTemplate( - input_variables=["issue"], - template=restaurant_template, - ) - - # Create an LLMChain - chain = LLMChain(llm=llm_hf, prompt=prompt) - - # Generate a response - response = chain.run(description) - - # Display the response - st.subheader("Legal Advice:") - st.write(response) - else: - st.warning("Please provide a description of your issue.") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Happy To Be Nappy (Board Book) Happy To Be Nappy Books Pdf File __FULL__.md b/spaces/tialenAdioni/chat-gpt-api/logs/Happy To Be Nappy (Board Book) Happy To Be Nappy Books Pdf File __FULL__.md deleted file mode 100644 index 78e53fecb25da9f70047f76315d88912200f0c71..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Happy To Be Nappy (Board Book) Happy To Be Nappy Books Pdf File __FULL__.md +++ /dev/null @@ -1,16 +0,0 @@ -
      -

      Happy to Be Nappy: A Picture Book Celebrating Hair Diversity

      -

      Happy to Be Nappy is a picture book by legendary author bell hooks and multi-Caldecott Medalist Chris Raschka that celebrates hair diversity, especially among African American girls. The book was first published in 1999 by Hyperion Books for Children and was nominated for an NAACP Image Award. It is now available in a board book edition for younger readers.

      -

      Happy to Be Nappy (Board Book) Happy to Be Nappy books pdf file


      DOWNLOAD ✺✺✺ https://urlcod.com/2uKamx



      -

      The book features colorful illustrations by Raschka that depict various hairstyles and textures of nappy hair, from short and strong to twisty and curly. The text by hooks is a lyrical poem that expresses the joy and beauty of nappy hair, as well as the affirmation and empowerment that comes from loving one's natural hair. The book also challenges the negative stereotypes and stigma that are often associated with nappy hair in mainstream culture.

      -

      Happy to Be Nappy is a fun and uplifting read aloud that celebrates the diversity and uniqueness of girls and their hair. It is a book that encourages self-love, self-esteem, and self-expression among young readers of all backgrounds and hair types. It is also a book that promotes social justice and racial equality by honoring the history and culture of African Americans through their hair.

      -

      To download a pdf file of Happy to Be Nappy (Board Book) Happy to Be Nappy, you can visit the Internet Archive website[^2^] where you can find a free digital copy of the book. You can also purchase a hardcover or board book edition of the book from Amazon[^1^] or Google Books[^3^].

      -

      - -

      Happy to Be Nappy is not only a picture book, but also a cultural phenomenon that has inspired many other books, songs, and movements that celebrate natural hair. Some examples of these are Hair Love by Matthew A. Cherry and Vashti Harrison, I Love My Hair by Natasha Anastasia Tarpley and E.B. Lewis, Nappy Hair by Carolivia Herron and Joe Cepeda, and the Nappy Roots rap group. These works all share the same message of embracing one's identity and heritage through one's hair.

      -

      Happy to Be Nappy is also a book that can spark meaningful conversations among parents, teachers, and children about the history and politics of hair in the African American community. The book can help readers understand the struggles and achievements of black people who have faced discrimination and oppression because of their hair. The book can also help readers appreciate the diversity and creativity of black people who have expressed their culture and personality through their hair.

      -

      Happy to Be Nappy is a book that every child should read and enjoy. It is a book that celebrates the beauty and power of nappy hair. It is a book that says: Happy to be nappy hair! Just all girl happy! Happy to be me!

      - -

      In conclusion, Happy to Be Nappy is a picture book that celebrates hair diversity, especially among African American girls. It is a book that features a lyrical poem by bell hooks and colorful illustrations by Chris Raschka that depict various hairstyles and textures of nappy hair. It is a book that expresses the joy and beauty of nappy hair, as well as the affirmation and empowerment that comes from loving one's natural hair. It is a book that challenges the negative stereotypes and stigma that are often associated with nappy hair in mainstream culture. It is a book that promotes social justice and racial equality by honoring the history and culture of African Americans through their hair. It is a book that every child should read and enjoy. It is a book that says: Happy to be nappy hair! Just all girl happy! Happy to be me!

      e93f5a0c3f
      -
      -
      \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Infinite Flight Simulator for Android - The Most Comprehensive Flight Simulation Experience on Mobile Devices.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Infinite Flight Simulator for Android - The Most Comprehensive Flight Simulation Experience on Mobile Devices.md deleted file mode 100644 index ba6319599fa78d661a6f9fece4357333cd99cfa8..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Infinite Flight Simulator for Android - The Most Comprehensive Flight Simulation Experience on Mobile Devices.md +++ /dev/null @@ -1,148 +0,0 @@ -
      -

      Infinite Flight Simulator APK Download Android: A Comprehensive Guide

      -

      If you are looking for a realistic and immersive flight simulation experience on your mobile device, you might want to check out Infinite Flight Simulator. This game offers you the opportunity to fly dozens of aircraft in various regions of the world, with realistic weather, navigation, and physics. You can also join thousands of other pilots and air traffic controllers in the online multiplayer mode, or fly solo with the advanced replay system. In this article, we will show you how to download and install Infinite Flight Simulator APK on your Android device, as well as the features, pros and cons, user reviews, and FAQs of this game.

      -

      infinite flight simulator apk download android


      DOWNLOADhttps://bltlly.com/2uOncx



      -

      What is Infinite Flight Simulator?

      -

      Infinite Flight Simulator is a flight simulation game developed by Infinite Flight LLC, a company founded by two aviation enthusiasts in 2011. The game was first released for iOS devices in 2012, and later for Android devices in 2014. Since then, the game has been updated regularly with new features, aircraft, regions, and improvements.

      -

      Infinite Flight Simulator aims to provide the most comprehensive flight simulation experience on mobile devices, whether you are a curious novice or a decorated pilot. You can explore high definition scenery in regions from around the world with a diverse inventory of detailed aircraft, tailoring each flight by choosing your time of day, weather conditions, and aircraft weight configuration. You can also use real-world navigation data, including airspaces, NAVAIDs, SIDs, STARs, and approaches, furnished by NavBlue (an Airbus Company). You can also customize your flight plan with accurate fixes and navigational aids.

      -

      Features of Infinite Flight Simulator

      -

      Some of the features that make Infinite Flight Simulator stand out from other flight simulation games are:

      -
        -
      • Dozens of aircraft in a diverse fleet of airliners, general aviation and military aircraft (subscribe to Infinite Flight Pro to unlock all aircraft)
      • -
      • Multiple regions featuring high definition satellite imagery, accurate topography and all major airports with precise runway and taxiway layouts
      • -
      • Growing list of 3D airports around the world
      • -
      • Real-world navigation data including airspaces, NAVAIDs, SIDs, STARs, and approaches, furnished by NavBlue (an Airbus Company)
      • -
      • Customizable time of day and weather conditions (real-time or custom)
      • -
      • Realistic atmospherics with the sun, moon, stars, clouds, and low-level fog
      • -
      • Autopilot (supports control of all flight parameters, NAV mode to follow your flight plan, and auto land on select aircraft)
      • -
      • Easy-to-use flight planning system with accurate fixes and Navigational Aids
      • -
      • Engine startup and shutdown
      • -
      • Instrument Landing System (ILS)
      • -
      • Advanced replay system
      • -
      • Weight and balance configuration
      • -
      • Aircraft cockpit and door animations, suspension animations, and wing flex, on select aircraft.
      • -
      -

      How to download and install Infinite Flight Simulator APK on Android

      -

      If you want to download and install Infinite Flight Simulator APK on your Android device, you can follow these simple steps:

      -

      infinite flight simulator apk free download for android
      -infinite flight simulator mod apk download android
      -infinite flight simulator apk full version download android
      -infinite flight simulator apk download latest version android
      -infinite flight simulator apk download android 1
      -infinite flight simulator apk download android 2023
      -infinite flight simulator apk download android offline
      -infinite flight simulator apk download android uptodown
      -infinite flight simulator apk download android rexdl
      -infinite flight simulator apk download android revdl
      -infinite flight simulator apk download android apkpure
      -infinite flight simulator apk download android aptoide
      -infinite flight simulator apk download android apkcombo
      -infinite flight simulator apk download android mob.org
      -infinite flight simulator apk download android modded
      -infinite flight simulator apk download android unlimited money
      -infinite flight simulator apk download android unlocked planes
      -infinite flight simulator apk download android all aircrafts
      -infinite flight simulator apk download android pro subscription
      -infinite flight simulator apk download android multiplayer mode
      -infinite flight simulator apk download android no root
      -infinite flight simulator apk download android obb data
      -infinite flight simulator apk download android highly compressed
      -infinite flight simulator apk download android hack version
      -infinite flight simulator apk download android cheat codes
      -infinite flight simulator apk download android gameplay video
      -infinite flight simulator apk download android review ratings
      -infinite flight simulator apk download android system requirements
      -infinite flight simulator apk download android installation guide
      -infinite flight simulator apk download android troubleshooting tips
      -infinite flight simulator apk download android update news
      -infinite flight simulator apk download android new features
      -infinite flight simulator apk download android best settings
      -infinite flight simulator apk download android realistic graphics
      -infinite flight simulator apk download android 3d airports
      -infinite flight simulator apk download android real-world navigation data
      -infinite flight simulator apk download android custom weather conditions
      -infinite flight simulator apk download android advanced replay system
      -infinite flight simulator apk download android instrument landing system (ILS)
      -infinite flight simulator apk download android easy-to-use flight planning system
      -infinite flight simulator apk download android engine startup and shutdown
      -infinite flight simulator apk download android aircraft cockpit and door animations
      -infinite flight simulator apk download android suspension animations and wing flex
      -infinite flight simulator apk download android global multiplayer experience
      -infinite flight simulator apk download android live weather and winds aloft
      -infinite flight simulator apk download android air traffic controller roleplay (ATC)
      -infinite flight simulator apk download android diverse fleet of airliners, general aviation and military aircrafts

      -
        -
      1. Go to APKCombo or Aptoide, two trusted sources for downloading APK files.
      2. -
      3. Search for "Infinite Flight Simulator" in the search bar.
      4. -
      5. Select the latest version of the game (23.2.1 as of June 2023), and tap on the download button.
      6. -
      7. Wait for the download to finish, and then open the APK file.
      8. -
      9. If you see a warning message that says "For your security, your phone is not allowed to install unknown apps from this source", go to your device settings and enable the option to install apps from unknown sources.
      10. -
      11. Follow the instructions on the screen to install the game on your device.
      12. -
      13. Launch the game and enjoy flying!
      14. -
      -

      Note: You may need to purchase a subscription to Infinite Flight Pro to access all the features and content of the game. You can choose from monthly, 6-month, or annual plans, depending on your preference and budget. You can also cancel your subscription at any time.

      -

      Why choose Infinite Flight Simulator?

      -

      Infinite Flight Simulator is not just another flight simulation game. It is a game that strives to provide the most realistic and immersive flight simulation experience on mobile devices. Whether you are a beginner or an expert, you will find something to enjoy and learn from this game. Here are some of the reasons why you should choose Infinite Flight Simulator:

      -

      Pros and cons of Infinite Flight Simulator

      -

      Like any other game, Infinite Flight Simulator has its pros and cons. Here are some of them:

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      ProsCons
      - High-quality graphics and sound effects- Requires a lot of storage space and battery power
      - Realistic flight physics and controls- Some features and content require a subscription
      - Diverse and detailed aircraft and regions- May encounter bugs and glitches occasionally
      - Real-world navigation data and weather conditions- May not work well on older or low-end devices
      - Online multiplayer mode with live ATC and voice chat- May experience lag or connection issues in online mode
      - Advanced replay system and flight planning system- May not support some devices or operating systems
      - Frequent updates and improvements- May have compatibility issues with some APK files or sources
      -

      User reviews and ratings of Infinite Flight Simulator

      -

      Infinite Flight Simulator has received mostly positive reviews and ratings from users who have downloaded and played the game. On Google Play Store, the game has a rating of 4.2 out of 5 stars, based on over 100,000 reviews. On App Store, the game has a rating of 4.6 out of 5 stars, based on over 30,000 reviews. Here are some of the comments from users who have enjoyed the game:

      -
      "This is by far the best flight simulator I have ever played on mobile. The graphics are amazing, the physics are realistic, and the online mode is awesome. I love flying with other pilots and controllers from around the world. The developers are also very responsive and helpful. I highly recommend this game to anyone who loves aviation."
      -
      "I have been playing this game for over a year now, and I am still amazed by how much it has improved. The new 3D airports, buildings, clouds, and lighting are stunning. The new aircraft models are also very detailed and accurate. The game is very easy to use and learn, but also challenging and rewarding. It is worth every penny."
      -
      "This game is a masterpiece. It is not just a game, it is a simulator. It teaches you how to fly different aircraft in different scenarios, with real-world data and weather. It also lets you interact with other pilots and controllers in a friendly and respectful community. It is not just fun, it is educational."
      -

      Of course, not everyone is satisfied with the game. Some users have also expressed their complaints and suggestions for improvement. Here are some of them:

      -
      "The game is good, but it needs more free content. The subscription is too expensive for me, and I can't afford it. I wish they would add more free aircraft and regions, or lower the price of the subscription."
      -
      "The game is great, but it has some bugs and glitches that need to be fixed. Sometimes the game crashes or freezes, or the graphics glitch out. Sometimes the online mode doesn't work properly, or I get disconnected or banned for no reason. Please fix these issues as soon as possible."
      -
      "The game is nice, but it needs more features and options. I would like to see more customization options for the aircraft, such as the liveries, the sounds, the cameras, and the instruments. I would also like to see more modes and challenges, such as missions, emergencies, and tutorials. I hope they will add these features in the future."
      -

      FAQs about Infinite Flight Simulator APK Download Android

      -

      If you have any questions or doubts about Infinite Flight Simulator APK Download Android, you might find the answers in this section. Here are some of the most frequently asked questions and their answers:

      -

      Q1: Is Infinite Flight Simulator free to play?

      -

      A1: Infinite Flight Simulator is free to download and play, but some features and content require a subscription to Infinite Flight Pro. You can choose from monthly, 6-month, or annual plans, depending on your preference and budget. You can also cancel your subscription at any time.

      -

      Q2: How to update Infinite Flight Simulator APK?

      -

      A2: To update Infinite Flight Simulator APK, you need to download and install the latest version of the game from the same source where you downloaded the previous version. You can also check for updates within the game settings. Make sure you have enough storage space and a stable internet connection before updating.

      -

      Q3: How to join multiplayer mode in Infinite Flight Simulator?

      -

      A3: To join multiplayer mode in Infinite Flight Simulator, you need to have a subscription to Infinite Flight Pro. Then, you can choose from three servers: Casual, Training, or Expert. Each server has different rules and requirements for pilots and controllers. You can also join or create groups with other players, or use voice chat to communicate with them.

      -

      Q4: How to access 3D airports in Infinite Flight Simulator?

      -

      A4: To access 3D airports in Infinite Flight Simulator, you need to have a subscription to Infinite Flight Pro. Then, you can select any region that has 3D airports available. You can also check the map or the airport list to see which airports have 3D buildings and structures.

      -

      Q5: How to contact Infinite Flight Simulator support team?

      -

      A5: To contact Infinite Flight Simulator support team, you can visit their official website Infinite Flight, where you can find their contact information, FAQs, guides, forums, blog, and social media links. You can also email them at support@infiniteflight.com, or send them a message through their Facebook or Twitter accounts.

      -

      Conclusion

      -

      Infinite Flight Simulator is a flight simulation game that offers you a realistic and immersive flight simulation experience on your mobile device. You can fly dozens of aircraft in various regions of the world, with realistic weather, navigation, and physics. You can also join thousands of other pilots and air traffic controllers in the online multiplayer mode, or fly solo with the advanced replay system.

      -

      If you want to download and install Infinite Flight Simulator APK on your Android device, you can follow the simple steps we have shown you in this article. You can also learn more about the features, pros and cons, user reviews, and FAQs of this game.

      -

      We hope you have enjoyed this article and found it helpful. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/tioseFevbu/cartoon-converter/scripts/LINK Full Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable.md b/spaces/tioseFevbu/cartoon-converter/scripts/LINK Full Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable.md deleted file mode 100644 index 6f1bfa03e7e234c3836bd2d9d55f9f2b3c20bacf..0000000000000000000000000000000000000000 --- a/spaces/tioseFevbu/cartoon-converter/scripts/LINK Full Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable.md +++ /dev/null @@ -1,24 +0,0 @@ -
      -

      FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable: A Powerful and Versatile Design Software for Residential and Light Commercial Projects

      -

      If you are looking for a software that can help you design and visualize your dream home or office, you might want to check out FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable. This is a comprehensive and professional software that allows you to create 2D and 3D models, floor plans, elevations, site plans, framing plans, section details, and more.

      -

      With FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable, you can draw walls and place smart architectural objects like doors, windows, cabinets, appliances, furniture, and landscaping. The software automatically generates a 3D model of your design, as well as a materials list and cost estimate. You can also use powerful building tools to produce construction documents with dimensions, annotations, schedules, and legends.

      -

      FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable


      Download Zip » https://urlcod.com/2uHvHi



      -

      One of the best features of FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable is that it is portable. This means that you can run it from any USB drive or external hard drive without installing it on your computer. This gives you more flexibility and convenience when working on different projects or devices.

      -

      FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable also comes with a patch that fixes some bugs and improves the performance of the software. You can download it from this link [^1^] and enjoy the full features of this amazing software.

      -

      If you want to learn more about FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable or other products from Chief Architect, you can visit their official website at this link [^2^]. You can also watch some tutorials and demos on their YouTube channel or join their online community of users and experts.

      - -

      In this article, we will show you some examples of designs made with FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable. You will see how this software can help you create realistic and stunning interiors and exteriors for your residential and light commercial projects.

      -

      Example 1: A Modern Kitchen

      -

      This is a design of a modern kitchen that features sleek cabinets, stainless steel appliances, a large island, and a skylight. The software allows you to customize the colors, materials, textures, and lighting of your design. You can also add accessories, such as plants, rugs, and artwork, to enhance the look and feel of your space.

      -A modern kitchen design made with Chief Architect Premier X8 -

      Example 2: A Cozy Living Room

      -

      This is a design of a cozy living room that features a fireplace, a sofa, a coffee table, and a TV. The software allows you to choose from thousands of furniture and decor items from the 3D Library. You can also adjust the size, shape, and orientation of your objects to fit your layout. You can also create custom materials and colors for your objects.

      -

      -A cozy living room design made with Chief Architect Premier X8 -

      Example 3: A Luxury Bathroom

      -

      This is a design of a luxury bathroom that features a freestanding tub, a walk-in shower, a double vanity, and a large window. The software allows you to create realistic water effects, such as steam, spray, and reflections. You can also add glass doors, tiles, mirrors, and fixtures to your design. You can also use the ray trace feature to render high-quality images of your design.

      -A luxury bathroom design made with Chief Architect Premier X8 -

      Conclusion

      -

      As you can see, FULL Chief Architect Premier X8 18.1.1.4 (x64) Incl Patch Portable is a powerful and versatile design software that can help you create amazing designs for your residential and light commercial projects. Whether you are a professional designer or a hobbyist, you will find this software easy to use and fun to explore. You can download it from this link and start creating your own designs today!

      81aa517590
      -
      -
      \ No newline at end of file diff --git a/spaces/tomaseo2022/Eliminar-Fondo-Imagen/git.sh b/spaces/tomaseo2022/Eliminar-Fondo-Imagen/git.sh deleted file mode 100644 index 0aabfded99e3ead2b6b903be6f4514d94213e7c5..0000000000000000000000000000000000000000 --- a/spaces/tomaseo2022/Eliminar-Fondo-Imagen/git.sh +++ /dev/null @@ -1,3 +0,0 @@ -git add . -git commit -m "1.0" -git push \ No newline at end of file diff --git a/spaces/tomofi/MMOCR/mmocr/models/textdet/detectors/panet.py b/spaces/tomofi/MMOCR/mmocr/models/textdet/detectors/panet.py deleted file mode 100644 index 1c95251380ebe1455de4d8fef2d0104160458643..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/models/textdet/detectors/panet.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from mmocr.models.builder import DETECTORS -from .single_stage_text_detector import SingleStageTextDetector -from .text_detector_mixin import TextDetectorMixin - - -@DETECTORS.register_module() -class PANet(TextDetectorMixin, SingleStageTextDetector): - """The class for implementing PANet text detector: - - Efficient and Accurate Arbitrary-Shaped Text Detection with Pixel - Aggregation Network [https://arxiv.org/abs/1908.05900]. - """ - - def __init__(self, - backbone, - neck, - bbox_head, - train_cfg=None, - test_cfg=None, - pretrained=None, - show_score=False, - init_cfg=None): - SingleStageTextDetector.__init__(self, backbone, neck, bbox_head, - train_cfg, test_cfg, pretrained, - init_cfg) - TextDetectorMixin.__init__(self, show_score) diff --git a/spaces/tomofi/MMOCR/tests/test_dataset/test_ocr_seg_target.py b/spaces/tomofi/MMOCR/tests/test_dataset/test_ocr_seg_target.py deleted file mode 100644 index 54f78bf053733f23beb1aac51fcc283d6c05bc45..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/tests/test_dataset/test_ocr_seg_target.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import os.path as osp -import tempfile - -import numpy as np -import pytest - -from mmocr.datasets.pipelines.ocr_seg_targets import OCRSegTargets - - -def _create_dummy_dict_file(dict_file): - chars = list('0123456789') - with open(dict_file, 'w') as fw: - for char in chars: - fw.write(char + '\n') - - -def test_ocr_segm_targets(): - tmp_dir = tempfile.TemporaryDirectory() - # create dummy dict file - dict_file = osp.join(tmp_dir.name, 'fake_chars.txt') - _create_dummy_dict_file(dict_file) - # dummy label convertor - label_convertor = dict( - type='SegConvertor', - dict_file=dict_file, - with_unknown=True, - lower=True) - # test init - with pytest.raises(AssertionError): - OCRSegTargets(None, 0.5, 0.5) - with pytest.raises(AssertionError): - OCRSegTargets(label_convertor, '1by2', 0.5) - with pytest.raises(AssertionError): - OCRSegTargets(label_convertor, 0.5, 2) - - ocr_seg_tgt = OCRSegTargets(label_convertor, 0.5, 0.5) - # test generate kernels - img_size = (8, 8) - pad_size = (8, 10) - char_boxes = [[2, 2, 6, 6]] - char_idxs = [2] - - with pytest.raises(AssertionError): - ocr_seg_tgt.generate_kernels(8, pad_size, char_boxes, char_idxs, 0.5, - True) - with pytest.raises(AssertionError): - ocr_seg_tgt.generate_kernels(img_size, pad_size, [2, 2, 6, 6], - char_idxs, 0.5, True) - with pytest.raises(AssertionError): - ocr_seg_tgt.generate_kernels(img_size, pad_size, char_boxes, 2, 0.5, - True) - - attn_tgt = ocr_seg_tgt.generate_kernels( - img_size, pad_size, char_boxes, char_idxs, 0.5, binary=True) - expect_attn_tgt = [[0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 1, 1, 1, 0, 0, 255, 255], - [0, 0, 0, 1, 1, 1, 0, 0, 255, 255], - [0, 0, 0, 1, 1, 1, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255]] - assert np.allclose(attn_tgt, np.array(expect_attn_tgt, dtype=np.int32)) - - segm_tgt = ocr_seg_tgt.generate_kernels( - img_size, pad_size, char_boxes, char_idxs, 0.5, binary=False) - expect_segm_tgt = [[0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 2, 2, 2, 0, 0, 255, 255], - [0, 0, 0, 2, 2, 2, 0, 0, 255, 255], - [0, 0, 0, 2, 2, 2, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255], - [0, 0, 0, 0, 0, 0, 0, 0, 255, 255]] - assert np.allclose(segm_tgt, np.array(expect_segm_tgt, dtype=np.int32)) - - # test __call__ - results = {} - results['img_shape'] = (4, 4, 3) - results['resize_shape'] = (8, 8, 3) - results['pad_shape'] = (8, 10) - results['ann_info'] = {} - results['ann_info']['char_rects'] = [[1, 1, 3, 3]] - results['ann_info']['chars'] = ['1'] - - results = ocr_seg_tgt(results) - assert results['mask_fields'] == ['gt_kernels'] - assert np.allclose(results['gt_kernels'].masks[0], - np.array(expect_attn_tgt, dtype=np.int32)) - assert np.allclose(results['gt_kernels'].masks[1], - np.array(expect_segm_tgt, dtype=np.int32)) - - tmp_dir.cleanup() diff --git a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/config/__init__.py b/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/config/__init__.py deleted file mode 100644 index 22a15023b1b06dad1f8c36924cdbb96bf1f5dc8d..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/config/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -from .defaults import _C as cfg diff --git a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/csrc/deform_pool.h b/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/csrc/deform_pool.h deleted file mode 100644 index 234223809bad726a8ecf71697b9281e75eec5288..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/csrc/deform_pool.h +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -#pragma once -#include "cpu/vision.h" - -#ifdef WITH_CUDA -#include "cuda/vision.h" -#endif - - -// Interface for Python -void deform_psroi_pooling_forward( - at::Tensor input, - at::Tensor bbox, - at::Tensor trans, - at::Tensor out, - at::Tensor top_count, - const int no_trans, - const float spatial_scale, - const int output_dim, - const int group_size, - const int pooled_size, - const int part_size, - const int sample_per_part, - const float trans_std) -{ - if (input.type().is_cuda()) { -#ifdef WITH_CUDA - return deform_psroi_pooling_cuda_forward( - input, bbox, trans, out, top_count, - no_trans, spatial_scale, output_dim, group_size, - pooled_size, part_size, sample_per_part, trans_std - ); -#else - AT_ERROR("Not compiled with GPU support"); -#endif - } - AT_ERROR("Not implemented on the CPU"); -} - - -void deform_psroi_pooling_backward( - at::Tensor out_grad, - at::Tensor input, - at::Tensor bbox, - at::Tensor trans, - at::Tensor top_count, - at::Tensor input_grad, - at::Tensor trans_grad, - const int no_trans, - const float spatial_scale, - const int output_dim, - const int group_size, - const int pooled_size, - const int part_size, - const int sample_per_part, - const float trans_std) -{ - if (input.type().is_cuda()) { -#ifdef WITH_CUDA - return deform_psroi_pooling_cuda_backward( - out_grad, input, bbox, trans, top_count, input_grad, trans_grad, - no_trans, spatial_scale, output_dim, group_size, pooled_size, - part_size, sample_per_part, trans_std - ); -#else - AT_ERROR("Not compiled with GPU support"); -#endif - } - AT_ERROR("Not implemented on the CPU"); -} diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/tests/test_models/test_utils/test_position_encoding.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/tests/test_models/test_utils/test_position_encoding.py deleted file mode 100644 index 94fdd479a4775d47ae0d0f069c7a37e862b84b2f..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/tests/test_models/test_utils/test_position_encoding.py +++ /dev/null @@ -1,38 +0,0 @@ -import pytest -import torch - -from mmdet.models.utils import (LearnedPositionalEncoding, - SinePositionalEncoding) - - -def test_sine_positional_encoding(num_feats=16, batch_size=2): - # test invalid type of scale - with pytest.raises(AssertionError): - module = SinePositionalEncoding( - num_feats, scale=(3., ), normalize=True) - - module = SinePositionalEncoding(num_feats) - h, w = 10, 6 - mask = torch.rand(batch_size, h, w) > 0.5 - assert not module.normalize - out = module(mask) - assert out.shape == (batch_size, num_feats * 2, h, w) - - # set normalize - module = SinePositionalEncoding(num_feats, normalize=True) - assert module.normalize - out = module(mask) - assert out.shape == (batch_size, num_feats * 2, h, w) - - -def test_learned_positional_encoding(num_feats=16, - row_num_embed=10, - col_num_embed=10, - batch_size=2): - module = LearnedPositionalEncoding(num_feats, row_num_embed, col_num_embed) - assert module.row_embed.weight.shape == (row_num_embed, num_feats) - assert module.col_embed.weight.shape == (col_num_embed, num_feats) - h, w = 10, 6 - mask = torch.rand(batch_size, h, w) > 0.5 - out = module(mask) - assert out.shape == (batch_size, num_feats * 2, h, w) diff --git a/spaces/tonne/pycaret/README.md b/spaces/tonne/pycaret/README.md deleted file mode 100644 index 37b96b90d4c6ad0bb9bdbad4c3f99258224a9ff9..0000000000000000000000000000000000000000 --- a/spaces/tonne/pycaret/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Pycaret -emoji: 😻 -colorFrom: purple -colorTo: pink -sdk: streamlit -sdk_version: 1.10.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/tonyassi/video-face-swap/run.py b/spaces/tonyassi/video-face-swap/run.py deleted file mode 100644 index 11500cdc86edf1a68cf1c53b78d4e7e01a6393c4..0000000000000000000000000000000000000000 --- a/spaces/tonyassi/video-face-swap/run.py +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env python3 - -from DeepFakeAI import core - -if __name__ == '__main__': - core.run() diff --git a/spaces/triggah61/chingu-music/tests/data/__init__.py b/spaces/triggah61/chingu-music/tests/data/__init__.py deleted file mode 100644 index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000 --- a/spaces/triggah61/chingu-music/tests/data/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. diff --git a/spaces/triggah61/li5/Dockerfile b/spaces/triggah61/li5/Dockerfile deleted file mode 100644 index 8673c32e47d0e6700f24404e933dac777d2abe83..0000000000000000000000000000000000000000 --- a/spaces/triggah61/li5/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ -FROM ghcr.io/livebook-dev/livebook:latest-cuda11.8 - -ENV LIVEBOOK_APP_SERVICE_NAME "🐳 Hugging Face - $SPACE_TITLE" -ENV LIVEBOOK_APP_SERVICE_URL "https://huggingface.co/spaces/$SPACE_AUTHOR_NAME/$SPACE_REPO_NAME" -ENV LIVEBOOK_UPDATE_INSTRUCTIONS_URL "https://livebook.dev" -ENV LIVEBOOK_WITHIN_IFRAME "true" -ENV LIVEBOOK_APPS_PATH "/public-apps" -ENV LIVEBOOK_DATA_PATH "/data" -ENV LIVEBOOK_PORT 7860 - -EXPOSE 7860 -USER root -COPY public-apps/ /public-apps -RUN mkdir -p /data -RUN chmod 777 /data diff --git a/spaces/tyao/CompVis-stable-diffusion-v1-4/README.md b/spaces/tyao/CompVis-stable-diffusion-v1-4/README.md deleted file mode 100644 index 5d204e92590c96a31f28c789a3710dce56a7a599..0000000000000000000000000000000000000000 --- a/spaces/tyao/CompVis-stable-diffusion-v1-4/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: CompVis Stable Diffusion V1 4 -emoji: 🐠 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 3.20.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/umichVision/virtex-redcaps/virtex/modules/visual_backbones.py b/spaces/umichVision/virtex-redcaps/virtex/modules/visual_backbones.py deleted file mode 100644 index 4f1f9e24f8ab9b0db7cc579e496a33b88fe3796f..0000000000000000000000000000000000000000 --- a/spaces/umichVision/virtex-redcaps/virtex/modules/visual_backbones.py +++ /dev/null @@ -1,198 +0,0 @@ -from typing import Any, Dict - -import torch -from torch import nn -import torchvision - - -class VisualBackbone(nn.Module): - r""" - Base class for all visual backbones. All child classes can simply inherit - from :class:`~torch.nn.Module`, however this is kept here for uniform - type annotations. - """ - - def __init__(self, visual_feature_size: int): - super().__init__() - self.visual_feature_size = visual_feature_size - - -class TorchvisionVisualBackbone(VisualBackbone): - r""" - A visual backbone from `Torchvision model zoo - `_. Any model can - be specified using corresponding method name from the model zoo. - - Parameters - ---------- - name: str, optional (default = "resnet50") - Name of the model from Torchvision model zoo. - visual_feature_size: int, optional (default = 2048) - Size of the channel dimension of output visual features from forward pass. - pretrained: bool, optional (default = False) - Whether to load ImageNet pretrained weights from Torchvision. - frozen: float, optional (default = False) - Whether to keep all weights frozen during training. - """ - - def __init__( - self, - name: str = "resnet50", - visual_feature_size: int = 2048, - pretrained: bool = False, - frozen: bool = False, - ): - super().__init__(visual_feature_size) - - self.cnn = getattr(torchvision.models, name)( - pretrained, zero_init_residual=True - ) - # Do nothing after the final residual stage. - self.cnn.fc = nn.Identity() - - # Freeze all weights if specified. - if frozen: - for param in self.cnn.parameters(): - param.requires_grad = False - self.cnn.eval() - - def forward(self, image: torch.Tensor) -> torch.Tensor: - r""" - Compute visual features for a batch of input images. - - Parameters - ---------- - image: torch.Tensor - Batch of input images. A tensor of shape - ``(batch_size, 3, height, width)``. - - Returns - ------- - torch.Tensor - A tensor of shape ``(batch_size, channels, height, width)``, for - example it will be ``(batch_size, 2048, 7, 7)`` for ResNet-50. - """ - - for idx, (name, layer) in enumerate(self.cnn.named_children()): - out = layer(image) if idx == 0 else layer(out) - - # These are the spatial features we need. - if name == "layer4": - # shape: (batch_size, channels, height, width) - return out - - def detectron2_backbone_state_dict(self) -> Dict[str, Any]: - r""" - Return state dict of visual backbone which can be loaded with - `Detectron2 `_. - This is useful for downstream tasks based on Detectron2 (such as - object detection and instance segmentation). This method renames - certain parameters from Torchvision-style to Detectron2-style. - - Returns - ------- - Dict[str, Any] - A dict with three keys: ``{"model", "author", "matching_heuristics"}``. - These are necessary keys for loading this state dict properly with - Detectron2. - """ - # Detectron2 backbones have slightly different module names, this mapping - # lists substrings of module names required to be renamed for loading a - # torchvision model into Detectron2. - DETECTRON2_RENAME_MAPPING: Dict[str, str] = { - "layer1": "res2", - "layer2": "res3", - "layer3": "res4", - "layer4": "res5", - "bn1": "conv1.norm", - "bn2": "conv2.norm", - "bn3": "conv3.norm", - "downsample.0": "shortcut", - "downsample.1": "shortcut.norm", - } - # Populate this dict by renaming module names. - d2_backbone_dict: Dict[str, torch.Tensor] = {} - - for name, param in self.cnn.state_dict().items(): - for old, new in DETECTRON2_RENAME_MAPPING.items(): - name = name.replace(old, new) - - # First conv and bn module parameters are prefixed with "stem.". - if not name.startswith("res"): - name = f"stem.{name}" - - d2_backbone_dict[name] = param - - return { - "model": d2_backbone_dict, - "__author__": "Karan Desai", - "matching_heuristics": True, - } - - -class TimmVisualBackbone(VisualBackbone): - r""" - A visual backbone from `Timm model zoo - `_. - This class is a generic wrapper over the ``timm`` library, and supports - all models provided by the library. Check ``timm.list_models()`` for all - supported model names. - - Parameters - ---------- - name: str, optional (default = "resnet50") - Name of the model from Timm model zoo. - visual_feature_size: int, optional (default = 2048) - Size of the channel dimension of output visual features from forward pass. - pretrained: bool, optional (default = False) - Whether to load ImageNet pretrained weights from Torchvision. - frozen: float, optional (default = False) - Whether to keep all weights frozen during training. - """ - - def __init__( - self, - name: str = "resnet50", - visual_feature_size: int = 2048, - pretrained: bool = False, - frozen: bool = False, - ): - super().__init__(visual_feature_size) - - # Limit the scope of library import inside class definition. - import timm - - # Create the model without any global pooling and softmax classifier. - self.cnn = timm.create_model( - name, pretrained=pretrained, num_classes=0, global_pool="" - ) - # Freeze all weights if specified. - if frozen: - for param in self.cnn.parameters(): - param.requires_grad = False - self.cnn.eval() - - def forward(self, image: torch.Tensor) -> torch.Tensor: - r""" - Compute visual features for a batch of input images. - - Parameters - ---------- - image: torch.Tensor - Batch of input images. A tensor of shape - ``(batch_size, 3, height, width)``. - - Returns - ------- - torch.Tensor - A tensor of shape ``(batch_size, channels, height, width)``, for - example it will be ``(batch_size, 2048, 7, 7)`` for ResNet-50. - """ - # shape: (batch_size, channels, height, width) - return self.cnn(image) - - def detectron2_backbone_state_dict(self) -> Dict[str, Any]: - - # Detectron2 may not support all timm models out of the box. These - # backbones won't be transferred to downstream detection tasks anyway. - raise NotImplementedError diff --git a/spaces/uranus0516/uranus/README.md b/spaces/uranus0516/uranus/README.md deleted file mode 100644 index 9fa9ee76dae03a2c58cd6a967de2d81843389e24..0000000000000000000000000000000000000000 --- a/spaces/uranus0516/uranus/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Uranus -emoji: 🌖 -colorFrom: red -colorTo: gray -sdk: gradio -sdk_version: 3.8 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/usecodenaija/x-spaces-web-ui/README.md b/spaces/usecodenaija/x-spaces-web-ui/README.md deleted file mode 100644 index 8d886dc9a036494d00e97e5de5676d967f9bfd4e..0000000000000000000000000000000000000000 --- a/spaces/usecodenaija/x-spaces-web-ui/README.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: X Spaces Web Ui -emoji: 🌖 -colorFrom: green -colorTo: red -sdk: gradio -sdk_version: 3.44.3 -app_file: app.py -pinned: false ---- - - -# X-Spaces: Pioneering Conversational AI Experiences - -Welcome to the X-Spaces Web UI. Dive into the future of conversational AI and experience lifelike dialogues between dynamic AI entities. - - - - - -## Overview - -X-Spaces offers an unparalleled tool for immersing users in vivid audio-based AI dialogues. Experience the magic of lifelike interactions between two AI entities. - -## Core Applications & Features - -### Conversational Audio Interaction -- Experience authentic audio dialogues between two AI entities. -- Revel in various scenarios, accents, or languages. - -### Customizable Experiences -- Personalize voice profiles to represent different personas or characters. -- Engage with context-aware dialogues based on the provided content. - -## Why Use X-Spaces? -- **Research & Development**: Test, validate, and refine conversational algorithms or models. -- **Entertainment & Media**: Discover compelling audio narratives, podcasts, or virtual dialogues. -- **Education**: Utilize conversations for language learning or role-playing scenarios. -- **Business**: Sample interactive voice systems, customer simulations, or sales demos. - -## Future Features -- **Video Generation Support**: Soon, not only will you hear the conversations, but you'll also see them. We're progressing towards introducing visual audio conversations to elevate the interactions. -- **Exclusive Features**: We're brimming with advanced features, including Discord integration and a myriad of customization options. These are available exclusively for our privileged members. Interested? [Join the waitlist here](https://09a828c3.sibforms.com/serve/MUIFAPFvWcya1KAj83yfQaPW6O-sjnzm-55rLBQS8HArqVWSMV80YewPyYrU0tHSE3shQvUdTIYtRKLQ7gsVlFWyK0dSzoIQc11DEGQTwZWbQ-3wzrF8VCewbvY0Bpz0dzvijpDa2SxRfOK1F-w4E1JLu9gxP_U7fWfC2nS-ZRJqVUPgeY61LN2F8EeYA-UTU4EXAnEF25ytth4y). - -## Join the X-Spaces Journey - -Your journey with X-Spaces promises to be an enlightening one. As we shape the future of AI-driven conversational experiences, your engagement remains our driving force. Join our community, share your experiences, and contribute to the X-Spaces narrative. - - diff --git a/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/docs/tasks/pose.md b/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/docs/tasks/pose.md deleted file mode 100644 index 6ed68aee50da18acb93d8781e277d16a8dbaa7b8..0000000000000000000000000000000000000000 --- a/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/docs/tasks/pose.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -comments: true -description: Learn how to use YOLOv8 pose estimation models to identify the position of keypoints on objects in an image, and how to train, validate, predict, and export these models for use with various formats such as ONNX or CoreML. -keywords: YOLOv8, Pose Models, Keypoint Detection, COCO dataset, COCO val2017, Amazon EC2 P4d, PyTorch ---- - -Pose estimation is a task that involves identifying the location of specific points in an image, usually referred -to as keypoints. The keypoints can represent various parts of the object such as joints, landmarks, or other distinctive -features. The locations of the keypoints are usually represented as a set of 2D `[x, y]` or 3D `[x, y, visible]` -coordinates. - - - -The output of a pose estimation model is a set of points that represent the keypoints on an object in the image, usually -along with the confidence scores for each point. Pose estimation is a good choice when you need to identify specific -parts of an object in a scene, and their location in relation to each other. - -!!! tip "Tip" - - YOLOv8 _pose_ models use the `-pose` suffix, i.e. `yolov8n-pose.pt`. These models are trained on the [COCO keypoints](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco-pose.yaml) dataset and are suitable for a variety of pose estimation tasks. - -## [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models/v8) - -YOLOv8 pretrained Pose models are shown here. Detect, Segment and Pose models are pretrained on -the [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify -models are pretrained on -the [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset. - -[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest -Ultralytics [release](https://github.com/ultralytics/assets/releases) on first use. - -| Model | size
      (pixels) | mAPpose
      50-95 | mAPpose
      50 | Speed
      CPU ONNX
      (ms) | Speed
      A100 TensorRT
      (ms) | params
      (M) | FLOPs
      (B) | -|------------------------------------------------------------------------------------------------------|-----------------------|-----------------------|--------------------|--------------------------------|-------------------------------------|--------------------|-------------------| -| [YOLOv8n-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-pose.pt) | 640 | 50.4 | 80.1 | 131.8 | 1.18 | 3.3 | 9.2 | -| [YOLOv8s-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-pose.pt) | 640 | 60.0 | 86.2 | 233.2 | 1.42 | 11.6 | 30.2 | -| [YOLOv8m-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-pose.pt) | 640 | 65.0 | 88.8 | 456.3 | 2.00 | 26.4 | 81.0 | -| [YOLOv8l-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-pose.pt) | 640 | 67.6 | 90.0 | 784.5 | 2.59 | 44.4 | 168.6 | -| [YOLOv8x-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose.pt) | 640 | 69.2 | 90.2 | 1607.1 | 3.73 | 69.4 | 263.2 | -| [YOLOv8x-pose-p6](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose-p6.pt) | 1280 | 71.6 | 91.2 | 4088.7 | 10.04 | 99.1 | 1066.4 | - -- **mAPval** values are for single-model single-scale on [COCO Keypoints val2017](http://cocodataset.org) - dataset. -
      Reproduce by `yolo val pose data=coco-pose.yaml device=0` -- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) - instance. -
      Reproduce by `yolo val pose data=coco8-pose.yaml batch=1 device=0|cpu` - -## Train - -Train a YOLOv8-pose model on the COCO128-pose dataset. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-pose.yaml') # build a new model from YAML - model = YOLO('yolov8n-pose.pt') # load a pretrained model (recommended for training) - model = YOLO('yolov8n-pose.yaml').load('yolov8n-pose.pt') # build from YAML and transfer weights - - # Train the model - model.train(data='coco8-pose.yaml', epochs=100, imgsz=640) - ``` - === "CLI" - - ```bash - # Build a new model from YAML and start training from scratch - yolo pose train data=coco8-pose.yaml model=yolov8n-pose.yaml epochs=100 imgsz=640 - - # Start training from a pretrained *.pt model - yolo pose train data=coco8-pose.yaml model=yolov8n-pose.pt epochs=100 imgsz=640 - - # Build a new model from YAML, transfer pretrained weights to it and start training - yolo pose train data=coco8-pose.yaml model=yolov8n-pose.yaml pretrained=yolov8n-pose.pt epochs=100 imgsz=640 - ``` - -### Dataset format - -YOLO pose dataset format can be found in detail in the [Dataset Guide](../datasets/pose/index.md). To convert your existing dataset from other formats( like COCO etc.) to YOLO format, please use [json2yolo tool](https://github.com/ultralytics/JSON2YOLO) by Ultralytics. - -## Val - -Validate trained YOLOv8n-pose model accuracy on the COCO128-pose dataset. No argument need to passed as the `model` -retains it's -training `data` and arguments as model attributes. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-pose.pt') # load an official model - model = YOLO('path/to/best.pt') # load a custom model - - # Validate the model - metrics = model.val() # no arguments needed, dataset and settings remembered - metrics.box.map # map50-95 - metrics.box.map50 # map50 - metrics.box.map75 # map75 - metrics.box.maps # a list contains map50-95 of each category - ``` - === "CLI" - - ```bash - yolo pose val model=yolov8n-pose.pt # val official model - yolo pose val model=path/to/best.pt # val custom model - ``` - -## Predict - -Use a trained YOLOv8n-pose model to run predictions on images. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-pose.pt') # load an official model - model = YOLO('path/to/best.pt') # load a custom model - - # Predict with the model - results = model('https://ultralytics.com/images/bus.jpg') # predict on an image - ``` - === "CLI" - - ```bash - yolo pose predict model=yolov8n-pose.pt source='https://ultralytics.com/images/bus.jpg' # predict with official model - yolo pose predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg' # predict with custom model - ``` - -See full `predict` mode details in the [Predict](https://docs.ultralytics.com/modes/predict/) page. - -## Export - -Export a YOLOv8n Pose model to a different format like ONNX, CoreML, etc. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-pose.pt') # load an official model - model = YOLO('path/to/best.pt') # load a custom trained - - # Export the model - model.export(format='onnx') - ``` - === "CLI" - - ```bash - yolo export model=yolov8n-pose.pt format=onnx # export official model - yolo export model=path/to/best.pt format=onnx # export custom trained model - ``` - -Available YOLOv8-pose export formats are in the table below. You can predict or validate directly on exported models, -i.e. `yolo predict model=yolov8n-pose.onnx`. Usage examples are shown for your model after export completes. - -| Format | `format` Argument | Model | Metadata | Arguments | -|--------------------------------------------------------------------|-------------------|--------------------------------|----------|-----------------------------------------------------| -| [PyTorch](https://pytorch.org/) | - | `yolov8n-pose.pt` | ✅ | - | -| [TorchScript](https://pytorch.org/docs/stable/jit.html) | `torchscript` | `yolov8n-pose.torchscript` | ✅ | `imgsz`, `optimize` | -| [ONNX](https://onnx.ai/) | `onnx` | `yolov8n-pose.onnx` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `opset` | -| [OpenVINO](https://docs.openvino.ai/latest/index.html) | `openvino` | `yolov8n-pose_openvino_model/` | ✅ | `imgsz`, `half` | -| [TensorRT](https://developer.nvidia.com/tensorrt) | `engine` | `yolov8n-pose.engine` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` | -| [CoreML](https://github.com/apple/coremltools) | `coreml` | `yolov8n-pose.mlmodel` | ✅ | `imgsz`, `half`, `int8`, `nms` | -| [TF SavedModel](https://www.tensorflow.org/guide/saved_model) | `saved_model` | `yolov8n-pose_saved_model/` | ✅ | `imgsz`, `keras` | -| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb` | `yolov8n-pose.pb` | ❌ | `imgsz` | -| [TF Lite](https://www.tensorflow.org/lite) | `tflite` | `yolov8n-pose.tflite` | ✅ | `imgsz`, `half`, `int8` | -| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/) | `edgetpu` | `yolov8n-pose_edgetpu.tflite` | ✅ | `imgsz` | -| [TF.js](https://www.tensorflow.org/js) | `tfjs` | `yolov8n-pose_web_model/` | ✅ | `imgsz` | -| [PaddlePaddle](https://github.com/PaddlePaddle) | `paddle` | `yolov8n-pose_paddle_model/` | ✅ | `imgsz` | -| [NCNN](https://github.com/Tencent/ncnn) | `ncnn` | `yolov8n-pose_ncnn_model/` | ✅ | `imgsz`, `half` | - -See full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page. \ No newline at end of file diff --git a/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/docs/tasks/segment.md b/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/docs/tasks/segment.md deleted file mode 100644 index 586bcfcd412756705301fdd14ab9f6f5efa360e0..0000000000000000000000000000000000000000 --- a/spaces/vaishanthr/Simultaneous-Segmented-Depth-Prediction/yolov8/docs/tasks/segment.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -comments: true -description: Learn what Instance segmentation is. Get pretrained YOLOv8 segment models, and how to train and export them to segments masks. Check the preformance metrics! -keywords: instance segmentation, YOLOv8, Ultralytics, pretrained models, train, predict, export, datasets ---- - -Instance segmentation goes a step further than object detection and involves identifying individual objects in an image -and segmenting them from the rest of the image. - - - -The output of an instance segmentation model is a set of masks or -contours that outline each object in the image, along with class labels and confidence scores for each object. Instance -segmentation is useful when you need to know not only where objects are in an image, but also what their exact shape is. - -!!! tip "Tip" - - YOLOv8 Segment models use the `-seg` suffix, i.e. `yolov8n-seg.pt` and are pretrained on [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml). - -## [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models/v8) - -YOLOv8 pretrained Segment models are shown here. Detect, Segment and Pose models are pretrained on -the [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify -models are pretrained on -the [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset. - -[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest -Ultralytics [release](https://github.com/ultralytics/assets/releases) on first use. - -| Model | size
      (pixels) | mAPbox
      50-95 | mAPmask
      50-95 | Speed
      CPU ONNX
      (ms) | Speed
      A100 TensorRT
      (ms) | params
      (M) | FLOPs
      (B) | -|----------------------------------------------------------------------------------------------|-----------------------|----------------------|-----------------------|--------------------------------|-------------------------------------|--------------------|-------------------| -| [YOLOv8n-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-seg.pt) | 640 | 36.7 | 30.5 | 96.1 | 1.21 | 3.4 | 12.6 | -| [YOLOv8s-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-seg.pt) | 640 | 44.6 | 36.8 | 155.7 | 1.47 | 11.8 | 42.6 | -| [YOLOv8m-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-seg.pt) | 640 | 49.9 | 40.8 | 317.0 | 2.18 | 27.3 | 110.2 | -| [YOLOv8l-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-seg.pt) | 640 | 52.3 | 42.6 | 572.4 | 2.79 | 46.0 | 220.5 | -| [YOLOv8x-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-seg.pt) | 640 | 53.4 | 43.4 | 712.1 | 4.02 | 71.8 | 344.1 | - -- **mAPval** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset. -
      Reproduce by `yolo val segment data=coco.yaml device=0` -- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) - instance. -
      Reproduce by `yolo val segment data=coco128-seg.yaml batch=1 device=0|cpu` - -## Train - -Train YOLOv8n-seg on the COCO128-seg dataset for 100 epochs at image size 640. For a full list of available -arguments see the [Configuration](../usage/cfg.md) page. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-seg.yaml') # build a new model from YAML - model = YOLO('yolov8n-seg.pt') # load a pretrained model (recommended for training) - model = YOLO('yolov8n-seg.yaml').load('yolov8n.pt') # build from YAML and transfer weights - - # Train the model - model.train(data='coco128-seg.yaml', epochs=100, imgsz=640) - ``` - === "CLI" - - ```bash - # Build a new model from YAML and start training from scratch - yolo segment train data=coco128-seg.yaml model=yolov8n-seg.yaml epochs=100 imgsz=640 - - # Start training from a pretrained *.pt model - yolo segment train data=coco128-seg.yaml model=yolov8n-seg.pt epochs=100 imgsz=640 - - # Build a new model from YAML, transfer pretrained weights to it and start training - yolo segment train data=coco128-seg.yaml model=yolov8n-seg.yaml pretrained=yolov8n-seg.pt epochs=100 imgsz=640 - ``` - -### Dataset format - -YOLO segmentation dataset format can be found in detail in the [Dataset Guide](../datasets/segment/index.md). To convert your existing dataset from other formats( like COCO etc.) to YOLO format, please use [json2yolo tool](https://github.com/ultralytics/JSON2YOLO) by Ultralytics. - -## Val - -Validate trained YOLOv8n-seg model accuracy on the COCO128-seg dataset. No argument need to passed as the `model` -retains it's training `data` and arguments as model attributes. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-seg.pt') # load an official model - model = YOLO('path/to/best.pt') # load a custom model - - # Validate the model - metrics = model.val() # no arguments needed, dataset and settings remembered - metrics.box.map # map50-95(B) - metrics.box.map50 # map50(B) - metrics.box.map75 # map75(B) - metrics.box.maps # a list contains map50-95(B) of each category - metrics.seg.map # map50-95(M) - metrics.seg.map50 # map50(M) - metrics.seg.map75 # map75(M) - metrics.seg.maps # a list contains map50-95(M) of each category - ``` - === "CLI" - - ```bash - yolo segment val model=yolov8n-seg.pt # val official model - yolo segment val model=path/to/best.pt # val custom model - ``` - -## Predict - -Use a trained YOLOv8n-seg model to run predictions on images. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-seg.pt') # load an official model - model = YOLO('path/to/best.pt') # load a custom model - - # Predict with the model - results = model('https://ultralytics.com/images/bus.jpg') # predict on an image - ``` - === "CLI" - - ```bash - yolo segment predict model=yolov8n-seg.pt source='https://ultralytics.com/images/bus.jpg' # predict with official model - yolo segment predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg' # predict with custom model - ``` - -See full `predict` mode details in the [Predict](https://docs.ultralytics.com/modes/predict/) page. - -## Export - -Export a YOLOv8n-seg model to a different format like ONNX, CoreML, etc. - -!!! example "" - - === "Python" - - ```python - from ultralytics import YOLO - - # Load a model - model = YOLO('yolov8n-seg.pt') # load an official model - model = YOLO('path/to/best.pt') # load a custom trained - - # Export the model - model.export(format='onnx') - ``` - === "CLI" - - ```bash - yolo export model=yolov8n-seg.pt format=onnx # export official model - yolo export model=path/to/best.pt format=onnx # export custom trained model - ``` - -Available YOLOv8-seg export formats are in the table below. You can predict or validate directly on exported models, -i.e. `yolo predict model=yolov8n-seg.onnx`. Usage examples are shown for your model after export completes. - -| Format | `format` Argument | Model | Metadata | Arguments | -|--------------------------------------------------------------------|-------------------|-------------------------------|----------|-----------------------------------------------------| -| [PyTorch](https://pytorch.org/) | - | `yolov8n-seg.pt` | ✅ | - | -| [TorchScript](https://pytorch.org/docs/stable/jit.html) | `torchscript` | `yolov8n-seg.torchscript` | ✅ | `imgsz`, `optimize` | -| [ONNX](https://onnx.ai/) | `onnx` | `yolov8n-seg.onnx` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `opset` | -| [OpenVINO](https://docs.openvino.ai/latest/index.html) | `openvino` | `yolov8n-seg_openvino_model/` | ✅ | `imgsz`, `half` | -| [TensorRT](https://developer.nvidia.com/tensorrt) | `engine` | `yolov8n-seg.engine` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` | -| [CoreML](https://github.com/apple/coremltools) | `coreml` | `yolov8n-seg.mlmodel` | ✅ | `imgsz`, `half`, `int8`, `nms` | -| [TF SavedModel](https://www.tensorflow.org/guide/saved_model) | `saved_model` | `yolov8n-seg_saved_model/` | ✅ | `imgsz`, `keras` | -| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb` | `yolov8n-seg.pb` | ❌ | `imgsz` | -| [TF Lite](https://www.tensorflow.org/lite) | `tflite` | `yolov8n-seg.tflite` | ✅ | `imgsz`, `half`, `int8` | -| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/) | `edgetpu` | `yolov8n-seg_edgetpu.tflite` | ✅ | `imgsz` | -| [TF.js](https://www.tensorflow.org/js) | `tfjs` | `yolov8n-seg_web_model/` | ✅ | `imgsz` | -| [PaddlePaddle](https://github.com/PaddlePaddle) | `paddle` | `yolov8n-seg_paddle_model/` | ✅ | `imgsz` | -| [NCNN](https://github.com/Tencent/ncnn) | `ncnn` | `yolov8n-seg_ncnn_model/` | ✅ | `imgsz`, `half` | - -See full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page. \ No newline at end of file diff --git a/spaces/vinthony/SadTalker/src/face3d/util/__init__.py b/spaces/vinthony/SadTalker/src/face3d/util/__init__.py deleted file mode 100644 index 04eecb58b62f8c9d11d17606c6241d278a48b9b9..0000000000000000000000000000000000000000 --- a/spaces/vinthony/SadTalker/src/face3d/util/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""This package includes a miscellaneous collection of useful helper functions.""" -from src.face3d.util import * - diff --git a/spaces/vishnu0001/text2mesh/shap_e/models/nerf/__init__.py b/spaces/vishnu0001/text2mesh/shap_e/models/nerf/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/vivien/trompeloeil/index.html b/spaces/vivien/trompeloeil/index.html deleted file mode 100644 index 8d375ef0d3ee8f9c736611dc5073ac783c5e5e61..0000000000000000000000000000000000000000 --- a/spaces/vivien/trompeloeil/index.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - 3D In Your Browser - - - - - - - -
      - -
      - - - - - - - - - - - - \ No newline at end of file diff --git a/spaces/vumichien/canvas_controlnet/annotator/uniformer/mmcv_custom/checkpoint.py b/spaces/vumichien/canvas_controlnet/annotator/uniformer/mmcv_custom/checkpoint.py deleted file mode 100644 index 19b87fef0a52d31babcdb3edb8f3089b6420173f..0000000000000000000000000000000000000000 --- a/spaces/vumichien/canvas_controlnet/annotator/uniformer/mmcv_custom/checkpoint.py +++ /dev/null @@ -1,500 +0,0 @@ -# Copyright (c) Open-MMLab. All rights reserved. -import io -import os -import os.path as osp -import pkgutil -import time -import warnings -from collections import OrderedDict -from importlib import import_module -from tempfile import TemporaryDirectory - -import torch -import torchvision -from torch.optim import Optimizer -from torch.utils import model_zoo -from torch.nn import functional as F - -import annotator.uniformer.mmcv as mmcv -from annotator.uniformer.mmcv.fileio import FileClient -from annotator.uniformer.mmcv.fileio import load as load_file -from annotator.uniformer.mmcv.parallel import is_module_wrapper -from annotator.uniformer.mmcv.utils import mkdir_or_exist -from annotator.uniformer.mmcv.runner import get_dist_info - -ENV_MMCV_HOME = 'MMCV_HOME' -ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' -DEFAULT_CACHE_DIR = '~/.cache' - - -def _get_mmcv_home(): - mmcv_home = os.path.expanduser( - os.getenv( - ENV_MMCV_HOME, - os.path.join( - os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv'))) - - mkdir_or_exist(mmcv_home) - return mmcv_home - - -def load_state_dict(module, state_dict, strict=False, logger=None): - """Load state_dict to a module. - - This method is modified from :meth:`torch.nn.Module.load_state_dict`. - Default value for ``strict`` is set to ``False`` and the message for - param mismatch will be shown even if strict is False. - - Args: - module (Module): Module that receives the state_dict. - state_dict (OrderedDict): Weights. - strict (bool): whether to strictly enforce that the keys - in :attr:`state_dict` match the keys returned by this module's - :meth:`~torch.nn.Module.state_dict` function. Default: ``False``. - logger (:obj:`logging.Logger`, optional): Logger to log the error - message. If not specified, print function will be used. - """ - unexpected_keys = [] - all_missing_keys = [] - err_msg = [] - - metadata = getattr(state_dict, '_metadata', None) - state_dict = state_dict.copy() - if metadata is not None: - state_dict._metadata = metadata - - # use _load_from_state_dict to enable checkpoint version control - def load(module, prefix=''): - # recursively check parallel module in case that the model has a - # complicated structure, e.g., nn.Module(nn.Module(DDP)) - if is_module_wrapper(module): - module = module.module - local_metadata = {} if metadata is None else metadata.get( - prefix[:-1], {}) - module._load_from_state_dict(state_dict, prefix, local_metadata, True, - all_missing_keys, unexpected_keys, - err_msg) - for name, child in module._modules.items(): - if child is not None: - load(child, prefix + name + '.') - - load(module) - load = None # break load->load reference cycle - - # ignore "num_batches_tracked" of BN layers - missing_keys = [ - key for key in all_missing_keys if 'num_batches_tracked' not in key - ] - - if unexpected_keys: - err_msg.append('unexpected key in source ' - f'state_dict: {", ".join(unexpected_keys)}\n') - if missing_keys: - err_msg.append( - f'missing keys in source state_dict: {", ".join(missing_keys)}\n') - - rank, _ = get_dist_info() - if len(err_msg) > 0 and rank == 0: - err_msg.insert( - 0, 'The model and loaded state dict do not match exactly\n') - err_msg = '\n'.join(err_msg) - if strict: - raise RuntimeError(err_msg) - elif logger is not None: - logger.warning(err_msg) - else: - print(err_msg) - - -def load_url_dist(url, model_dir=None): - """In distributed setting, this function only download checkpoint at local - rank 0.""" - rank, world_size = get_dist_info() - rank = int(os.environ.get('LOCAL_RANK', rank)) - if rank == 0: - checkpoint = model_zoo.load_url(url, model_dir=model_dir) - if world_size > 1: - torch.distributed.barrier() - if rank > 0: - checkpoint = model_zoo.load_url(url, model_dir=model_dir) - return checkpoint - - -def load_pavimodel_dist(model_path, map_location=None): - """In distributed setting, this function only download checkpoint at local - rank 0.""" - try: - from pavi import modelcloud - except ImportError: - raise ImportError( - 'Please install pavi to load checkpoint from modelcloud.') - rank, world_size = get_dist_info() - rank = int(os.environ.get('LOCAL_RANK', rank)) - if rank == 0: - model = modelcloud.get(model_path) - with TemporaryDirectory() as tmp_dir: - downloaded_file = osp.join(tmp_dir, model.name) - model.download(downloaded_file) - checkpoint = torch.load(downloaded_file, map_location=map_location) - if world_size > 1: - torch.distributed.barrier() - if rank > 0: - model = modelcloud.get(model_path) - with TemporaryDirectory() as tmp_dir: - downloaded_file = osp.join(tmp_dir, model.name) - model.download(downloaded_file) - checkpoint = torch.load( - downloaded_file, map_location=map_location) - return checkpoint - - -def load_fileclient_dist(filename, backend, map_location): - """In distributed setting, this function only download checkpoint at local - rank 0.""" - rank, world_size = get_dist_info() - rank = int(os.environ.get('LOCAL_RANK', rank)) - allowed_backends = ['ceph'] - if backend not in allowed_backends: - raise ValueError(f'Load from Backend {backend} is not supported.') - if rank == 0: - fileclient = FileClient(backend=backend) - buffer = io.BytesIO(fileclient.get(filename)) - checkpoint = torch.load(buffer, map_location=map_location) - if world_size > 1: - torch.distributed.barrier() - if rank > 0: - fileclient = FileClient(backend=backend) - buffer = io.BytesIO(fileclient.get(filename)) - checkpoint = torch.load(buffer, map_location=map_location) - return checkpoint - - -def get_torchvision_models(): - model_urls = dict() - for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__): - if ispkg: - continue - _zoo = import_module(f'torchvision.models.{name}') - if hasattr(_zoo, 'model_urls'): - _urls = getattr(_zoo, 'model_urls') - model_urls.update(_urls) - return model_urls - - -def get_external_models(): - mmcv_home = _get_mmcv_home() - default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json') - default_urls = load_file(default_json_path) - assert isinstance(default_urls, dict) - external_json_path = osp.join(mmcv_home, 'open_mmlab.json') - if osp.exists(external_json_path): - external_urls = load_file(external_json_path) - assert isinstance(external_urls, dict) - default_urls.update(external_urls) - - return default_urls - - -def get_mmcls_models(): - mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json') - mmcls_urls = load_file(mmcls_json_path) - - return mmcls_urls - - -def get_deprecated_model_names(): - deprecate_json_path = osp.join(mmcv.__path__[0], - 'model_zoo/deprecated.json') - deprecate_urls = load_file(deprecate_json_path) - assert isinstance(deprecate_urls, dict) - - return deprecate_urls - - -def _process_mmcls_checkpoint(checkpoint): - state_dict = checkpoint['state_dict'] - new_state_dict = OrderedDict() - for k, v in state_dict.items(): - if k.startswith('backbone.'): - new_state_dict[k[9:]] = v - new_checkpoint = dict(state_dict=new_state_dict) - - return new_checkpoint - - -def _load_checkpoint(filename, map_location=None): - """Load checkpoint from somewhere (modelzoo, file, url). - - Args: - filename (str): Accept local filepath, URL, ``torchvision://xxx``, - ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for - details. - map_location (str | None): Same as :func:`torch.load`. Default: None. - - Returns: - dict | OrderedDict: The loaded checkpoint. It can be either an - OrderedDict storing model weights or a dict containing other - information, which depends on the checkpoint. - """ - if filename.startswith('modelzoo://'): - warnings.warn('The URL scheme of "modelzoo://" is deprecated, please ' - 'use "torchvision://" instead') - model_urls = get_torchvision_models() - model_name = filename[11:] - checkpoint = load_url_dist(model_urls[model_name]) - elif filename.startswith('torchvision://'): - model_urls = get_torchvision_models() - model_name = filename[14:] - checkpoint = load_url_dist(model_urls[model_name]) - elif filename.startswith('open-mmlab://'): - model_urls = get_external_models() - model_name = filename[13:] - deprecated_urls = get_deprecated_model_names() - if model_name in deprecated_urls: - warnings.warn(f'open-mmlab://{model_name} is deprecated in favor ' - f'of open-mmlab://{deprecated_urls[model_name]}') - model_name = deprecated_urls[model_name] - model_url = model_urls[model_name] - # check if is url - if model_url.startswith(('http://', 'https://')): - checkpoint = load_url_dist(model_url) - else: - filename = osp.join(_get_mmcv_home(), model_url) - if not osp.isfile(filename): - raise IOError(f'{filename} is not a checkpoint file') - checkpoint = torch.load(filename, map_location=map_location) - elif filename.startswith('mmcls://'): - model_urls = get_mmcls_models() - model_name = filename[8:] - checkpoint = load_url_dist(model_urls[model_name]) - checkpoint = _process_mmcls_checkpoint(checkpoint) - elif filename.startswith(('http://', 'https://')): - checkpoint = load_url_dist(filename) - elif filename.startswith('pavi://'): - model_path = filename[7:] - checkpoint = load_pavimodel_dist(model_path, map_location=map_location) - elif filename.startswith('s3://'): - checkpoint = load_fileclient_dist( - filename, backend='ceph', map_location=map_location) - else: - if not osp.isfile(filename): - raise IOError(f'{filename} is not a checkpoint file') - checkpoint = torch.load(filename, map_location=map_location) - return checkpoint - - -def load_checkpoint(model, - filename, - map_location='cpu', - strict=False, - logger=None): - """Load checkpoint from a file or URI. - - Args: - model (Module): Module to load checkpoint. - filename (str): Accept local filepath, URL, ``torchvision://xxx``, - ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for - details. - map_location (str): Same as :func:`torch.load`. - strict (bool): Whether to allow different params for the model and - checkpoint. - logger (:mod:`logging.Logger` or None): The logger for error message. - - Returns: - dict or OrderedDict: The loaded checkpoint. - """ - checkpoint = _load_checkpoint(filename, map_location) - # OrderedDict is a subclass of dict - if not isinstance(checkpoint, dict): - raise RuntimeError( - f'No state_dict found in checkpoint file {filename}') - # get state_dict from checkpoint - if 'state_dict' in checkpoint: - state_dict = checkpoint['state_dict'] - elif 'model' in checkpoint: - state_dict = checkpoint['model'] - else: - state_dict = checkpoint - # strip prefix of state_dict - if list(state_dict.keys())[0].startswith('module.'): - state_dict = {k[7:]: v for k, v in state_dict.items()} - - # for MoBY, load model of online branch - if sorted(list(state_dict.keys()))[0].startswith('encoder'): - state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')} - - # reshape absolute position embedding - if state_dict.get('absolute_pos_embed') is not None: - absolute_pos_embed = state_dict['absolute_pos_embed'] - N1, L, C1 = absolute_pos_embed.size() - N2, C2, H, W = model.absolute_pos_embed.size() - if N1 != N2 or C1 != C2 or L != H*W: - logger.warning("Error in loading absolute_pos_embed, pass") - else: - state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) - - # interpolate position bias table if needed - relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k] - for table_key in relative_position_bias_table_keys: - table_pretrained = state_dict[table_key] - table_current = model.state_dict()[table_key] - L1, nH1 = table_pretrained.size() - L2, nH2 = table_current.size() - if nH1 != nH2: - logger.warning(f"Error in loading {table_key}, pass") - else: - if L1 != L2: - S1 = int(L1 ** 0.5) - S2 = int(L2 ** 0.5) - table_pretrained_resized = F.interpolate( - table_pretrained.permute(1, 0).view(1, nH1, S1, S1), - size=(S2, S2), mode='bicubic') - state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) - - # load state_dict - load_state_dict(model, state_dict, strict, logger) - return checkpoint - - -def weights_to_cpu(state_dict): - """Copy a model state_dict to cpu. - - Args: - state_dict (OrderedDict): Model weights on GPU. - - Returns: - OrderedDict: Model weights on GPU. - """ - state_dict_cpu = OrderedDict() - for key, val in state_dict.items(): - state_dict_cpu[key] = val.cpu() - return state_dict_cpu - - -def _save_to_state_dict(module, destination, prefix, keep_vars): - """Saves module state to `destination` dictionary. - - This method is modified from :meth:`torch.nn.Module._save_to_state_dict`. - - Args: - module (nn.Module): The module to generate state_dict. - destination (dict): A dict where state will be stored. - prefix (str): The prefix for parameters and buffers used in this - module. - """ - for name, param in module._parameters.items(): - if param is not None: - destination[prefix + name] = param if keep_vars else param.detach() - for name, buf in module._buffers.items(): - # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d - if buf is not None: - destination[prefix + name] = buf if keep_vars else buf.detach() - - -def get_state_dict(module, destination=None, prefix='', keep_vars=False): - """Returns a dictionary containing a whole state of the module. - - Both parameters and persistent buffers (e.g. running averages) are - included. Keys are corresponding parameter and buffer names. - - This method is modified from :meth:`torch.nn.Module.state_dict` to - recursively check parallel module in case that the model has a complicated - structure, e.g., nn.Module(nn.Module(DDP)). - - Args: - module (nn.Module): The module to generate state_dict. - destination (OrderedDict): Returned dict for the state of the - module. - prefix (str): Prefix of the key. - keep_vars (bool): Whether to keep the variable property of the - parameters. Default: False. - - Returns: - dict: A dictionary containing a whole state of the module. - """ - # recursively check parallel module in case that the model has a - # complicated structure, e.g., nn.Module(nn.Module(DDP)) - if is_module_wrapper(module): - module = module.module - - # below is the same as torch.nn.Module.state_dict() - if destination is None: - destination = OrderedDict() - destination._metadata = OrderedDict() - destination._metadata[prefix[:-1]] = local_metadata = dict( - version=module._version) - _save_to_state_dict(module, destination, prefix, keep_vars) - for name, child in module._modules.items(): - if child is not None: - get_state_dict( - child, destination, prefix + name + '.', keep_vars=keep_vars) - for hook in module._state_dict_hooks.values(): - hook_result = hook(module, destination, prefix, local_metadata) - if hook_result is not None: - destination = hook_result - return destination - - -def save_checkpoint(model, filename, optimizer=None, meta=None): - """Save checkpoint to file. - - The checkpoint will have 3 fields: ``meta``, ``state_dict`` and - ``optimizer``. By default ``meta`` will contain version and time info. - - Args: - model (Module): Module whose params are to be saved. - filename (str): Checkpoint filename. - optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. - meta (dict, optional): Metadata to be saved in checkpoint. - """ - if meta is None: - meta = {} - elif not isinstance(meta, dict): - raise TypeError(f'meta must be a dict or None, but got {type(meta)}') - meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) - - if is_module_wrapper(model): - model = model.module - - if hasattr(model, 'CLASSES') and model.CLASSES is not None: - # save class name to the meta - meta.update(CLASSES=model.CLASSES) - - checkpoint = { - 'meta': meta, - 'state_dict': weights_to_cpu(get_state_dict(model)) - } - # save optimizer state dict in the checkpoint - if isinstance(optimizer, Optimizer): - checkpoint['optimizer'] = optimizer.state_dict() - elif isinstance(optimizer, dict): - checkpoint['optimizer'] = {} - for name, optim in optimizer.items(): - checkpoint['optimizer'][name] = optim.state_dict() - - if filename.startswith('pavi://'): - try: - from pavi import modelcloud - from pavi.exception import NodeNotFoundError - except ImportError: - raise ImportError( - 'Please install pavi to load checkpoint from modelcloud.') - model_path = filename[7:] - root = modelcloud.Folder() - model_dir, model_name = osp.split(model_path) - try: - model = modelcloud.get(model_dir) - except NodeNotFoundError: - model = root.create_training_model(model_dir) - with TemporaryDirectory() as tmp_dir: - checkpoint_file = osp.join(tmp_dir, model_name) - with open(checkpoint_file, 'wb') as f: - torch.save(checkpoint, f) - f.flush() - model.create_file(checkpoint_file, name=model_name) - else: - mmcv.mkdir_or_exist(osp.dirname(filename)) - # immediately flush buffer - with open(filename, 'wb') as f: - torch.save(checkpoint, f) - f.flush() \ No newline at end of file diff --git a/spaces/vumichien/canvas_controlnet/ldm/modules/midas/midas/dpt_depth.py b/spaces/vumichien/canvas_controlnet/ldm/modules/midas/midas/dpt_depth.py deleted file mode 100644 index 4e9aab5d2767dffea39da5b3f30e2798688216f1..0000000000000000000000000000000000000000 --- a/spaces/vumichien/canvas_controlnet/ldm/modules/midas/midas/dpt_depth.py +++ /dev/null @@ -1,109 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -from .base_model import BaseModel -from .blocks import ( - FeatureFusionBlock, - FeatureFusionBlock_custom, - Interpolate, - _make_encoder, - forward_vit, -) - - -def _make_fusion_block(features, use_bn): - return FeatureFusionBlock_custom( - features, - nn.ReLU(False), - deconv=False, - bn=use_bn, - expand=False, - align_corners=True, - ) - - -class DPT(BaseModel): - def __init__( - self, - head, - features=256, - backbone="vitb_rn50_384", - readout="project", - channels_last=False, - use_bn=False, - ): - - super(DPT, self).__init__() - - self.channels_last = channels_last - - hooks = { - "vitb_rn50_384": [0, 1, 8, 11], - "vitb16_384": [2, 5, 8, 11], - "vitl16_384": [5, 11, 17, 23], - } - - # Instantiate backbone and reassemble blocks - self.pretrained, self.scratch = _make_encoder( - backbone, - features, - False, # Set to true of you want to train from scratch, uses ImageNet weights - groups=1, - expand=False, - exportable=False, - hooks=hooks[backbone], - use_readout=readout, - ) - - self.scratch.refinenet1 = _make_fusion_block(features, use_bn) - self.scratch.refinenet2 = _make_fusion_block(features, use_bn) - self.scratch.refinenet3 = _make_fusion_block(features, use_bn) - self.scratch.refinenet4 = _make_fusion_block(features, use_bn) - - self.scratch.output_conv = head - - - def forward(self, x): - if self.channels_last == True: - x.contiguous(memory_format=torch.channels_last) - - layer_1, layer_2, layer_3, layer_4 = forward_vit(self.pretrained, x) - - layer_1_rn = self.scratch.layer1_rn(layer_1) - layer_2_rn = self.scratch.layer2_rn(layer_2) - layer_3_rn = self.scratch.layer3_rn(layer_3) - layer_4_rn = self.scratch.layer4_rn(layer_4) - - path_4 = self.scratch.refinenet4(layer_4_rn) - path_3 = self.scratch.refinenet3(path_4, layer_3_rn) - path_2 = self.scratch.refinenet2(path_3, layer_2_rn) - path_1 = self.scratch.refinenet1(path_2, layer_1_rn) - - out = self.scratch.output_conv(path_1) - - return out - - -class DPTDepthModel(DPT): - def __init__(self, path=None, non_negative=True, **kwargs): - features = kwargs["features"] if "features" in kwargs else 256 - - head = nn.Sequential( - nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1), - Interpolate(scale_factor=2, mode="bilinear", align_corners=True), - nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1), - nn.ReLU(True), - nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), - nn.ReLU(True) if non_negative else nn.Identity(), - nn.Identity(), - ) - - super().__init__(head, **kwargs) - - if path is not None: - self.load(path) - - def forward(self, x): - return super().forward(x).squeeze(dim=1) - diff --git a/spaces/wahaha/u2net_portrait/README.md b/spaces/wahaha/u2net_portrait/README.md deleted file mode 100644 index 1d0f0f924ee22f63c4d50c660b8fe2d41b9525ef..0000000000000000000000000000000000000000 --- a/spaces/wahaha/u2net_portrait/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -python_version: 3.7 -title: U2net_portrait -emoji: 🦀 -colorFrom: indigo -colorTo: green -sdk: gradio -sdk_version: 2.9.4 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/wanfeimsn/stabilityai-stable-diffusion-2-1/app.py b/spaces/wanfeimsn/stabilityai-stable-diffusion-2-1/app.py deleted file mode 100644 index 0160420876923d89f2ab5fccb9f4d13725e29972..0000000000000000000000000000000000000000 --- a/spaces/wanfeimsn/stabilityai-stable-diffusion-2-1/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/stabilityai/stable-diffusion-2-1").launch() \ No newline at end of file diff --git a/spaces/wangrongsheng/ChatImprovement/crazy_functions/test_project/python/dqn/dqn.py b/spaces/wangrongsheng/ChatImprovement/crazy_functions/test_project/python/dqn/dqn.py deleted file mode 100644 index 6cea64d39baa7ff4c1e549869aaa4b0ae17779a9..0000000000000000000000000000000000000000 --- a/spaces/wangrongsheng/ChatImprovement/crazy_functions/test_project/python/dqn/dqn.py +++ /dev/null @@ -1,245 +0,0 @@ -from typing import Any, Dict, List, Optional, Tuple, Type, Union - -import gym -import numpy as np -import torch as th -from torch.nn import functional as F - -from stable_baselines3.common import logger -from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm -from stable_baselines3.common.preprocessing import maybe_transpose -from stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule -from stable_baselines3.common.utils import get_linear_fn, is_vectorized_observation, polyak_update -from stable_baselines3.dqn.policies import DQNPolicy - - -class DQN(OffPolicyAlgorithm): - """ - Deep Q-Network (DQN) - - Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236 - Default hyperparameters are taken from the nature paper, - except for the optimizer and learning rate that were taken from Stable Baselines defaults. - - :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...) - :param env: The environment to learn from (if registered in Gym, can be str) - :param learning_rate: The learning rate, it can be a function - of the current progress remaining (from 1 to 0) - :param buffer_size: size of the replay buffer - :param learning_starts: how many steps of the model to collect transitions for before learning starts - :param batch_size: Minibatch size for each gradient update - :param tau: the soft update coefficient ("Polyak update", between 0 and 1) default 1 for hard update - :param gamma: the discount factor - :param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit - like ``(5, "step")`` or ``(2, "episode")``. - :param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``) - Set to ``-1`` means to do as many gradient steps as steps done in the environment - during the rollout. - :param optimize_memory_usage: Enable a memory efficient variant of the replay buffer - at a cost of more complexity. - See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195 - :param target_update_interval: update the target network every ``target_update_interval`` - environment steps. - :param exploration_fraction: fraction of entire training period over which the exploration rate is reduced - :param exploration_initial_eps: initial value of random action probability - :param exploration_final_eps: final value of random action probability - :param max_grad_norm: The maximum value for the gradient clipping - :param tensorboard_log: the log location for tensorboard (if None, no logging) - :param create_eval_env: Whether to create a second environment that will be - used for evaluating the agent periodically. (Only available when passing string for the environment) - :param policy_kwargs: additional arguments to be passed to the policy on creation - :param verbose: the verbosity level: 0 no output, 1 info, 2 debug - :param seed: Seed for the pseudo random generators - :param device: Device (cpu, cuda, ...) on which the code should be run. - Setting it to auto, the code will be run on the GPU if possible. - :param _init_setup_model: Whether or not to build the network at the creation of the instance - """ - - def __init__( - self, - policy: Union[str, Type[DQNPolicy]], - env: Union[GymEnv, str], - learning_rate: Union[float, Schedule] = 1e-4, - buffer_size: int = 1000000, - learning_starts: int = 50000, - batch_size: Optional[int] = 32, - tau: float = 1.0, - gamma: float = 0.99, - train_freq: Union[int, Tuple[int, str]] = 4, - gradient_steps: int = 1, - optimize_memory_usage: bool = False, - target_update_interval: int = 10000, - exploration_fraction: float = 0.1, - exploration_initial_eps: float = 1.0, - exploration_final_eps: float = 0.05, - max_grad_norm: float = 10, - tensorboard_log: Optional[str] = None, - create_eval_env: bool = False, - policy_kwargs: Optional[Dict[str, Any]] = None, - verbose: int = 0, - seed: Optional[int] = None, - device: Union[th.device, str] = "auto", - _init_setup_model: bool = True, - ): - - super(DQN, self).__init__( - policy, - env, - DQNPolicy, - learning_rate, - buffer_size, - learning_starts, - batch_size, - tau, - gamma, - train_freq, - gradient_steps, - action_noise=None, # No action noise - policy_kwargs=policy_kwargs, - tensorboard_log=tensorboard_log, - verbose=verbose, - device=device, - create_eval_env=create_eval_env, - seed=seed, - sde_support=False, - optimize_memory_usage=optimize_memory_usage, - supported_action_spaces=(gym.spaces.Discrete,), - ) - - self.exploration_initial_eps = exploration_initial_eps - self.exploration_final_eps = exploration_final_eps - self.exploration_fraction = exploration_fraction - self.target_update_interval = target_update_interval - self.max_grad_norm = max_grad_norm - # "epsilon" for the epsilon-greedy exploration - self.exploration_rate = 0.0 - # Linear schedule will be defined in `_setup_model()` - self.exploration_schedule = None - self.q_net, self.q_net_target = None, None - - if _init_setup_model: - self._setup_model() - - def _setup_model(self) -> None: - super(DQN, self)._setup_model() - self._create_aliases() - self.exploration_schedule = get_linear_fn( - self.exploration_initial_eps, self.exploration_final_eps, self.exploration_fraction - ) - - def _create_aliases(self) -> None: - self.q_net = self.policy.q_net - self.q_net_target = self.policy.q_net_target - - def _on_step(self) -> None: - """ - Update the exploration rate and target network if needed. - This method is called in ``collect_rollouts()`` after each step in the environment. - """ - if self.num_timesteps % self.target_update_interval == 0: - polyak_update(self.q_net.parameters(), self.q_net_target.parameters(), self.tau) - - self.exploration_rate = self.exploration_schedule(self._current_progress_remaining) - logger.record("rollout/exploration rate", self.exploration_rate) - - def train(self, gradient_steps: int, batch_size: int = 100) -> None: - # Update learning rate according to schedule - self._update_learning_rate(self.policy.optimizer) - - losses = [] - for _ in range(gradient_steps): - # Sample replay buffer - replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env) - - with th.no_grad(): - # Compute the next Q-values using the target network - next_q_values = self.q_net_target(replay_data.next_observations) - # Follow greedy policy: use the one with the highest value - next_q_values, _ = next_q_values.max(dim=1) - # Avoid potential broadcast issue - next_q_values = next_q_values.reshape(-1, 1) - # 1-step TD target - target_q_values = replay_data.rewards + (1 - replay_data.dones) * self.gamma * next_q_values - - # Get current Q-values estimates - current_q_values = self.q_net(replay_data.observations) - - # Retrieve the q-values for the actions from the replay buffer - current_q_values = th.gather(current_q_values, dim=1, index=replay_data.actions.long()) - - # Compute Huber loss (less sensitive to outliers) - loss = F.smooth_l1_loss(current_q_values, target_q_values) - losses.append(loss.item()) - - # Optimize the policy - self.policy.optimizer.zero_grad() - loss.backward() - # Clip gradient norm - th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm) - self.policy.optimizer.step() - - # Increase update counter - self._n_updates += gradient_steps - - logger.record("train/n_updates", self._n_updates, exclude="tensorboard") - logger.record("train/loss", np.mean(losses)) - - def predict( - self, - observation: np.ndarray, - state: Optional[np.ndarray] = None, - mask: Optional[np.ndarray] = None, - deterministic: bool = False, - ) -> Tuple[np.ndarray, Optional[np.ndarray]]: - """ - Overrides the base_class predict function to include epsilon-greedy exploration. - - :param observation: the input observation - :param state: The last states (can be None, used in recurrent policies) - :param mask: The last masks (can be None, used in recurrent policies) - :param deterministic: Whether or not to return deterministic actions. - :return: the model's action and the next state - (used in recurrent policies) - """ - if not deterministic and np.random.rand() < self.exploration_rate: - if is_vectorized_observation(maybe_transpose(observation, self.observation_space), self.observation_space): - n_batch = observation.shape[0] - action = np.array([self.action_space.sample() for _ in range(n_batch)]) - else: - action = np.array(self.action_space.sample()) - else: - action, state = self.policy.predict(observation, state, mask, deterministic) - return action, state - - def learn( - self, - total_timesteps: int, - callback: MaybeCallback = None, - log_interval: int = 4, - eval_env: Optional[GymEnv] = None, - eval_freq: int = -1, - n_eval_episodes: int = 5, - tb_log_name: str = "DQN", - eval_log_path: Optional[str] = None, - reset_num_timesteps: bool = True, - ) -> OffPolicyAlgorithm: - - return super(DQN, self).learn( - total_timesteps=total_timesteps, - callback=callback, - log_interval=log_interval, - eval_env=eval_env, - eval_freq=eval_freq, - n_eval_episodes=n_eval_episodes, - tb_log_name=tb_log_name, - eval_log_path=eval_log_path, - reset_num_timesteps=reset_num_timesteps, - ) - - def _excluded_save_params(self) -> List[str]: - return super(DQN, self)._excluded_save_params() + ["q_net", "q_net_target"] - - def _get_torch_save_params(self) -> Tuple[List[str], List[str]]: - state_dicts = ["policy", "policy.optimizer"] - - return state_dicts, [] diff --git a/spaces/whgwd2023/bingo/src/lib/utils.ts b/spaces/whgwd2023/bingo/src/lib/utils.ts deleted file mode 100644 index 8de2eba94bf0bc93579d4f489e8b810dbf6ce92a..0000000000000000000000000000000000000000 --- a/spaces/whgwd2023/bingo/src/lib/utils.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { clsx, type ClassValue } from 'clsx' -import { customAlphabet } from 'nanoid' -import { twMerge } from 'tailwind-merge' -// @ts-ignore -import randomip from 'random-ip' -import cidr from './cidr.json' - -export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)) -} - -export const nanoid = customAlphabet( - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', - 7 -) // 7-character random string - -export function createChunkDecoder() { - const decoder = new TextDecoder() - return function (chunk: Uint8Array | undefined): string { - if (!chunk) return '' - return decoder.decode(chunk, { stream: true }) - } -} - -export function random (start: number, end: number) { - return start + Math.floor(Math.random() * (end - start)) -} - -export function randomIP() { - // return `104.${random(0, 21)}.${random(0, 127)}.${random(1, 255)}` - const [ip, range] = cidr.at(random(0, cidr.length))?.split('/')! - return randomip(ip, range) -} - -export const defaultUID = 'xxx' - -export function parseHeadersFromCurl(content: string) { - const re = /-H '([^:]+):\s*([^']+)/mg - const headers: HeadersInit = {} - content = content.replaceAll('-H "', '-H \'').replaceAll('" ^', '\'\\').replaceAll('^\\^"', '"') // 将 cmd curl 转成 bash curl - content.replace(re, (_: string, key: string, value: string) => { - headers[key] = value - return '' - }) - return headers -} - -export const ChunkKeys = ['BING_HEADER', 'BING_HEADER1', 'BING_HEADER2'] -export function encodeHeadersToCookie(content: string) { - const base64Content = btoa(content) - const contentChunks = base64Content.match(/.{1,4000}/g) || [] - return ChunkKeys.map((key, index) => `${key}=${contentChunks[index] ?? ''}`) -} - -export function extraCurlFromCookie(cookies: Partial<{ [key: string]: string }>) { - let base64Content = '' - ChunkKeys.forEach((key) => { - base64Content += (cookies[key] || '') - }) - try { - return atob(base64Content) - } catch(e) { - return '' - } -} - -export function extraHeadersFromCookie(cookies: Partial<{ [key: string]: string }>) { - return parseHeadersFromCurl(extraCurlFromCookie(cookies)) -} - -export function formatDate(input: string | number | Date): string { - const date = new Date(input) - return date.toLocaleDateString('en-US', { - month: 'long', - day: 'numeric', - year: 'numeric' - }) -} - -export function parseCookie(cookie: string, cookieName: string) { - const targetCookie = new RegExp(`(?:[; ]|^)${cookieName}=([^;]*)`).test(cookie) ? RegExp.$1 : cookie - return targetCookie ? decodeURIComponent(targetCookie).trim() : cookie.indexOf('=') === -1 ? cookie.trim() : '' -} - -export function setCookie(key: string, value: string) { - const maxAge = value ? 86400 * 30 : 0 - document.cookie = `${key}=${value || ''}; Path=/; Max-Age=${maxAge}; SameSite=None; Secure` -} - -export function getCookie(cookieName: string) { - const re = new RegExp(`(?:[; ]|^)${cookieName}=([^;]*)`) - return re.test(document.cookie) ? RegExp.$1 : '' -} - -export function parseCookies(cookie: string, cookieNames: string[]) { - const cookies: { [key: string]: string } = {} - cookieNames.forEach(cookieName => { - cookies[cookieName] = parseCookie(cookie, cookieName) - }) - return cookies -} - -export const DEFAULT_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.0.0' - -export function parseUA(ua?: string, default_ua = DEFAULT_UA) { - return / EDGE?/i.test(decodeURIComponent(ua || '')) ? decodeURIComponent(ua!.trim()) : default_ua -} - -export function mockUser(cookies: Partial<{ [key: string]: string }>) { - const { - BING_UA = process.env.BING_UA, - BING_IP, - _U = defaultUID, - } = cookies - const ua = parseUA(BING_UA) - - return { - 'x-forwarded-for': BING_IP!, - 'Accept-Encoding': 'gzip, deflate, br', - 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', - 'User-Agent': ua!, - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.3 OS/Win32', - cookie: `_U=${_U}` || '', - } -} - -export function createHeaders(cookies: Partial<{ [key: string]: string }>, type?: string) { - let { - BING_HEADER = process.env.BING_HEADER, - BING_IP, - IMAGE_ONLY = process.env.IMAGE_ONLY ?? '1', - } = cookies - const imageOnly = /^(1|true|yes)$/.test(String(IMAGE_ONLY)) - if (BING_HEADER) { - if ( - (imageOnly && type === 'image') - || !imageOnly - ) { - const headers = extraHeadersFromCookie({ - BING_HEADER, - ...cookies, - }) || {} - headers['x-forward-for'] = BING_IP! - return headers - } - } - return mockUser(cookies) -} - -export class WatchDog { - private tid = 0 - watch(fn: Function, timeout = 2000) { - clearTimeout(this.tid) - this.tid = setTimeout(fn, timeout + Math.random() * 1000) - } - reset() { - clearTimeout(this.tid) - } -} diff --git a/spaces/williamzhou2023/GPT2/assets/Kelpy-Codos.js b/spaces/williamzhou2023/GPT2/assets/Kelpy-Codos.js deleted file mode 100644 index cfbaeedb4f371dfb5fe157db545b364046fca3e1..0000000000000000000000000000000000000000 --- a/spaces/williamzhou2023/GPT2/assets/Kelpy-Codos.js +++ /dev/null @@ -1,76 +0,0 @@ -// ==UserScript== -// @name Kelpy Codos -// @namespace https://github.com/Keldos-Li/Kelpy-Codos -// @version 1.0.5 -// @author Keldos; https://keldos.me/ -// @description Add copy button to PRE tags before CODE tag, for Chuanhu ChatGPT especially. -// Based on Chuanhu ChatGPT version: ac04408 (2023-3-22) -// @license GPL-3.0 -// @grant none -// ==/UserScript== - -(function () { - 'use strict'; - - function addCopyButton(pre) { - var code = pre.querySelector('code'); - if (!code) { - return; // 如果没有找到 元素,则不添加按钮 - } - var firstChild = code.firstChild; - if (!firstChild) { - return; // 如果 元素没有子节点,则不添加按钮 - } - var button = document.createElement('button'); - button.textContent = '\uD83D\uDCCE'; // 使用 📎 符号作为“复制”按钮的文本 - button.style.position = 'relative'; - button.style.float = 'right'; - button.style.fontSize = '1em'; // 可选:调整按钮大小 - button.style.background = 'none'; // 可选:去掉背景颜色 - button.style.border = 'none'; // 可选:去掉边框 - button.style.cursor = 'pointer'; // 可选:显示指针样式 - button.addEventListener('click', function () { - var range = document.createRange(); - range.selectNodeContents(code); - range.setStartBefore(firstChild); // 将范围设置为第一个子节点之前 - var selection = window.getSelection(); - selection.removeAllRanges(); - selection.addRange(range); - - try { - var success = document.execCommand('copy'); - if (success) { - button.textContent = '\u2714'; - setTimeout(function () { - button.textContent = '\uD83D\uDCCE'; // 恢复按钮为“复制” - }, 2000); - } else { - button.textContent = '\u2716'; - } - } catch (e) { - console.error(e); - button.textContent = '\u2716'; - } - - selection.removeAllRanges(); - }); - code.insertBefore(button, firstChild); // 将按钮插入到第一个子元素之前 - } - - function handleNewElements(mutationsList, observer) { - for (var mutation of mutationsList) { - if (mutation.type === 'childList') { - for (var node of mutation.addedNodes) { - if (node.nodeName === 'PRE') { - addCopyButton(node); - } - } - } - } - } - - var observer = new MutationObserver(handleNewElements); - observer.observe(document.documentElement, { childList: true, subtree: true }); - - document.querySelectorAll('pre').forEach(addCopyButton); -})(); diff --git a/spaces/wuhuik/bingo/tests/kblob.ts b/spaces/wuhuik/bingo/tests/kblob.ts deleted file mode 100644 index 9e15b41c1c94a690beb61b23cdb42fc78767ccd2..0000000000000000000000000000000000000000 --- a/spaces/wuhuik/bingo/tests/kblob.ts +++ /dev/null @@ -1,27 +0,0 @@ -import FormData from 'form-data' - -import { fetch } from '@/lib/isomorphic' - -const formData = new FormData() - -const knowledgeRequest = {"imageInfo":{"url":"https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png"},"knowledgeRequest":{"invokedSkills":["ImageById"],"subscriptionId":"Bing.Chat.Multimodal","invokedSkillsRequestData":{"enableFaceBlur":true},"convoData":{"convoid":"51D|BingProdUnAuthenticatedUsers|E3DCA904FF236C67C3450163BCEC64CFF3F618CC8A4AFD75FD518F5ED0ADA080","convotone":"Creative"}}} - -formData.append('knowledgeRequest', JSON.stringify(knowledgeRequest)) - - -fetch('https://bing.vcanbb.top/images/kblob', - { - method: 'POST', - body: formData.getBuffer(), - headers: { - "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"", - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-platform": "\"Windows\"", - "Referer": "https://bing.vcanbb.top/web/index.html", - "Referrer-Policy": "origin-when-cross-origin", - ...formData.getHeaders() - } - - } -).then(res => res.text()) -.then(res => console.log('res', res)) diff --git a/spaces/xuetao/bingo3/postcss.config.js b/spaces/xuetao/bingo3/postcss.config.js deleted file mode 100644 index 33ad091d26d8a9dc95ebdf616e217d985ec215b8..0000000000000000000000000000000000000000 --- a/spaces/xuetao/bingo3/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} diff --git a/spaces/xujunhao/AudioLM/app.py b/spaces/xujunhao/AudioLM/app.py deleted file mode 100644 index 304566c2a04e4e98dfcde963b139c681913c98bf..0000000000000000000000000000000000000000 --- a/spaces/xujunhao/AudioLM/app.py +++ /dev/null @@ -1,105 +0,0 @@ -import gradio as gr -import torch -from diffusers import AudioLDMPipeline - -from transformers import AutoProcessor, ClapModel - - -device = "cpu" -torch_dtype = torch.float32 - -repo_id = "cvssp/audioldm-m-full" -pipe = AudioLDMPipeline.from_pretrained(repo_id, torch_dtype=torch_dtype).to(device) -pipe.unet = torch.compile(pipe.unet) - - -clap_model = ClapModel.from_pretrained("sanchit-gandhi/clap-htsat-unfused-m-full").to(device) -processor = AutoProcessor.from_pretrained("sanchit-gandhi/clap-htsat-unfused-m-full") - -generator = torch.Generator(device) - - -def text2audio(text, negative_prompt, duration, guidance_scale, random_seed, n_candidates): - if text is None: - raise gr.Error("请提供文本输入") - - waveforms = pipe( - text, - audio_length_in_s=duration, - guidance_scale=guidance_scale, - negative_prompt=negative_prompt, - num_waveforms_per_prompt=n_candidates if n_candidates else 1, - generator=generator.manual_seed(int(random_seed)), - )["audios"] - - if waveforms.shape[0] > 1: - waveform = score_waveforms(text, waveforms) - else: - waveform = waveforms[0] - - return gr.make_waveform((16000, waveform)) - - -def score_waveforms(text, waveforms): - inputs = processor(text=text, audios=list(waveforms), return_tensors="pt", padding=True) - inputs = {key: inputs[key].to(device) for key in inputs} - with torch.no_grad(): - logits_per_text = clap_model(**inputs).logits_per_text - probs = logits_per_text.softmax(dim=-1) - most_probable = torch.argmax(probs) - waveform = waveforms[most_probable] - return waveform - - -iface = gr.Blocks() - -with iface: - with gr.Group(): - with gr.Box(): - textbox = gr.Textbox( - max_lines=1, - label="要求", - info="要求", - elem_id="prompt-in", - ) - negative_textbox = gr.Textbox( - max_lines=1, - label="更详细的要求", - info="更详细的要求", - elem_id="prompt-in", - ) - - with gr.Accordion("展开更多选项", open=False): - seed = gr.Number( - value=45, - label="种子", - info="不同种子有不同结果,相同种子有相同结果", - ) - duration = gr.Slider(2.5, 10, value=5, step=2.5, label="持续时间(秒)") - guidance_scale = gr.Slider( - 0, - 4, - value=2.5, - step=0.5, - label="质量", - info="大有更好的质量和与文本的相关性;小有更好的多样性", - ) - n_candidates = gr.Slider( - 1, - 3, - value=3, - step=1, - label="候选数量", - info="这个数字控制候选数量", - ) - - outputs = gr.Video(label="Output", elem_id="output-video") - btn = gr.Button("Submit").style(full_width=True) - - btn.click( - text2audio, - inputs=[textbox, negative_textbox, duration, guidance_scale, seed, n_candidates], - outputs=[outputs], - ) - -iface.queue(max_size=10).launch(debug=True) diff --git a/spaces/yangogo/bingo/src/components/ui/input.tsx b/spaces/yangogo/bingo/src/components/ui/input.tsx deleted file mode 100644 index 684a857f3d769b78818fb13de1abaebfb09ca79c..0000000000000000000000000000000000000000 --- a/spaces/yangogo/bingo/src/components/ui/input.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from 'react' - -import { cn } from '@/lib/utils' - -export interface InputProps - extends React.InputHTMLAttributes {} - -const Input = React.forwardRef( - ({ className, type, ...props }, ref) => { - return ( - - ) - } -) -Input.displayName = 'Input' - -export { Input } diff --git a/spaces/yardi/phrase-semantic-similarity/README.md b/spaces/yardi/phrase-semantic-similarity/README.md deleted file mode 100644 index 2939d5a5f6767d8599af112256fd9067fc7dff6d..0000000000000000000000000000000000000000 --- a/spaces/yardi/phrase-semantic-similarity/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Phrase Semantic Similarity -emoji: 🐨 -colorFrom: purple -colorTo: green -sdk: streamlit -sdk_version: 1.21.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/blenderbot/tokenization_blenderbot_fast.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/blenderbot/tokenization_blenderbot_fast.py deleted file mode 100644 index fdd490b12adcf9b66027f7114c6445215f648530..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/blenderbot/tokenization_blenderbot_fast.py +++ /dev/null @@ -1,315 +0,0 @@ -# coding=utf-8 -# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Fast Tokenization class for Blenderbot.""" -import json -from typing import List, Optional, Tuple - -from tokenizers import pre_tokenizers, processors - -from ...tokenization_utils_base import AddedToken, BatchEncoding -from ...tokenization_utils_fast import PreTrainedTokenizerFast -from ...utils import logging -from .tokenization_blenderbot import BlenderbotTokenizer - - -logger = logging.get_logger(__name__) - - -VOCAB_FILES_NAMES = { - "vocab_file": "vocab.json", - "merges_file": "merges.txt", - "tokenizer_config_file": "tokenizer_config.json", -} - -PRETRAINED_VOCAB_FILES_MAP = { - "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"}, - "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"}, - "tokenizer_config_file": { - "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json" - }, -} - -PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot-3B": 128} - - -class BlenderbotTokenizerFast(PreTrainedTokenizerFast): - """ - Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 - tokenizer, using byte-level Byte-Pair-Encoding. - - This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will - be encoded differently whether it is at the beginning of the sentence (without space) or not: - - ```python - >>> from transformers import BlenderbotTokenizerFast - - >>> tokenizer = BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B") - >>> tokenizer("Hello world")["input_ids"] - [6950, 1085, 2] - - >>> tokenizer(" Hello world")["input_ids"] - [6950, 1085, 2] - ``` - - You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you - call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance. - - - - When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`. - - - - This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should - refer to this superclass for more information regarding those methods. - - Args: - vocab_file (`str`): - Path to the vocabulary file. - merges_file (`str`): - Path to the merges file. - errors (`str`, *optional*, defaults to `"replace"`): - Paradigm to follow when decoding bytes to UTF-8. See - [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information. - bos_token (`str`, *optional*, defaults to `""`): - The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. - - - - When building a sequence using special tokens, this is not the token that is used for the beginning of - sequence. The token used is the `cls_token`. - - - - eos_token (`str`, *optional*, defaults to `""`): - The end of sequence token. - - - - When building a sequence using special tokens, this is not the token that is used for the end of sequence. - The token used is the `sep_token`. - - - - sep_token (`str`, *optional*, defaults to `""`): - The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for - sequence classification or for a text and a question for question answering. It is also used as the last - token of a sequence built with special tokens. - cls_token (`str`, *optional*, defaults to `""`): - The classifier token which is used when doing sequence classification (classification of the whole sequence - instead of per-token classification). It is the first token of the sequence when built with special tokens. - unk_token (`str`, *optional*, defaults to `""`): - The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this - token instead. - pad_token (`str`, *optional*, defaults to `""`): - The token used for padding, for example when batching sequences of different lengths. - mask_token (`str`, *optional*, defaults to `""`): - The token used for masking values. This is the token used when training this model with masked language - modeling. This is the token which the model will try to predict. - add_prefix_space (`bool`, *optional*, defaults to `False`): - Whether or not to add an initial space to the input. This allows to treat the leading word just as any - other word. (Blenderbot tokenizer detect beginning of words by the preceding space). - trim_offsets (`bool`, *optional*, defaults to `True`): - Whether the post processing step should trim offsets to avoid including whitespaces. - """ - - vocab_files_names = VOCAB_FILES_NAMES - pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP - max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES - model_input_names = ["input_ids", "attention_mask"] - slow_tokenizer_class = BlenderbotTokenizer - - # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot - def __init__( - self, - vocab_file=None, - merges_file=None, - tokenizer_file=None, - errors="replace", - bos_token="", - eos_token="", - sep_token="", - cls_token="", - unk_token="", - pad_token="", - mask_token="", - add_prefix_space=False, - trim_offsets=True, - **kwargs, - ): - mask_token = ( - AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False) - if isinstance(mask_token, str) - else mask_token - ) - super().__init__( - vocab_file, - merges_file, - tokenizer_file=tokenizer_file, - errors=errors, - bos_token=bos_token, - eos_token=eos_token, - sep_token=sep_token, - cls_token=cls_token, - unk_token=unk_token, - pad_token=pad_token, - mask_token=mask_token, - add_prefix_space=add_prefix_space, - trim_offsets=trim_offsets, - **kwargs, - ) - - pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) - if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space: - pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type")) - pre_tok_state["add_prefix_space"] = add_prefix_space - self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state) - - self.add_prefix_space = add_prefix_space - - tokenizer_component = "post_processor" - tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None) - if tokenizer_component_instance: - state = json.loads(tokenizer_component_instance.__getstate__()) - - # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` - if "sep" in state: - state["sep"] = tuple(state["sep"]) - if "cls" in state: - state["cls"] = tuple(state["cls"]) - - changes_to_apply = False - - if state.get("add_prefix_space", add_prefix_space) != add_prefix_space: - state["add_prefix_space"] = add_prefix_space - changes_to_apply = True - - if state.get("trim_offsets", trim_offsets) != trim_offsets: - state["trim_offsets"] = trim_offsets - changes_to_apply = True - - if changes_to_apply: - component_class = getattr(processors, state.pop("type")) - new_value = component_class(**state) - setattr(self.backend_tokenizer, tokenizer_component, new_value) - - @property - # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot - def mask_token(self) -> str: - """ - `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not - having been set. - - Blenderbot tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will - greedily comprise the space before the **. - """ - if self._mask_token is None: - if self.verbose: - logger.error("Using mask_token, but it is not set yet.") - return None - return str(self._mask_token) - - @mask_token.setter - def mask_token(self, value): - """ - Overriding the default behavior of the mask token to have it eat the space before it. - - This is needed to preserve backward compatibility with all the previously used models based on Roberta. - """ - # Mask token behave like a normal word, i.e. include the space before it - # So we set lstrip to True - value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value - self._mask_token = value - - # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._batch_encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot - def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding: - is_split_into_words = kwargs.get("is_split_into_words", False) - assert self.add_prefix_space or not is_split_into_words, ( - f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " - "to use it with pretokenized inputs." - ) - - return super()._batch_encode_plus(*args, **kwargs) - - # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot - def _encode_plus(self, *args, **kwargs) -> BatchEncoding: - is_split_into_words = kwargs.get("is_split_into_words", False) - - assert self.add_prefix_space or not is_split_into_words, ( - f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " - "to use it with pretokenized inputs." - ) - - return super()._encode_plus(*args, **kwargs) - - # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot - def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: - files = self._tokenizer.model.save(save_directory, name=filename_prefix) - return tuple(files) - - # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot - def create_token_type_ids_from_sequences( - self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None - ) -> List[int]: - """ - Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does - not make use of token type ids, therefore a list of zeros is returned. - - Args: - token_ids_0 (`List[int]`): - List of IDs. - token_ids_1 (`List[int]`, *optional*): - Optional second list of IDs for sequence pairs. - - Returns: - `List[int]`: List of zeros. - """ - sep = [self.sep_token_id] - cls = [self.cls_token_id] - - if token_ids_1 is None: - return len(cls + token_ids_0 + sep) * [0] - return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0] - - def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None): - """ - Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and - adding special tokens. A Blenderbot sequence has the following format: - - single sequence: ` X ` - - Args: - token_ids_0 (`List[int]`): - List of IDs to which the special tokens will be added - token_ids_1 (`List[int]`, *optional*): - Will be ignored - Returns: - `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens. - """ - return token_ids_0 + [self.eos_token_id] - - @property - # Copied from transformers.models.blenderbot.tokenization_blenderbot.BlenderbotTokenizer.default_chat_template - def default_chat_template(self): - """ - A very simple chat template that just adds whitespace between messages. - """ - return ( - "{% for message in messages %}" - "{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}" - "{{ message['content'] }}" - "{% if not loop.last %}{{ ' ' }}{% endif %}" - "{% endfor %}" - "{{ eos_token }}" - ) diff --git a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/docs/tutorials/README.md b/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/docs/tutorials/README.md deleted file mode 100644 index 1ca9c94d042ef838143a45490fe6b4556c19f3c9..0000000000000000000000000000000000000000 --- a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/docs/tutorials/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Read the docs: - -The latest documentation built from this directory is available at [detectron2.readthedocs.io](https://detectron2.readthedocs.io/). -Documents in this directory are not meant to be read on github. diff --git a/spaces/yuhanbo/chat-gpt/app/api/chat/route.ts b/spaces/yuhanbo/chat-gpt/app/api/chat/route.ts deleted file mode 100644 index 18c7db148fc0bd3de35f5f97aa2f8fbbe9439d07..0000000000000000000000000000000000000000 --- a/spaces/yuhanbo/chat-gpt/app/api/chat/route.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { OpenAIApi, Configuration } from "openai"; -import { ChatRequest } from "./typing"; - -export async function POST(req: Request) { - try { - let apiKey = process.env.OPENAI_API_KEY; - - const userApiKey = req.headers.get("token"); - if (userApiKey) { - apiKey = userApiKey; - } - - const openai = new OpenAIApi( - new Configuration({ - apiKey, - }) - ); - - const requestBody = (await req.json()) as ChatRequest; - const completion = await openai!.createChatCompletion({ - ...requestBody, - }); - - return new Response(JSON.stringify(completion.data)); - } catch (e) { - console.error("[Chat] ", e); - return new Response(JSON.stringify(e)); - } -} diff --git a/spaces/zetavg/LLaMA-LoRA-Tuner-UI-Demo/llama_lora/lib/get_device.py b/spaces/zetavg/LLaMA-LoRA-Tuner-UI-Demo/llama_lora/lib/get_device.py deleted file mode 100644 index 559a6dcbdcb02150d713a0dfb0bd35af1702faea..0000000000000000000000000000000000000000 --- a/spaces/zetavg/LLaMA-LoRA-Tuner-UI-Demo/llama_lora/lib/get_device.py +++ /dev/null @@ -1,16 +0,0 @@ -import importlib - - -def get_device(): - torch = importlib.import_module('torch') - device ="cpu" - if torch.cuda.is_available(): - device = "cuda" - - try: - if torch.backends.mps.is_available(): - device = "mps" - except: # noqa: E722 - pass - - return device diff --git a/spaces/zhang-wei-jian/docker/node_modules/nodemon/lib/config/command.js b/spaces/zhang-wei-jian/docker/node_modules/nodemon/lib/config/command.js deleted file mode 100644 index 9839b5c7cba45e7df6217b23fe82bcb5cefc7dcd..0000000000000000000000000000000000000000 --- a/spaces/zhang-wei-jian/docker/node_modules/nodemon/lib/config/command.js +++ /dev/null @@ -1,43 +0,0 @@ -module.exports = command; - -/** - * command constructs the executable command to run in a shell including the - * user script, the command arguments. - * - * @param {Object} settings Object as: - * { execOptions: { - * exec: String, - * [script: String], - * [scriptPosition: Number], - * [execArgs: Array] - * } - * } - * @return {Object} an object with the node executable and the - * arguments to the command - */ -function command(settings) { - var options = settings.execOptions; - var executable = options.exec; - var args = []; - - // after "executable" go the exec args (like --debug, etc) - if (options.execArgs) { - [].push.apply(args, options.execArgs); - } - - // then goes the user's script arguments - if (options.args) { - [].push.apply(args, options.args); - } - - // after the "executable" goes the user's script - if (options.script) { - args.splice((options.scriptPosition || 0) + - options.execArgs.length, 0, options.script); - } - - return { - executable: executable, - args: args, - }; -} diff --git a/spaces/zhanghaohui/szu-gpt-academic/crazy_functions/test_project/latex/attention/parameter_attention.tex b/spaces/zhanghaohui/szu-gpt-academic/crazy_functions/test_project/latex/attention/parameter_attention.tex deleted file mode 100644 index 7bc4fe452dbdbfe44ff72f0cdbd37acd5c786ce6..0000000000000000000000000000000000000000 --- a/spaces/zhanghaohui/szu-gpt-academic/crazy_functions/test_project/latex/attention/parameter_attention.tex +++ /dev/null @@ -1,45 +0,0 @@ -\pagebreak -\section*{Two Feed-Forward Layers = Attention over Parameters}\label{sec:parameter_attention} - -In addition to attention layers, our model contains position-wise feed-forward networks (Section \ref{sec:ffn}), which consist of two linear transformations with a ReLU activation in between. In fact, these networks too can be seen as a form of attention. Compare the formula for such a network with the formula for a simple dot-product attention layer (biases and scaling factors omitted): - -\begin{align*} - FFN(x, W_1, W_2) = ReLU(xW_1)W_2 \\ - A(q, K, V) = Softmax(qK^T)V -\end{align*} - -Based on the similarity of these formulae, the two-layer feed-forward network can be seen as a kind of attention, where the keys and values are the rows of the trainable parameter matrices $W_1$ and $W_2$, and where we use ReLU instead of Softmax in the compatibility function. - -%the compatablity function is $compat(q, k_i) = ReLU(q \cdot k_i)$ instead of $Softmax(qK_T)_i$. - -Given this similarity, we experimented with replacing the position-wise feed-forward networks with attention layers similar to the ones we use everywhere else our model. The multi-head-attention-over-parameters sublayer is identical to the multi-head attention described in \ref{sec:multihead}, except that the "keys" and "values" inputs to each attention head are trainable model parameters, as opposed to being linear projections of a previous layer. These parameters are scaled up by a factor of $\sqrt{d_{model}}$ in order to be more similar to activations. - -In our first experiment, we replaced each position-wise feed-forward network with a multi-head-attention-over-parameters sublayer with $h_p=8$ heads, key-dimensionality $d_{pk}=64$, and value-dimensionality $d_{pv}=64$, using $n_p=1536$ key-value pairs for each attention head. The sublayer has a total of $2097152$ parameters, including the parameters in the query projection and the output projection. This matches the number of parameters in the position-wise feed-forward network that we replaced. While the theoretical amount of computation is also the same, in practice, the attention version caused the step times to be about 30\% longer. - -In our second experiment, we used $h_p=8$ heads, and $n_p=512$ key-value pairs for each attention head, again matching the total number of parameters in the base model. - -Results for the first experiment were slightly worse than for the base model, and results for the second experiment were slightly better, see Table~\ref{tab:parameter_attention}. - -\begin{table}[h] -\caption{Replacing the position-wise feed-forward networks with multihead-attention-over-parameters produces similar results to the base model. All metrics are on the English-to-German translation development set, newstest2013.} -\label{tab:parameter_attention} -\begin{center} -\vspace{-2mm} -%\scalebox{1.0}{ -\begin{tabular}{c|cccccc|cccc} -\hline\rule{0pt}{2.0ex} - & \multirow{2}{*}{$\dmodel$} & \multirow{2}{*}{$\dff$} & -\multirow{2}{*}{$h_p$} & \multirow{2}{*}{$d_{pk}$} & \multirow{2}{*}{$d_{pv}$} & - \multirow{2}{*}{$n_p$} & - PPL & BLEU & params & training\\ - & & & & & & & (dev) & (dev) & $\times10^6$ & time \\ -\hline\rule{0pt}{2.0ex} -base & 512 & 2048 & & & & & 4.92 & 25.8 & 65 & 12 hours\\ -\hline\rule{0pt}{2.0ex} -AOP$_1$ & 512 & & 8 & 64 & 64 & 1536 & 4.92& 25.5 & 65 & 16 hours\\ -AOP$_2$ & 512 & & 16 & 64 & 64 & 512 & \textbf{4.86} & \textbf{25.9} & 65 & 16 hours \\ -\hline -\end{tabular} -%} -\end{center} -\end{table} diff --git a/spaces/zhuyuheng/IMossGPT/ChuanhuChatbot.py b/spaces/zhuyuheng/IMossGPT/ChuanhuChatbot.py deleted file mode 100644 index cbf63e52857a1852658fdf2009ca26f9fb0a6bec..0000000000000000000000000000000000000000 --- a/spaces/zhuyuheng/IMossGPT/ChuanhuChatbot.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding:utf-8 -*- -import os -import logging -import sys - -import gradio as gr - -from modules import config -from modules.config import * -from modules.utils import * -from modules.presets import * -from modules.overwrites import * -from modules.models import get_model - - -gr.Chatbot._postprocess_chat_messages = postprocess_chat_messages -gr.Chatbot.postprocess = postprocess -PromptHelper.compact_text_chunks = compact_text_chunks - -with open("assets/custom.css", "r", encoding="utf-8") as f: - customCSS = f.read() - -def create_new_model(): - return get_model(model_name = MODELS[DEFAULT_MODEL], access_key = my_api_key)[0] - -with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo: - user_name = gr.State("") - promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2)) - user_question = gr.State("") - user_api_key = gr.State(my_api_key) - current_model = gr.State(create_new_model) - - topic = gr.State(i18n("未命名对话历史记录")) - - with gr.Row(): - gr.HTML(CHUANHU_TITLE, elem_id="app_title") - status_display = gr.Markdown(get_geoip(), elem_id="status_display") - with gr.Row(elem_id="float_display"): - user_info = gr.Markdown(value="getting user info...", elem_id="user_info") - - # https://github.com/gradio-app/gradio/pull/3296 - def create_greeting(request: gr.Request): - if hasattr(request, "username") and request.username: # is not None or is not "" - logging.info(f"Get User Name: {request.username}") - return gr.Markdown.update(value=f"User: {request.username}"), request.username - else: - return gr.Markdown.update(value=f"User: default", visible=False), "" - demo.load(create_greeting, inputs=None, outputs=[user_info, user_name]) - - with gr.Row().style(equal_height=True): - with gr.Column(scale=5): - with gr.Row(): - chatbot = gr.Chatbot(elem_id="chuanhu_chatbot").style(height="100%") - with gr.Row(): - with gr.Column(min_width=225, scale=12): - user_input = gr.Textbox( - elem_id="user_input_tb", - show_label=False, placeholder=i18n("在这里输入") - ).style(container=False) - with gr.Column(min_width=42, scale=1): - submitBtn = gr.Button(value="", variant="primary", elem_id="submit_btn") - cancelBtn = gr.Button(value="", variant="secondary", visible=False, elem_id="cancel_btn") - with gr.Row(): - emptyBtn = gr.Button( - i18n("🧹 新的对话"), - ) - retryBtn = gr.Button(i18n("🔄 重新生成")) - delFirstBtn = gr.Button(i18n("🗑️ 删除最旧对话")) - delLastBtn = gr.Button(i18n("🗑️ 删除最新对话")) - with gr.Row(visible=False) as like_dislike_area: - with gr.Column(min_width=20, scale=1): - likeBtn = gr.Button(i18n("👍")) - with gr.Column(min_width=20, scale=1): - dislikeBtn = gr.Button(i18n("👎")) - - with gr.Column(): - with gr.Column(min_width=50, scale=1): - with gr.Tab(label=i18n("模型")): - keyTxt = gr.Textbox( - show_label=True, - placeholder=f"Your API-key...", - value=hide_middle_chars(user_api_key.value), - type="password", - visible=not HIDE_MY_KEY, - label="API-Key", - ) - if multi_api_key: - usageTxt = gr.Markdown(i18n("多账号模式已开启,无需输入key,可直接开始对话"), elem_id="usage_display", elem_classes="insert_block") - else: - usageTxt = gr.Markdown(i18n("**发送消息** 或 **提交key** 以显示额度"), elem_id="usage_display", elem_classes="insert_block") - model_select_dropdown = gr.Dropdown( - label=i18n("选择模型"), choices=MODELS, multiselect=False, value=MODELS[DEFAULT_MODEL], interactive=True - ) - lora_select_dropdown = gr.Dropdown( - label=i18n("选择LoRA模型"), choices=[], multiselect=False, interactive=True, visible=False - ) - with gr.Row(): - use_streaming_checkbox = gr.Checkbox( - label=i18n("实时传输回答"), value=True, visible=ENABLE_STREAMING_OPTION - ) - single_turn_checkbox = gr.Checkbox(label=i18n("单轮对话"), value=False) - use_websearch_checkbox = gr.Checkbox(label=i18n("使用在线搜索"), value=False) - language_select_dropdown = gr.Dropdown( - label=i18n("选择回复语言(针对搜索&索引功能)"), - choices=REPLY_LANGUAGES, - multiselect=False, - value=REPLY_LANGUAGES[0], - ) - index_files = gr.Files(label=i18n("上传"), type="file") - two_column = gr.Checkbox(label=i18n("双栏pdf"), value=advance_docs["pdf"].get("two_column", False)) - # TODO: 公式ocr - # formula_ocr = gr.Checkbox(label=i18n("识别公式"), value=advance_docs["pdf"].get("formula_ocr", False)) - - with gr.Tab(label="Prompt"): - systemPromptTxt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入System Prompt..."), - label="System prompt", - value=INITIAL_SYSTEM_PROMPT, - lines=10, - ).style(container=False) - with gr.Accordion(label=i18n("加载Prompt模板"), open=True): - with gr.Column(): - with gr.Row(): - with gr.Column(scale=6): - templateFileSelectDropdown = gr.Dropdown( - label=i18n("选择Prompt模板集合文件"), - choices=get_template_names(plain=True), - multiselect=False, - value=get_template_names(plain=True)[0], - ).style(container=False) - with gr.Column(scale=1): - templateRefreshBtn = gr.Button(i18n("🔄 刷新")) - with gr.Row(): - with gr.Column(): - templateSelectDropdown = gr.Dropdown( - label=i18n("从Prompt模板中加载"), - choices=load_template( - get_template_names(plain=True)[0], mode=1 - ), - multiselect=False, - ).style(container=False) - - with gr.Tab(label=i18n("保存/加载")): - with gr.Accordion(label=i18n("保存/加载对话历史记录"), open=True): - with gr.Column(): - with gr.Row(): - with gr.Column(scale=6): - historyFileSelectDropdown = gr.Dropdown( - label=i18n("从列表中加载对话"), - choices=get_history_names(plain=True), - multiselect=False, - value=get_history_names(plain=True)[0], - ) - with gr.Column(scale=1): - historyRefreshBtn = gr.Button(i18n("🔄 刷新")) - with gr.Row(): - with gr.Column(scale=6): - saveFileName = gr.Textbox( - show_label=True, - placeholder=i18n("设置文件名: 默认为.json,可选为.md"), - label=i18n("设置保存文件名"), - value=i18n("对话历史记录"), - ).style(container=True) - with gr.Column(scale=1): - saveHistoryBtn = gr.Button(i18n("💾 保存对话")) - exportMarkdownBtn = gr.Button(i18n("📝 导出为Markdown")) - gr.Markdown(i18n("默认保存于history文件夹")) - with gr.Row(): - with gr.Column(): - downloadFile = gr.File(interactive=True) - - with gr.Tab(label=i18n("高级")): - gr.Markdown(i18n("# ⚠️ 务必谨慎更改 ⚠️\n\n如果无法使用请恢复默认设置")) - gr.HTML(APPEARANCE_SWITCHER, elem_classes="insert_block") - with gr.Accordion(i18n("参数"), open=False): - temperature_slider = gr.Slider( - minimum=-0, - maximum=2.0, - value=1.0, - step=0.1, - interactive=True, - label="temperature", - ) - top_p_slider = gr.Slider( - minimum=-0, - maximum=1.0, - value=1.0, - step=0.05, - interactive=True, - label="top-p", - ) - n_choices_slider = gr.Slider( - minimum=1, - maximum=10, - value=1, - step=1, - interactive=True, - label="n choices", - ) - stop_sequence_txt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入停止符,用英文逗号隔开..."), - label="stop", - value="", - lines=1, - ) - max_context_length_slider = gr.Slider( - minimum=1, - maximum=32768, - value=2000, - step=1, - interactive=True, - label="max context", - ) - max_generation_slider = gr.Slider( - minimum=1, - maximum=32768, - value=1000, - step=1, - interactive=True, - label="max generations", - ) - presence_penalty_slider = gr.Slider( - minimum=-2.0, - maximum=2.0, - value=0.0, - step=0.01, - interactive=True, - label="presence penalty", - ) - frequency_penalty_slider = gr.Slider( - minimum=-2.0, - maximum=2.0, - value=0.0, - step=0.01, - interactive=True, - label="frequency penalty", - ) - logit_bias_txt = gr.Textbox( - show_label=True, - placeholder=f"word:likelihood", - label="logit bias", - value="", - lines=1, - ) - user_identifier_txt = gr.Textbox( - show_label=True, - placeholder=i18n("用于定位滥用行为"), - label=i18n("用户名"), - value=user_name.value, - lines=1, - ) - - with gr.Accordion(i18n("网络设置"), open=False): - # 优先展示自定义的api_host - apihostTxt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入API-Host..."), - label="API-Host", - value=config.api_host or shared.API_HOST, - lines=1, - ) - changeAPIURLBtn = gr.Button(i18n("🔄 切换API地址")) - proxyTxt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入代理地址..."), - label=i18n("代理地址(示例:http://127.0.0.1:10809)"), - value="", - lines=2, - ) - changeProxyBtn = gr.Button(i18n("🔄 设置代理地址")) - default_btn = gr.Button(i18n("🔙 恢复默认设置")) - - gr.Markdown(CHUANHU_DESCRIPTION, elem_id="description") - gr.HTML(FOOTER.format(versions=versions_html()), elem_id="footer") - demo.load(refresh_ui_elements_on_load, [current_model, model_select_dropdown], [like_dislike_area], show_progress=False) - chatgpt_predict_args = dict( - fn=predict, - inputs=[ - current_model, - user_question, - chatbot, - use_streaming_checkbox, - use_websearch_checkbox, - index_files, - language_select_dropdown, - ], - outputs=[chatbot, status_display], - show_progress=True, - ) - - start_outputing_args = dict( - fn=start_outputing, - inputs=[], - outputs=[submitBtn, cancelBtn], - show_progress=True, - ) - - end_outputing_args = dict( - fn=end_outputing, inputs=[], outputs=[submitBtn, cancelBtn] - ) - - reset_textbox_args = dict( - fn=reset_textbox, inputs=[], outputs=[user_input] - ) - - transfer_input_args = dict( - fn=transfer_input, inputs=[user_input], outputs=[user_question, user_input, submitBtn, cancelBtn], show_progress=True - ) - - get_usage_args = dict( - fn=billing_info, inputs=[current_model], outputs=[usageTxt], show_progress=False - ) - - load_history_from_file_args = dict( - fn=load_chat_history, - inputs=[current_model, historyFileSelectDropdown, chatbot, user_name], - outputs=[saveFileName, systemPromptTxt, chatbot] - ) - - - # Chatbot - cancelBtn.click(interrupt, [current_model], []) - - user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args) - user_input.submit(**get_usage_args) - - submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args) - submitBtn.click(**get_usage_args) - - index_files.change(handle_file_upload, [current_model, index_files, chatbot], [index_files, chatbot, status_display]) - - emptyBtn.click( - reset, - inputs=[current_model], - outputs=[chatbot, status_display], - show_progress=True, - ) - - retryBtn.click(**start_outputing_args).then( - retry, - [ - current_model, - chatbot, - use_streaming_checkbox, - use_websearch_checkbox, - index_files, - language_select_dropdown, - ], - [chatbot, status_display], - show_progress=True, - ).then(**end_outputing_args) - retryBtn.click(**get_usage_args) - - delFirstBtn.click( - delete_first_conversation, - [current_model], - [status_display], - ) - - delLastBtn.click( - delete_last_conversation, - [current_model, chatbot], - [chatbot, status_display], - show_progress=False - ) - - likeBtn.click( - like, - [current_model], - [status_display], - show_progress=False - ) - - dislikeBtn.click( - dislike, - [current_model], - [status_display], - show_progress=False - ) - - two_column.change(update_doc_config, [two_column], None) - - # LLM Models - keyTxt.change(set_key, [current_model, keyTxt], [user_api_key, status_display]).then(**get_usage_args) - keyTxt.submit(**get_usage_args) - single_turn_checkbox.change(set_single_turn, [current_model, single_turn_checkbox], None) - model_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt], [current_model, status_display, lora_select_dropdown], show_progress=True) - model_select_dropdown.change(toggle_like_btn_visibility, [model_select_dropdown], [like_dislike_area], show_progress=False) - lora_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt], [current_model, status_display], show_progress=True) - - # Template - systemPromptTxt.change(set_system_prompt, [current_model, systemPromptTxt], None) - templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown]) - templateFileSelectDropdown.change( - load_template, - [templateFileSelectDropdown], - [promptTemplates, templateSelectDropdown], - show_progress=True, - ) - templateSelectDropdown.change( - get_template_content, - [promptTemplates, templateSelectDropdown, systemPromptTxt], - [systemPromptTxt], - show_progress=True, - ) - - # S&L - saveHistoryBtn.click( - save_chat_history, - [current_model, saveFileName, chatbot, user_name], - downloadFile, - show_progress=True, - ) - saveHistoryBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown]) - exportMarkdownBtn.click( - export_markdown, - [current_model, saveFileName, chatbot, user_name], - downloadFile, - show_progress=True, - ) - historyRefreshBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown]) - historyFileSelectDropdown.change(**load_history_from_file_args) - downloadFile.change(**load_history_from_file_args) - - # Advanced - max_context_length_slider.change(set_token_upper_limit, [current_model, max_context_length_slider], None) - temperature_slider.change(set_temperature, [current_model, temperature_slider], None) - top_p_slider.change(set_top_p, [current_model, top_p_slider], None) - n_choices_slider.change(set_n_choices, [current_model, n_choices_slider], None) - stop_sequence_txt.change(set_stop_sequence, [current_model, stop_sequence_txt], None) - max_generation_slider.change(set_max_tokens, [current_model, max_generation_slider], None) - presence_penalty_slider.change(set_presence_penalty, [current_model, presence_penalty_slider], None) - frequency_penalty_slider.change(set_frequency_penalty, [current_model, frequency_penalty_slider], None) - logit_bias_txt.change(set_logit_bias, [current_model, logit_bias_txt], None) - user_identifier_txt.change(set_user_identifier, [current_model, user_identifier_txt], None) - - default_btn.click( - reset_default, [], [apihostTxt, proxyTxt, status_display], show_progress=True - ) - changeAPIURLBtn.click( - change_api_host, - [apihostTxt], - [status_display], - show_progress=True, - ) - changeProxyBtn.click( - change_proxy, - [proxyTxt], - [status_display], - show_progress=True, - ) - -logging.info( - colorama.Back.GREEN - + "\n川虎的温馨提示:访问 http://localhost:7860 查看界面" - + colorama.Style.RESET_ALL -) -# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接 -demo.title = i18n("川虎Chat 🚀") - -if __name__ == "__main__": - reload_javascript() - demo.queue(concurrency_count=CONCURRENT_COUNT).launch( - favicon_path="./assets/favicon.ico", - ) - # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口 - # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码 - # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(auth=("在这里填写用户名", "在这里填写密码")) # 适合Nginx反向代理