diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Anne (dvd 12) S01 Ep 123 124 Fix.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Anne (dvd 12) S01 Ep 123 124 Fix.md deleted file mode 100644 index 100e9c52af5aad062024fc7175c1d436e320eb00..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Anne (dvd 12) S01 Ep 123 124 Fix.md +++ /dev/null @@ -1,19 +0,0 @@ - -

Anne with an E: A Review of Season 1 Episodes 123 and 124

-

Anne with an E is a Canadian television series based on the classic novel Anne of Green Gables by Lucy Maud Montgomery. The series follows the adventures of Anne Shirley, a spirited and imaginative orphan girl who finds a new home with an elderly brother and sister on Prince Edward Island.

-

anne (dvd 12) s01 ep 123 124


Download ★★★ https://byltly.com/2uKwN5



-

In this article, I will review the last two episodes of season 1, which are available on DVD 12. These episodes are titled "Remorse Is the Poison of Life" and "Wherever You Are Is My Home".

-

Remorse Is the Poison of Life

-

This episode deals with the aftermath of a tragic accident that leaves one of Anne's friends in a coma. Anne blames herself for what happened and struggles with guilt and remorse. She also faces the wrath of the town's gossip, Mrs. Lynde, who accuses her of being a bad influence.

-

Meanwhile, Marilla and Matthew face a financial crisis that threatens to take away their farm. They try to find a way to save Green Gables, but their options are limited. Marilla also receives a visit from an old flame, who stirs up some memories of her past.

-

This episode is emotional and dramatic, as it shows how Anne and the Cuthberts cope with adversity and loss. It also reveals some secrets about Marilla's history and her feelings for Matthew. The performances of Amybeth McNulty as Anne, Geraldine James as Marilla, and R.H. Thomson as Matthew are superb and moving.

-

-

Wherever You Are Is My Home

-

This episode is the season finale, and it wraps up some of the main conflicts and challenges that Anne and the Cuthberts faced throughout the season. Anne finally gets to attend the Christmas ball at the Barrys' house, where she hopes to impress Gilbert Blythe, her academic rival and crush. However, things do not go as planned, and Anne has to deal with some unexpected surprises.

-

On the other hand, Marilla and Matthew manage to find a solution to their financial troubles, thanks to a generous offer from an unexpected source. They also decide to make Anne's stay at Green Gables permanent, by officially adopting her as their daughter.

-

This episode is heartwarming and satisfying, as it shows how Anne's dreams come true and how she finds a true family with the Cuthberts. It also sets up some new possibilities for season 2, such as Anne's friendship with Gilbert, her education at Queen's College, and her exploration of her identity and heritage.

-

Conclusion

-

Anne with an E is a wonderful adaptation of a beloved classic, that brings new life and depth to the characters and the story. The series is beautifully shot, well-written, and superbly acted. It tackles some serious issues such as orphanhood, trauma, prejudice, and identity, while also celebrating the joys of imagination, friendship, and love.

-

The last two episodes of season 1 are a testament to the quality and charm of this series. They are emotional, engaging, and uplifting. They leave the viewers wanting more of Anne's adventures and growth.

cec2833e83
-
-
\ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download The Sims 2 for PC and Create Your Own Virtual World.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download The Sims 2 for PC and Create Your Own Virtual World.md deleted file mode 100644 index c75d1c8afb4eca64c5de28de474280fb31a5b2ca..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download The Sims 2 for PC and Create Your Own Virtual World.md +++ /dev/null @@ -1,17 +0,0 @@ - -

The Sims 2 Download for PC

-

The Sims 2 is a popular life simulation game that was released in 2004 by Electronic Arts. It is the sequel to The Sims, and it allows players to create and control their own virtual characters, called Sims, in various activities and scenarios. The game has multiple expansion and stuff packs that add new features, content, and gameplay options to the base game.

-

If you want to download The Sims 2 for PC, you have a few options. One of them is to get the original game from Old Games Download, which provides a link to download a zip file containing the game ISO and a serial key. You will need to extract the file, mount the ISO, run the setup.exe, and copy the Sims2.exe file from the NoCD folder to the game folder. You will also need to install DirectX from the Redist folder and run the game as administrator.

-

the sims 2 download for pc


Download File »»» https://byltly.com/2uKwhh



-

Another option is to get The Sims 2: Ultimate Collection from Old Games Download, which includes the original game along with all expansion and stuff packs. This is a repack of the game that comes in a rar file that you need to extract and run the Setup.exe. You will also need to install DirectX from the Redist folder and run the game as administrator. The first time you open the game, it may take some time to start and you may see a black screen for a while. You will also need to change the shadows settings from high to low or medium to avoid black squares under your Sims.

-

A third option is to get The Sims 2: Ultimate Collection from Origin, which is an online platform that sells and distributes digital games. You will need to create an account on Origin and download their client software. Then you can locate The Sims 2 Ultimate Collection in your Origin Game Library and click on download. You will then be presented with a series of pop-up boxes that will guide you through the installation process.

-

Whichever option you choose, you will be able to enjoy The Sims 2 on your PC and create your own virtual world with endless possibilities.

The Sims 2 Tips and Tricks

-

Once you have downloaded The Sims 2 for PC, you may want to learn some tips and tricks to make your gameplay more enjoyable and efficient. Here are some of them:

- -

These are just some of the tips and tricks that you can use in The Sims 2. There are many more that you can discover by exploring the game and trying different things. Have fun!

ddb901b051
-
-
\ No newline at end of file diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/Avengers-Age-Of-Ultron-Full-Movie-Hd-Download-Free-EXCLUSIVE.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/Avengers-Age-Of-Ultron-Full-Movie-Hd-Download-Free-EXCLUSIVE.md deleted file mode 100644 index d831eac862dd42a8677502ab56b20832790b0360..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/Avengers-Age-Of-Ultron-Full-Movie-Hd-Download-Free-EXCLUSIVE.md +++ /dev/null @@ -1,94 +0,0 @@ -## Avengers: Age Of Ultron Full Movie Hd Download Free - - - - - - ![Avengers: Age Of Ultron Full Movie Hd Download Free ((EXCLUSIVE))](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTBHIeSh9UhrWrkROv7I1Kjyj_vkDXfdCbviu8eCZAGzhNgrZgqtFCNTCPM) - - - - - -**Download ○ [https://kneedacexbrew.blogspot.com/?d=2txjhR](https://kneedacexbrew.blogspot.com/?d=2txjhR)** - - - - - - - - - - - - - -# How to Watch Avengers: Age Of Ultron Full Movie HD for Free Online - - - -If you are a fan of Marvel's superhero movies, you might be wondering how to watch Avengers: Age Of Ultron full movie HD for free online. Avengers: Age Of Ultron is the sequel to the 2012 blockbuster The Avengers, and it features the return of Iron Man, Captain America, Thor, Hulk, Black Widow, Hawkeye, and Nick Fury as they face a new threat from a rogue artificial intelligence named Ultron. - - - -Avengers: Age Of Ultron was released in 2015 and it was a huge success at the box office, grossing over $1.4 billion worldwide. It received positive reviews from critics and audiences alike, who praised its action, humor, visual effects, and performances. The movie also introduced new characters such as Scarlet Witch, Quicksilver, Vision, and Ant-Man to the Marvel Cinematic Universe. - - - -However, if you missed the chance to watch Avengers: Age Of Ultron in theaters or on streaming platforms, you might be looking for ways to watch it for free online. There are many websites that claim to offer Avengers: Age Of Ultron full movie HD download free, but most of them are either illegal, unsafe, or low-quality. In this article, we will show you how to watch Avengers: Age Of Ultron full movie HD for free online legally and safely. - - - -## The Best Way to Watch Avengers: Age Of Ultron Full Movie HD for Free Online - - - -The best way to watch Avengers: Age Of Ultron full movie HD for free online is to use a reputable and reliable website that offers legal and high-quality streaming services. One of such websites is M4uHD[^1^], which is a popular and trusted site that provides thousands of movies and TV shows for free. - - - -M4uHD has Avengers: Age Of Ultron full movie HD available for streaming on its website. You can watch it without any registration or subscription. All you need is a stable internet connection and a compatible device such as a computer, smartphone, tablet, or smart TV. You can also choose from different video qualities ranging from 360p to 1080p. - - - -M4uHD is not only free but also safe and secure. It does not host any illegal or pirated content on its servers. It only links to third-party sources that host the movies and TV shows. It also does not contain any malware or viruses that can harm your device or data. It respects your privacy and does not collect any personal information from you. - - - -To watch Avengers: Age Of Ultron full movie HD for free online on M4uHD, follow these simple steps: - - - -1. Go to M4uHD's website by clicking [here](https://m4uhd.tv/watch-movie-avengers-age-of-ultron-2015-4932.html). - -2. Search for Avengers: Age Of Ultron in the search bar or browse through the categories. - -3. Click on the movie poster or title to open the movie page. - -4. Choose a video quality and a server from the list of options. - -5. Click on the play button and enjoy watching Avengers: Age Of Ultron full movie HD for free online. - - - -## Other Ways to Watch Avengers: Age Of Ultron Full Movie HD for Free Online - - - -If you are looking for other ways to watch Avengers: Age Of Ultron full movie HD for free online, you can also try some of these alternatives: - - - -- MoviesFlix[^2^]: MoviesFlix is another website that offers free streaming of movies and TV shows in various genres and languages. It has Avengers: Age Of Ultron full movie HD download free option as well as streaming option. You can download the movie in different formats such as 300MB, 480p, 720p, and 1080p. You can also watch it online without any registration or subscription. - -- Google Drive[^3^]: Google Drive is a cloud storage service that allows you to store and share files online. You can also use it to watch movies and TV shows that are uploaded 1b8d091108 - - - - - - - - - diff --git a/spaces/1phancelerku/anime-remove-background/Descarga Clash Royale Hack APK con todas las cartas desbloqueadas y gemas ilimitadas.md b/spaces/1phancelerku/anime-remove-background/Descarga Clash Royale Hack APK con todas las cartas desbloqueadas y gemas ilimitadas.md deleted file mode 100644 index 4c6461e0a447cdcee0df2a8ce9b112da1b9e6f8f..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Descarga Clash Royale Hack APK con todas las cartas desbloqueadas y gemas ilimitadas.md +++ /dev/null @@ -1,69 +0,0 @@ - -

Clash Royale Hack APK Todas Las Cartas: What You Need to Know

-

Clash Royale is a popular mobile game that combines elements of strategy, card collecting, and tower defense. It is developed by Supercell, the same company behind Clash of Clans. In Clash Royale, you can collect and upgrade over 100 cards featuring characters from the Clash universe, as well as spells and defenses. You can also build your own battle deck and challenge other players in real-time multiplayer matches.

-

clash royale hack apk todas las cartas


DOWNLOAD ★★★ https://jinyurl.com/2uNNhq



-

However, some players are not satisfied with playing Clash Royale the way it is intended. They want to get access to all the cards in the game without spending any money or time. That's why they look for hack APKs for Clash Royale.

-

A hack APK is a modified version of an app that allows users to cheat or bypass certain restrictions in the game. For example, a hack APK for Clash Royale may let you get unlimited gems, gold, and cards for free. It may also let you unlock all arenas and chests instantly. In Spanish, "todas las cartas" means "all cards", so a hack APK that claims to offer "todas las cartas" is one that gives you access to every card in the game.

-

But before you download and install a hack APK for Clash Royale, you should know that there are many risks and drawbacks involved. In this article, we will explain why using hack APKs for Clash Royale is not a good idea, and how you can play Clash Royale without using them.

-

-

Why Do People Use Hack APKs for Clash Royale?

-

There are several reasons why some players use hack APKs for Clash Royale. Here are some of them:

- -

These are some of the reasons why some players use hack APKs for Clash Royale. However, they may not realize that using hack APKs for Clash Royale is not only illegal, but also risky and unethical.

-

How Do Hack APKs Work for Clash Royale?

-

Hack APKs for Clash Royale work by modifying the original game files, bypassing the security checks, and injecting fake data into the game servers. Here is how they do it:

- -

What Are the Risks and Drawbacks of Using Hack APKs for Clash Royale?

-

Using hack APKs for Clash Royale may seem tempting, but it comes with many risks and drawbacks. Here are some of them:

-

Legal Issues

-

Using hack APKs for Clash Royale is illegal and can get you in trouble with the law. By using hack APKs, you are violating the terms of service of Clash Royale, which state that you are not allowed to modify, hack, or cheat in the game. You are also infringing the intellectual property rights of Supercell, which own the exclusive rights to the game and its content. If you are caught using hack APKs, you may face legal actions from Supercell, such as lawsuits, fines, or bans.

-

Technical Issues

-

Using hack APKs for Clash Royale is risky and can damage your device and data. Hack APKs are not verified or approved by Supercell or Google Play, and may contain malware, viruses, or spyware that can harm your device or steal your personal information. Hack APKs may also cause data loss, device damage, or compatibility issues, as they may not be compatible with the latest updates or versions of the game. If you use hack APKs, you may lose your progress, account, or device.

-

Ethical Issues

-

Using hack APKs for Clash Royale is unethical and can ruin the game experience for yourself and others. Hack APKs are a form of cheating that gives you an unfair advantage over other players who play by the rules. By using hack APKs, you are ruining the game balance, the game challenge, and the game fun. You are also disrespecting other players who work hard to earn their rewards and achievements legitimately. If you use hack APKs, you may lose your reputation, respect, or friends.

-

How to Play Clash Royale Without Using Hack APKs?

-

Now that you know the risks and drawbacks of using hack APKs for Clash Royale, you may wonder how to play Clash Royale without using them. The answer is simple: just play the game as it is meant to be played. Here are some tips and benefits of playing Clash Royale without using hack APKs:

-

Tips and Tricks for Beginners

-

If you are new to Clash Royale, you may feel overwhelmed by the game's complexity and difficulty. However, there are some tips and tricks that can help you improve your skills and strategies in Clash Royale. Here are some of them:

- -

Features and Benefits of Playing Legally

-

If you play Clash Royale without using hack APKs, you will enjoy many features and benefits that hack APKs cannot offer. Here are some of them:

- -

Conclusion

-

In conclusion, using hack APKs for Clash Royale is not a good idea, as it can cause many legal, technical, and ethical issues. Hack APKs for Clash Royale are illegal, risky, and unethical. They can get you in trouble with the law, damage your device and data, and ruin the game experience for yourself and others.

-

Instead of using hack APKs for Clash Royale, you should play the game without using them. Playing Clash Royale without using hack APKs is simple, safe, and fun. You can improve your skills and strategies in Clash Royale by following some tips and tricks for beginners. You can also enjoy many features and benefits of playing legally, such as enjoying the game's original design, earning rewards fairly, supporting the developers, and being part of a respectful community.

-

So what are you waiting for? Download Clash Royale from Google Play or App Store today and start playing without using hack APKs. You will have a blast!

-

FAQs

-

Here are some frequently asked questions about Clash Royale and hack APKs:

-

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Amp Install Google Drive For Desktop HOT!.md b/spaces/1phancelerku/anime-remove-background/Download Amp Install Google Drive For Desktop HOT!.md deleted file mode 100644 index 04e3c38dd52a32ac2a5fa01f1cc82c02079db80b..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Amp Install Google Drive For Desktop HOT!.md +++ /dev/null @@ -1,84 +0,0 @@ - -

How to Download and Install Google Drive for Desktop

-

Google Drive is a popular online storage service that lets you store and access your files from any device. But did you know that you can also use Google Drive on your desktop computer? With Google Drive for desktop, you can sync your files between the cloud and your computer, open files directly from your computer, back up your photos, collaborate on Microsoft Office files, and more. In this article, we will show you how to download and install Google Drive for desktop, how to use its features, and some tips and tricks to make the most of it.

-

download amp; install google drive for desktop


DOWNLOAD >>> https://jinyurl.com/2uNSTF



-

What is Google Drive for Desktop and Why You Need It

-

Google Drive for desktop is an app that lets you access your Google Drive files and folders on your computer with Windows File Explorer or macOS Finder. It also lets you sync folders from your computer to Google Drive or backup to Google Photos. When you sync, your files download from the cloud and upload from your computer’s hard drive. After you sync, your computer's files match those in the cloud. Your files stay up to date and accessible, any change you make applies across devices.

-

Some of the benefits of using Google Drive for desktop are:

- -

How to Download Google Drive for Desktop

-

To download Google Drive for desktop, follow these steps:

-
    -
  1. Go to https://www.google.com/drive/download/ and click Download under Drive for desktop.
  2. -
  3. Select DOWNLOAD FOR WINDOWS or DOWNLOAD FOR MAC, depending on your operating system.
  4. -
  5. A file named GoogleDriveSetup.exe (for Windows) or GoogleDrive.dmg (for Mac) will be downloaded to your computer. Open it and follow the on-screen instructions.
  6. -
-

How to Install Google Drive for Desktop

-

To install Google Drive for desktop, follow these steps:

-
    -
  1. After you open the downloaded file, a window will appear asking you to sign in with your Google account. Enter your email address and password, then click Next.
  2. -
  3. A window will appear asking you to choose how you want to use Google Drive for desktop. You can choose between Stream files to free up space or Sync files to your computer. The first option lets you stream files from the cloud without downloading them, while the second option lets you sync files between your computer and the cloud. Choose the option that suits your needs and click Next.
  4. -
  5. A window will appear asking you to choose which folders you want to sync or stream. You can select all folders or specific folders from My Drive and Shared drives. You can also change the location of the Google Drive folder on your computer. Click Start when you are done.
  6. -
  7. A window will appear showing the progress of the installation. Wait until it is complete, then click Close.
  8. -
  9. A Google Drive icon will appear on your taskbar (for Windows) or menu bar (for Mac). Click it to open Google Drive for desktop and access your files.
  10. -
-

How to Use Google Drive for Desktop

-

Google Drive for desktop has many features and functions that you can use to manage your files and folders. Here are some of the main ones:

-

- -

Tips and Tricks for Google Drive for Desktop

-

Here are some tips and tricks to help you make the most of Google Drive for desktop:

- -

Conclusion

-

In this article, we have shown you how to download and install Google Drive for desktop, how to use its features, and some tips and tricks to make the most of it. Google Drive for desktop is a powerful app that lets you access your Google Drive files and folders on your computer with ease. It also lets you sync folders from your computer to Google Drive or backup to Google Photos. You can also open files directly from your computer, save files for offline use, collaborate on Microsoft Office files, and extend the power of Drive with third-party apps. If you haven't tried it yet, we recommend you download it today and see how it can improve your productivity and workflow.

-

FAQs

What are the system requirements for Google Drive for desktop?

-

To use Google Drive for desktop, you need to have a computer that meets the following system requirements:

- - - - - - - - - - - - - -
Operating systemMinimum requirements
WindowsWindows 7 and up. .NET Framework 4.5.2 or higher.
MacEl Capitan (10.11) and up.
-

How much storage space does Google Drive for desktop use?

-

The amount of storage space that Google Drive for desktop uses depends on the option you choose for syncing or streaming files. If you choose to stream files, Google Drive for desktop will use a small amount of disk space to cache some of your files for faster access. You can change the cache size by going to Preferences > Syncing > Cache size. If you choose to sync files, Google Drive for desktop will use the same amount of disk space as the files you sync. You can change the folders you sync by going to Preferences > Syncing > Choose folders.

-

How can I access my Google Drive files offline?

-

To access your Google Drive files offline, you need to save them for offline use. To do this, right-click a file or folder in the Google Drive folder and select Available offline. A checkmark will appear next to it. You can also see which files are available offline by going to Preferences > Offline Files. When you are offline, you can open and edit your offline files as usual. When you are online again, your changes will sync to the cloud.

-

How can I collaborate on Microsoft Office files with Google Drive for desktop?

-

To collaborate on Microsoft Office files with Google Drive for desktop, you need to use Google Workspace plugins for Microsoft Office. To do this, go to https://workspace.google.com/marketplace/app/drive_for_office/1016028792930 and download the plugin for your version of Office. After installing it, you can open Office files from Google Drive on your computer and edit them in real time with other users. You can also see their comments and suggestions, and save your changes to the cloud.

-

How can I troubleshoot errors in Google Drive for desktop?

-

If you encounter any errors or issues in Google Drive for desktop, you can try the following steps to fix them:

-

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Spider Fighter Mod APK and Become the Ultimate Hero.md b/spaces/1phancelerku/anime-remove-background/Download Spider Fighter Mod APK and Become the Ultimate Hero.md deleted file mode 100644 index bd67221b41380fec6178d1d16df23e0ed8e428af..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Spider Fighter Mod APK and Become the Ultimate Hero.md +++ /dev/null @@ -1,70 +0,0 @@ -
-

Download Game Spider Fighter Mod Apk: A Guide for Superhero Fans

-

Do you love superhero games? Do you want to become a spider hero and fight against the evil forces in the city? If yes, then you should download game spider fighter mod apk, a thrilling action game that will make you feel like a real superhero. In this game, you can craft superskills and spider's powers, fight crime bosses and corrupted forces, and explore the grand city and its secrets. In this article, we will tell you everything you need to know about spider fighter mod apk, including its features, how to download and install it, and why you should download it. So, let's get started!

-

download game spider fighter mod apk


Download File » https://jinyurl.com/2uNPVv



-

What is Spider Fighter Mod Apk?

-

Spider Fighter Mod Apk is a modified version of the original game Spider Fighter, developed by Superhero Academy. It is an action game that lets you play as a spider hero who has to save the city from the mafia and other enemies. You can use your spider's powers, such as web-shooting, wall-crawling, and swinging, to move around the city and fight your foes. You can also craft superskills, such as fireballs, lightning bolts, and ice blasts, to enhance your abilities and defeat your enemies faster. The game has a captivating storyline, realistic physics, and stunning graphics that will keep you hooked for hours.

-

Features of Spider Fighter Mod Apk

-

Craft superskills and spider's powers

-

One of the most exciting features of spider fighter mod apk is that you can craft superskills and spider's powers to complement your man body and become more powerful. You can choose from different types of skills, such as fire, ice, lightning, earth, wind, and water, and combine them with your spider's powers to create unique effects. For example, you can shoot fireballs from your web-shooter, or freeze your enemies with your ice blast. You can also upgrade your skills and powers as you progress in the game and unlock new ones.

-

Fight crime bosses and corrupted forces

-

The city is in danger as crime bosses have occupied it and corrupted the police and army forces. You have to fight them and restore peace in the city. You will face different types of enemies, such as thugs, gangsters, snipers, robots, helicopters, tanks, and more. You have to use your skills and powers wisely to defeat them and avoid their attacks. You can also use the environment to your advantage, such as cars, buildings, bridges, and more. You will also encounter boss battles that will challenge your skills and strategy.

-

How to download game spider fighter mod apk for free
-Download game spider fighter 3 mod apk latest version
-Spider fighter game review: a thrilling superhero adventure
-Best tips and tricks for playing spider fighter game on android
-Spider fighter game features: what makes it stand out from other spider games
-Download game spider fighter mod apk unlimited money and gems
-Spider fighter game walkthrough: how to complete all missions and challenges
-Download game spider fighter mod apk offline mode
-Spider fighter game cheats: how to unlock all spider suits and gadgets
-Spider fighter game vs spider man game: which one is better
-Download game spider fighter mod apk for PC using emulator
-Spider fighter game system requirements: can your device run it smoothly
-Download game spider fighter mod apk no root needed
-Spider fighter game update: what's new in the latest version
-Spider fighter game fan art: how to create your own spider hero
-Download game spider fighter mod apk with obb data file
-Spider fighter game soundtrack: how to download and enjoy the music
-Spider fighter game online: how to play with other players around the world
-Download game spider fighter mod apk with all levels unlocked
-Spider fighter game bugs and glitches: how to fix them easily
-Download game spider fighter mod apk from APKCombo[^1^] [^2^]
-Spider fighter game ratings and reviews: what do other players think about it
-Download game spider fighter mod apk without ads and pop-ups
-Spider fighter game lore and backstory: how did the spider hero become who he is
-Spider fighter game achievements and trophies: how to earn them all

-

Explore the grand city and its secrets

-

The game has a large open-world map that allows you to explore the grand city and its secrets. You can roam around freely and discover different places, such as parks, streets, alleys, rooftops, tunnels, warehouses, and more. You can also interact with various objects and people in the city. You can find hidden items, such as coins, gems, health packs, weapons, and more. You can also complete missions and quests that will reward you with money and experience points. You can use the money to buy new costumes, gadgets, vehicles, and more.

-

How to download and install Spider Fighter Mod Apk?

-

Step 1: Download the mod apk file from a trusted source

-

The first step to download game spider fighter mod apk is to find a reliable source that offers the mod apk file for free and without any viruses or malware. You can use the link below to download the mod apk file from our website. The file size is about 100 MB and it is compatible with Android 4.4 and above.

-

Step 2: Enable unknown sources on your device

-

The next step is to enable unknown sources on your device so that you can install the mod apk file. To do this, go to your device settings and look for the security or privacy option. Then, find the unknown sources option and toggle it on. This will allow you to install apps from sources other than the Google Play Store.

-

Step 3: Install the mod apk file and enjoy the game

-

The final step is to install the mod apk file and enjoy the game. To do this, locate the downloaded mod apk file on your device and tap on it. Then, follow the instructions on the screen to complete the installation process. Once done, you can launch the game and start playing as a spider hero.

-

Why should you download Spider Fighter Mod Apk?

-

Unlimited money and gems

-

One of the main reasons why you should download spider fighter mod apk is that it gives you unlimited money and gems in the game. Money and gems are the main currencies in the game that you can use to buy new costumes, gadgets, vehicles, and more. You can also use them to upgrade your skills and powers and unlock new ones. With unlimited money and gems, you can enjoy the game without any limitations or restrictions.

-

No ads and no root required

-

Another reason why you should download spider fighter mod apk is that it removes all the ads and does not require root access on your device. Ads can be annoying and distracting when you are playing the game, especially when they pop up in between the action scenes. They can also consume your data and battery life. With spider fighter mod apk, you can play the game without any ads and interruptions. Moreover, you do not need to root your device to install the mod apk file, which means you do not have to risk damaging your device or voiding its warranty.

-

High-quality graphics and sound effects

-

The last reason why you should download spider fighter mod apk is that it enhances the graphics and sound effects of the game. The game has high-quality graphics that make the city look realistic and immersive. You can see the details of the buildings, cars, bridges, and more. The game also has amazing sound effects that make you feel like you are in a real superhero movie. You can hear the sounds of your web-shooting, swinging, fighting, and more. The game also has a catchy soundtrack that matches the mood of the game.

-

Conclusion

-

Spider Fighter Mod Apk is a must-have game for all superhero fans who want to become a spider hero and save the city from evil forces. The game has many features that make it fun and exciting, such as crafting superskills and spider's powers, fighting crime bosses and corrupted forces, exploring the grand city and its secrets, unlimited money and gems, no ads and no root required, high-quality graphics and sound effects, and more. You can download game spider fighter mod apk from our website for free and without any viruses or malware. Just follow the steps we have provided above and enjoy the game.

-

FAQs

-

Here are some frequently asked questions about spider fighter mod apk:

-

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/2kaara/oreo/README.md b/spaces/2kaara/oreo/README.md deleted file mode 100644 index 916cfc8a411ec91ae4040da061a7fb79e164fd29..0000000000000000000000000000000000000000 --- a/spaces/2kaara/oreo/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Oreo -emoji: 🏆 -colorFrom: pink -colorTo: purple -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/34we12er/newbing/README.md b/spaces/34we12er/newbing/README.md deleted file mode 100644 index 7a7c191d1b727e6206b2f008125b792cad9b98be..0000000000000000000000000000000000000000 --- a/spaces/34we12er/newbing/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Newbing -emoji: 🐨 -colorFrom: green -colorTo: pink -sdk: docker -pinned: false -license: mit -app_port: 8080 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/AI-ZTH-03-23/3.HTML5-Aframe-3dMap-Flight/index.html b/spaces/AI-ZTH-03-23/3.HTML5-Aframe-3dMap-Flight/index.html deleted file mode 100644 index 7e01f307db53fb82e81f33fc94c898d5e909e1e6..0000000000000000000000000000000000000000 --- a/spaces/AI-ZTH-03-23/3.HTML5-Aframe-3dMap-Flight/index.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Recursive Polygons in 3D - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spaces/AIFILMS/generate_human_motion/VQ-Trans/visualize/vis_utils.py b/spaces/AIFILMS/generate_human_motion/VQ-Trans/visualize/vis_utils.py deleted file mode 100644 index 05728b38e3d6be4bfd83324907e3fa7a3f358071..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/generate_human_motion/VQ-Trans/visualize/vis_utils.py +++ /dev/null @@ -1,66 +0,0 @@ -from model.rotation2xyz import Rotation2xyz -import numpy as np -from trimesh import Trimesh -import os -import torch -from visualize.simplify_loc2rot import joints2smpl - -class npy2obj: - def __init__(self, npy_path, sample_idx, rep_idx, device=0, cuda=True): - self.npy_path = npy_path - self.motions = np.load(self.npy_path, allow_pickle=True) - if self.npy_path.endswith('.npz'): - self.motions = self.motions['arr_0'] - self.motions = self.motions[None][0] - self.rot2xyz = Rotation2xyz(device='cpu') - self.faces = self.rot2xyz.smpl_model.faces - self.bs, self.njoints, self.nfeats, self.nframes = self.motions['motion'].shape - self.opt_cache = {} - self.sample_idx = sample_idx - self.total_num_samples = self.motions['num_samples'] - self.rep_idx = rep_idx - self.absl_idx = self.rep_idx*self.total_num_samples + self.sample_idx - self.num_frames = self.motions['motion'][self.absl_idx].shape[-1] - self.j2s = joints2smpl(num_frames=self.num_frames, device_id=device, cuda=cuda) - - if self.nfeats == 3: - print(f'Running SMPLify For sample [{sample_idx}], repetition [{rep_idx}], it may take a few minutes.') - motion_tensor, opt_dict = self.j2s.joint2smpl(self.motions['motion'][self.absl_idx].transpose(2, 0, 1)) # [nframes, njoints, 3] - self.motions['motion'] = motion_tensor.cpu().numpy() - elif self.nfeats == 6: - self.motions['motion'] = self.motions['motion'][[self.absl_idx]] - self.bs, self.njoints, self.nfeats, self.nframes = self.motions['motion'].shape - self.real_num_frames = self.motions['lengths'][self.absl_idx] - - self.vertices = self.rot2xyz(torch.tensor(self.motions['motion']), mask=None, - pose_rep='rot6d', translation=True, glob=True, - jointstype='vertices', - # jointstype='smpl', # for joint locations - vertstrans=True) - self.root_loc = self.motions['motion'][:, -1, :3, :].reshape(1, 1, 3, -1) - self.vertices += self.root_loc - - def get_vertices(self, sample_i, frame_i): - return self.vertices[sample_i, :, :, frame_i].squeeze().tolist() - - def get_trimesh(self, sample_i, frame_i): - return Trimesh(vertices=self.get_vertices(sample_i, frame_i), - faces=self.faces) - - def save_obj(self, save_path, frame_i): - mesh = self.get_trimesh(0, frame_i) - with open(save_path, 'w') as fw: - mesh.export(fw, 'obj') - return save_path - - def save_npy(self, save_path): - data_dict = { - 'motion': self.motions['motion'][0, :, :, :self.real_num_frames], - 'thetas': self.motions['motion'][0, :-1, :, :self.real_num_frames], - 'root_translation': self.motions['motion'][0, -1, :3, :self.real_num_frames], - 'faces': self.faces, - 'vertices': self.vertices[0, :, :, :self.real_num_frames], - 'text': self.motions['text'][0], - 'length': self.real_num_frames, - } - np.save(save_path, data_dict) diff --git a/spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/tts/syntaspeech/syntactic_graph_encoder.py b/spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/tts/syntaspeech/syntactic_graph_encoder.py deleted file mode 100644 index e345f0f36113977d601b0b3100e54c59897a712a..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/tts/syntaspeech/syntactic_graph_encoder.py +++ /dev/null @@ -1,193 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -import dgl -from dgl.nn.pytorch import GatedGraphConv - -def sequence_mask(lengths, maxlen, dtype=torch.bool): - if maxlen is None: - maxlen = lengths.max() - mask = ~(torch.ones((len(lengths), maxlen)).to(lengths.device).cumsum(dim=1).t() > lengths).t() - mask.type(dtype) - return mask - - -def group_hidden_by_segs(h, seg_ids, max_len): - """ - :param h: [B, T, H] - :param seg_ids: [B, T] - :return: h_ph: [B, T_ph, H] - """ - B, T, H = h.shape - h_gby_segs = h.new_zeros([B, max_len + 1, H]).scatter_add_(1, seg_ids[:, :, None].repeat([1, 1, H]), h) - all_ones = h.new_ones(h.shape[:2]) - cnt_gby_segs = h.new_zeros([B, max_len + 1]).scatter_add_(1, seg_ids, all_ones).contiguous() - h_gby_segs = h_gby_segs[:, 1:] - cnt_gby_segs = cnt_gby_segs[:, 1:] - h_gby_segs = h_gby_segs / torch.clamp(cnt_gby_segs[:, :, None], min=1) - # assert h_gby_segs.shape[-1] == 192 - return h_gby_segs - -class GraphAuxEnc(nn.Module): - def __init__(self, in_dim, hid_dim, out_dim, n_iterations=5, n_edge_types=6): - super(GraphAuxEnc, self).__init__() - self.in_dim = in_dim - self.hid_dim = hid_dim - self.out_dim = out_dim - self.skip_connect = True - self.dropout_after_gae = False - - self.ggc_1 = GatedGraphConv(in_feats=in_dim, out_feats=hid_dim - , n_steps=n_iterations, n_etypes=n_edge_types) - self.ggc_2 = GatedGraphConv(in_feats=hid_dim, out_feats=out_dim - , n_steps=n_iterations, n_etypes=n_edge_types) - self.dropout = nn.Dropout(p=0.5) - - @staticmethod - def ph_encoding_to_word_encoding(ph_encoding, ph2word, word_len): - """ - ph_encoding: [batch, t_p, hid] - ph2word: tensor [batch, t_w] - word_len: tensor [batch] - """ - word_encoding_for_graph, batch_word_encoding, has_word_row_idx = GraphAuxEnc._process_ph_to_word_encoding( - ph_encoding, - ph2word, - word_len) - # [batch, t_w, hid] - return batch_word_encoding, word_encoding_for_graph - - def pad_word_encoding_to_phoneme(self, word_encoding, ph2word, t_p): - return self._postprocess_word2ph(word_encoding, ph2word, t_p) - - @staticmethod - def _process_ph_to_word_encoding(ph_encoding, ph2word, word_len=None): - """ - ph_encoding: [batch, t_p, hid] - ph2word: tensor [batch, t_w] - word_len: tensor [batch] - """ - word_len = word_len.reshape([-1,]) - max_len = max(word_len) - num_nodes = sum(word_len) - - batch_word_encoding = group_hidden_by_segs(ph_encoding, ph2word, max_len) - bs, t_p, hid = batch_word_encoding.shape - has_word_mask = sequence_mask(word_len, max_len) # [batch, t_p, 1] - word_encoding = batch_word_encoding.reshape([bs * t_p, hid]) - has_word_row_idx = has_word_mask.reshape([-1]) - word_encoding = word_encoding[has_word_row_idx] - assert word_encoding.shape[0] == num_nodes - return word_encoding, batch_word_encoding, has_word_row_idx - - @staticmethod - def _postprocess_word2ph(word_encoding, ph2word, t_p): - word_encoding = F.pad(word_encoding,[0,0,1,0]) - ph2word_ = ph2word[:, :, None].repeat([1, 1, word_encoding.shape[-1]]) - out = torch.gather(word_encoding, 1, ph2word_) # [B, T, H] - return out - - @staticmethod - def _repeat_one_sequence(x, d, T): - """Repeat each frame according to duration.""" - if d.sum() == 0: - d = d.fill_(1) - hid = x.shape[-1] - expanded_lst = [x_.repeat(int(d_), 1) for x_, d_ in zip(x, d) if d_ != 0] - expanded = torch.cat(expanded_lst, dim=0) - if T > expanded.shape[0]: - expanded = torch.cat([expanded, torch.zeros([T - expanded.shape[0], hid]).to(expanded.device)], dim=0) - return expanded - - def word_forward(self, graph_lst, word_encoding, etypes_lst): - """ - word encoding in, word encoding out. - """ - batched_graph = dgl.batch(graph_lst) - inp = word_encoding - batched_etypes = torch.cat(etypes_lst) # [num_edges_in_batch, 1] - assert batched_graph.num_nodes() == inp.shape[0] - - gcc1_out = self.ggc_1(batched_graph, inp, batched_etypes) - if self.dropout_after_gae: - gcc1_out = self.dropout(gcc1_out) - gcc2_out = self.ggc_2(batched_graph, gcc1_out, batched_etypes) # [num_nodes_in_batch, hin] - if self.dropout_after_gae: - gcc2_out = self.ggc_2(batched_graph, gcc2_out, batched_etypes) - if self.skip_connect: - assert self.in_dim == self.hid_dim and self.hid_dim == self.out_dim - gcc2_out = inp + gcc1_out + gcc2_out - - word_len = torch.tensor([g.num_nodes() for g in graph_lst]).reshape([-1]) - max_len = max(word_len) - has_word_mask = sequence_mask(word_len, max_len) # [batch, t_p, 1] - has_word_row_idx = has_word_mask.reshape([-1]) - bs = len(graph_lst) - t_w = max([g.num_nodes() for g in graph_lst]) - hid = word_encoding.shape[-1] - output = torch.zeros([bs * t_w, hid]).to(gcc2_out.device) - output[has_word_row_idx] = gcc2_out - output = output.reshape([bs, t_w, hid]) - word_level_output = output - return torch.transpose(word_level_output, 1, 2) - - def forward(self, graph_lst, ph_encoding, ph2word, etypes_lst, return_word_encoding=False): - """ - graph_lst: [list of dgl_graph] - ph_encoding: [batch, hid, t_p] - ph2word: [list of list[1,2,2,2,3,3,3]] - etypes_lst: [list of etypes]; etypes: torch.LongTensor - """ - t_p = ph_encoding.shape[-1] - ph_encoding = ph_encoding.transpose(1,2) # [batch, t_p, hid] - word_len = torch.tensor([g.num_nodes() for g in graph_lst]).reshape([-1]) - batched_graph = dgl.batch(graph_lst) - inp, batched_word_encoding, has_word_row_idx = self._process_ph_to_word_encoding(ph_encoding, ph2word, - word_len=word_len) # [num_nodes_in_batch, in_dim] - bs, t_w, hid = batched_word_encoding.shape - batched_etypes = torch.cat(etypes_lst) # [num_edges_in_batch, 1] - gcc1_out = self.ggc_1(batched_graph, inp, batched_etypes) - gcc2_out = self.ggc_2(batched_graph, gcc1_out, batched_etypes) # [num_nodes_in_batch, hin] - # skip connection - gcc2_out = inp + gcc1_out + gcc2_out # [n_nodes, hid] - - output = torch.zeros([bs * t_w, hid]).to(gcc2_out.device) - output[has_word_row_idx] = gcc2_out - output = output.reshape([bs, t_w, hid]) - word_level_output = output - output = self._postprocess_word2ph(word_level_output, ph2word, t_p) # [batch, t_p, hid] - output = torch.transpose(output, 1, 2) - - if return_word_encoding: - return output, torch.transpose(word_level_output, 1, 2) - else: - return output - -if __name__ == '__main__': - # Unit Test for batching graphs - from text_to_speech.modules.tts.syntaspeech.syntactic_graph_buider import Sentence2GraphParser, plot_dgl_sentence_graph - parser = Sentence2GraphParser("en") - - # Unit Test for English Graph Builder - text1 = "To be or not to be , that 's a question ." - text2 = "I love you . You love me . Mixue ice-scream and tea ." - graph1, etypes1 = parser.parse(text1) - graph2, etypes2 = parser.parse(text2) - batched_text = " " + text1 + " " + " " + " " + text2 + " " - batched_nodes = [graph1.num_nodes(), graph2.num_nodes()] - plot_dgl_sentence_graph(dgl.batch([graph1, graph2]), {i: w for i, w in enumerate(batched_text.split(" "))}) - etypes_lst = [etypes1, etypes2] - - # Unit Test for Graph Encoder forward - in_feats = 4 - out_feats = 4 - enc = GraphAuxEnc(in_dim=in_feats, hid_dim=in_feats, out_dim=out_feats) - ph2word = torch.tensor([ - [1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], - [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] - ]) - inp = torch.randn([2, in_feats, 17]) # [N_sentence, feat, ph_length] - graph_lst = [graph1, graph2] - out = enc(graph_lst, inp, ph2word, etypes_lst) - print(out.shape) # [N_sentence, feat, ph_length] diff --git a/spaces/AIZerotoHero-Health4All/01-Gradio-Speech2Text2Speech-AIPipeline/app.py b/spaces/AIZerotoHero-Health4All/01-Gradio-Speech2Text2Speech-AIPipeline/app.py deleted file mode 100644 index 6c4b5962cc6aa534cab8ab7d367b0a7f942f90ba..0000000000000000000000000000000000000000 --- a/spaces/AIZerotoHero-Health4All/01-Gradio-Speech2Text2Speech-AIPipeline/app.py +++ /dev/null @@ -1,160 +0,0 @@ -import streamlit as st -import datetime -from transformers import pipeline -import gradio as gr - -import tempfile -from typing import Optional -import numpy as np -from TTS.utils.manage import ModelManager -from TTS.utils.synthesizer import Synthesizer - -# PersistDataset ----- -import os -import csv -import gradio as gr -from gradio import inputs, outputs -import huggingface_hub -from huggingface_hub import Repository, hf_hub_download, upload_file -from datetime import datetime - -# created new dataset as awacke1/MindfulStory.csv -#DATASET_REPO_URL = "https://huggingface.co/datasets/awacke1/MindfulStory.csv" -#DATASET_REPO_ID = "awacke1/MindfulStory.csv" -#DATA_FILENAME = "MindfulStory.csv" -#DATA_FILE = os.path.join("data", DATA_FILENAME) -HF_TOKEN = os.environ.get("HF_TOKEN") - -# Download dataset repo using hub download -#try: -# hf_hub_download( -# repo_id=DATASET_REPO_ID, -# filename=DATA_FILENAME, -# cache_dir=DATA_DIRNAME, -# force_filename=DATA_FILENAME -# ) -#except: -# print("file not found") - -#def AIMemory(name: str, message: str): -# if name and message: - # with open(DATA_FILE, "a") as csvfile: - # writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"]) - # writer.writerow({"name": name, "message": message, "time": str(datetime.now())}) - # commit_url = repo.push_to_hub() - # return {"name": name, "message": message, "time": str(datetime.now())} - -#with open('Mindfulness.txt', 'r') as file: -# context = file.read() - -# Set up cloned dataset from repo for operations -#repo = Repository( local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN) - -# set up ASR -asr = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h") - -# set up TTS -MODEL_NAMES = [ - "en/ljspeech/tacotron2-DDC", - "en/ljspeech/glow-tts", - "en/ljspeech/speedy-speech-wn", - "en/ljspeech/vits", - "en/sam/tacotron-DDC", - "fr/mai/tacotron2-DDC", - "de/thorsten/tacotron2-DCA", -] - -# Use Model Manager to load vocoders -MODELS = {} -manager = ModelManager() -for MODEL_NAME in MODEL_NAMES: - print(f"downloading {MODEL_NAME}") - model_path, config_path, model_item = manager.download_model(f"tts_models/{MODEL_NAME}") - vocoder_name: Optional[str] = model_item["default_vocoder"] - vocoder_path = None - vocoder_config_path = None - if vocoder_name is not None: - vocoder_path, vocoder_config_path, _ = manager.download_model(vocoder_name) - - synthesizer = Synthesizer( - model_path, config_path, None, vocoder_path, vocoder_config_path, - ) - MODELS[MODEL_NAME] = synthesizer - -# transcribe -def transcribe(audio): - text = asr(audio)["text"] - return text - -#text classifier -classifier = pipeline("text-classification") - - -def speech_to_text(speech): - text = asr(speech)["text"] - #rMem = AIMemory("STT", text) - return text - -def text_to_sentiment(text): - sentiment = classifier(text)[0]["label"] - #rMem = AIMemory(text, sentiment) - return sentiment - -def upsert(text): - date_time =str(datetime.datetime.today()) - doc_ref = db.collection('Text2SpeechSentimentSave').document(date_time) - doc_ref.set({u'firefield': 'Recognize Speech', u'first': 'https://huggingface.co/spaces/awacke1/TTS-STT-Blocks/', u'last': text, u'born': date_time,}) - saved = select('TTS-STT', date_time) - return saved - -def select(collection, document): - doc_ref = db.collection(collection).document(document) - doc = doc_ref.get() - docid = ("The id is: ", doc.id) - contents = ("The contents are: ", doc.to_dict()) - return contents - -def selectall(text): - docs = db.collection('Text2SpeechSentimentSave').stream() - doclist='' - for doc in docs: - r=(f'{doc.id} => {doc.to_dict()}') - doclist += r - return doclist - -def tts(text: str, model_name: str): - print(text, model_name) - synthesizer = MODELS.get(model_name, None) - if synthesizer is None: - raise NameError("model not found") - wavs = synthesizer.tts(text) - with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp: - synthesizer.save_wav(wavs, fp) - - #rMem = AIMemory("TTS", text + model_name) - - return fp.name - -demo = gr.Blocks() -with demo: - audio_file = gr.inputs.Audio(source="microphone", type="filepath") - text = gr.Textbox(label="Speech to Text") - #label = gr.Label() - #saved = gr.Textbox(label="Saved") - #savedAll = gr.Textbox(label="SavedAll") - TTSchoice = gr.inputs.Radio( label="Pick a Text to Speech Model", choices=MODEL_NAMES, ) - audio = gr.Audio(label="Output", interactive=False) - - b1 = gr.Button("Recognize Speech") - #b2 = gr.Button("Classify Sentiment") - #b3 = gr.Button("Save Speech to Text") - #b4 = gr.Button("Retrieve All") - b5 = gr.Button("Read It Back Aloud") - - b1.click(speech_to_text, inputs=audio_file, outputs=text) - #b2.click(text_to_sentiment, inputs=text, outputs=label) - #b3.click(upsert, inputs=text, outputs=saved) - #b4.click(selectall, inputs=text, outputs=savedAll) - b5.click(tts, inputs=[text,TTSchoice], outputs=audio) - -demo.launch(share=True) \ No newline at end of file diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov6/yolov6_m_syncbn_fast_8xb32-300e_coco.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov6/yolov6_m_syncbn_fast_8xb32-300e_coco.py deleted file mode 100644 index 09811c8c06fb81a061ac4da7904c8d7d1e248411..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov6/yolov6_m_syncbn_fast_8xb32-300e_coco.py +++ /dev/null @@ -1,62 +0,0 @@ -_base_ = './yolov6_s_syncbn_fast_8xb32-300e_coco.py' - -# ======================= Possible modified parameters ======================= -# -----model related----- -# The scaling factor that controls the depth of the network structure -deepen_factor = 0.6 -# The scaling factor that controls the width of the network structure -widen_factor = 0.75 - -# -----train val related----- -affine_scale = 0.9 # YOLOv5RandomAffine scaling ratio - -# ============================== Unmodified in most cases =================== -model = dict( - backbone=dict( - type='YOLOv6CSPBep', - deepen_factor=deepen_factor, - widen_factor=widen_factor, - hidden_ratio=2. / 3, - block_cfg=dict(type='RepVGGBlock'), - act_cfg=dict(type='ReLU', inplace=True)), - neck=dict( - type='YOLOv6CSPRepPAFPN', - deepen_factor=deepen_factor, - widen_factor=widen_factor, - block_cfg=dict(type='RepVGGBlock'), - hidden_ratio=2. / 3, - block_act_cfg=dict(type='ReLU', inplace=True)), - bbox_head=dict( - type='YOLOv6Head', head_module=dict(widen_factor=widen_factor))) - -mosaic_affine_pipeline = [ - dict( - type='Mosaic', - img_scale=_base_.img_scale, - pad_val=114.0, - pre_transform=_base_.pre_transform), - dict( - type='YOLOv5RandomAffine', - max_rotate_degree=0.0, - max_shear_degree=0.0, - scaling_ratio_range=(1 - affine_scale, 1 + affine_scale), - # img_scale is (width, height) - border=(-_base_.img_scale[0] // 2, -_base_.img_scale[1] // 2), - border_val=(114, 114, 114)) -] - -train_pipeline = [ - *_base_.pre_transform, *mosaic_affine_pipeline, - dict( - type='YOLOv5MixUp', - prob=0.1, - pre_transform=[*_base_.pre_transform, *mosaic_affine_pipeline]), - dict(type='YOLOv5HSVRandomAug'), - dict(type='mmdet.RandomFlip', prob=0.5), - dict( - type='mmdet.PackDetInputs', - meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'flip', - 'flip_direction')) -] - -train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) diff --git a/spaces/Aabbhishekk/MistralQnA/README.md b/spaces/Aabbhishekk/MistralQnA/README.md deleted file mode 100644 index 8e09e5e12fb449bcc6f03fdb4072754bdb02c1a3..0000000000000000000000000000000000000000 --- a/spaces/Aabbhishekk/MistralQnA/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: FalconInstructQA -emoji: 😻 -colorFrom: red -colorTo: gray -sdk: streamlit -sdk_version: 1.21.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/Abs6187/AI_Chatbot/app.py b/spaces/Abs6187/AI_Chatbot/app.py deleted file mode 100644 index 726242519429896114d64b41de842e1d3913f28a..0000000000000000000000000000000000000000 --- a/spaces/Abs6187/AI_Chatbot/app.py +++ /dev/null @@ -1,24 +0,0 @@ - -import gradio -from transformers import pipeline - -import openai -import gradio - -openai.api_key = "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" - -messages = [{"role": "system", "content": "You are a Indian Lawyer and Gave Advice according to Indian constitution"}] - -def CustomChatGPT(user_input): - messages.append({"role": "user", "content": user_input}) - response = openai.ChatCompletion.create( - model = "gpt-3.5-turbo", - messages = messages - ) - ChatGPT_reply = response["choices"][0]["message"]["content"] - messages.append({"role": "assistant", "content": ChatGPT_reply}) - return ChatGPT_reply - -iface = gradio.Interface(fn=CustomChatGPT, inputs = "text", outputs = "text", title = "AI Chat Bot for Legal Assistance This is Free version and if it doesnt work kindly contact at Email ID contact2abhaygupta@gmail.com") -print(" This is Free version and if it doesnt work kindly contact at Email ID contact2abhaygupta@gmail.com") -iface.launch(inline=False) diff --git a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/Mishalsgpt.py b/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/Mishalsgpt.py deleted file mode 100644 index 63080c674900a181f66380bcfe6c185b7469cebd..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/Mishalsgpt.py +++ /dev/null @@ -1,23 +0,0 @@ -import os, requests, uuid -from ...typing import sha256, Dict, get_type_hints - -url = 'https://mishalsgpt.vercel.app' -model = ['gpt-3.5-turbo-16k-0613', 'gpt-3.5-turbo'] -supports_stream = True -needs_auth = False - -def _create_completion(model: str, messages: list, stream: bool, **kwargs): - headers = { - 'Content-Type': 'application/json', - } - data = { - 'model': model, - 'temperature': 0.7, - 'messages': messages - } - response = requests.post(url + '/api/openai/v1/chat/completions', - headers=headers, json=data, stream=True) - yield response.json()['choices'][0]['message']['content'] - -params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \ - '(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]]) diff --git a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/deprecated/V50.py b/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/deprecated/V50.py deleted file mode 100644 index 9a8b032c3949d493de81ff49b2e24ab33a2004f4..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/deprecated/V50.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -import uuid - -import requests - -from ...typing import Any, CreateResult -from ..base_provider import BaseProvider - - -class V50(BaseProvider): - url = 'https://p5.v50.ltd' - supports_gpt_35_turbo = True - supports_stream = False - needs_auth = False - working = False - - @staticmethod - def create_completion( - model: str, - messages: list[dict[str, str]], - stream: bool, **kwargs: Any) -> CreateResult: - - conversation = "\n".join(f"{message['role']}: {message['content']}" for message in messages) - conversation += "\nassistant: " - - payload = { - "prompt" : conversation, - "options" : {}, - "systemMessage" : ".", - "temperature" : kwargs.get("temperature", 0.4), - "top_p" : kwargs.get("top_p", 0.4), - "model" : model, - "user" : str(uuid.uuid4()) - } - - headers = { - 'authority' : 'p5.v50.ltd', - 'accept' : 'application/json, text/plain, */*', - 'accept-language' : 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', - 'content-type' : 'application/json', - 'origin' : 'https://p5.v50.ltd', - 'referer' : 'https://p5.v50.ltd/', - 'sec-ch-ua-platform': '"Windows"', - 'sec-fetch-dest' : 'empty', - 'sec-fetch-mode' : 'cors', - 'sec-fetch-site' : 'same-origin', - 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36' - } - response = requests.post("https://p5.v50.ltd/api/chat-process", - json=payload, headers=headers, proxies=kwargs['proxy'] if 'proxy' in kwargs else {}) - - if "https://fk1.v50.ltd" not in response.text: - yield response.text - - @classmethod - @property - def params(cls): - params = [ - ("model", "str"), - ("messages", "list[dict[str, str]]"), - ("stream", "bool"), - ("temperature", "float"), - ("top_p", "int"), - ] - param = ", ".join([": ".join(p) for p in params]) - return f"g4f.provider.{cls.__name__} supports: ({param})" \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/csvtoarray.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/csvtoarray.d.ts deleted file mode 100644 index f99d1e6986a349a63358cc7c0028973d9b22da04..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/csvtoarray.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import CSVToArray from './data/csvtoarray/CSVToArray'; -export default CSVToArray; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Custom.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Custom.d.ts deleted file mode 100644 index ff04aebdfeb33c133b5f38922677ada549283e03..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Custom.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -import Base from '../base/Base'; -import * as Geoms from '../../../plugins/gameobjects/shape/shapes/geoms'; - -export default Custom; - -declare namespace Custom { - - type NameTypes = string | string[] | number; - - type Arc = Geoms.Arc; - type Circle = Geoms.Circle; - type Curve = Geoms.Curve; - type Ellipse = Geoms.Ellipse; - type Line = Geoms.Line; - type Lines = Geoms.Lines; - type Rectangle = Geoms.Rectangle; - type RoundRectangle = Geoms.RoundRectangle; - type Triangle = Geoms.Triangle; - type ShapeTypes = Arc | Circle | Curve | Ellipse | - Line | Lines | Rectangle | RoundRectangle | Triangle; - - interface IConfig extends Base.IConfig { - create?: { - arc?: NameTypes, - circle?: NameTypes, - ellipse?: NameTypes, - line?: NameTypes, - lines?: NameTypes, - rectangle?: NameTypes, - triangle?: NameTypes, - } | ((this: Custom) => void); - - update?: (this: Custom) => void; - - type?: string, - } - -} - -declare class Custom extends Base { - constructor( - scene: Phaser.Scene, - config?: Custom.IConfig - ) - - getShape(name: string): Custom.ShapeTypes; - getShapes(): Custom.ShapeTypes[]; -} \ No newline at end of file diff --git a/spaces/AlexZou/Deploy_Restoration/net/block.py b/spaces/AlexZou/Deploy_Restoration/net/block.py deleted file mode 100644 index 944a167784bbeb40de1079a264d7e3772f5f36a5..0000000000000000000000000000000000000000 --- a/spaces/AlexZou/Deploy_Restoration/net/block.py +++ /dev/null @@ -1,477 +0,0 @@ -import torch.nn as nn -import torch.nn.functional as F -import torch as th -import datetime -import os -import time -import timeit -import copy -import numpy as np -from torch.nn import ModuleList -from torch.nn import Conv2d -from torch.nn import LeakyReLU - - - - -#PixelwiseNorm代替了BatchNorm -class PixelwiseNorm(th.nn.Module): - def __init__(self): - super(PixelwiseNorm, self).__init__() - - def forward(self, x, alpha=1e-8): - """ - forward pass of the module - :param x: input activations volume - :param alpha: small number for numerical stability - :return: y => pixel normalized activations - """ - y = x.pow(2.).mean(dim=1, keepdim=True).add(alpha).sqrt() # [N1HW] - y = x / y # normalize the input x volume - return y - - - -class MinibatchStdDev(th.nn.Module): - """ - Minibatch standard deviation layer for the discriminator - """ - - def __init__(self): - """ - derived class constructor - """ - super().__init__() - - def forward(self, x, alpha=1e-8): - """ - forward pass of the layer - :param x: input activation volume - :param alpha: small number for numerical stability - :return: y => x appended with standard deviation constant map - """ - batch_size, _, height, width = x.shape - - # [B x C x H x W] Subtract mean over batch. - y = x - x.mean(dim=0, keepdim=True) - - # [1 x C x H x W] Calc standard deviation over batch - y = th.sqrt(y.pow(2.).mean(dim=0, keepdim=False) + alpha) - - # [1] Take average over feature_maps and pixels. - y = y.mean().view(1, 1, 1, 1) - - # [B x 1 x H x W] Replicate over group and pixels. - y = y.repeat(batch_size, 1, height, width) - - # [B x C x H x W] Append as new feature_map. - y = th.cat([x, y], 1) - - # return the computed values: - return y - - - - - -# ========================================================== -# Equalized learning rate blocks: -# extending Conv2D and Deconv2D layers for equalized learning rate logic -# ========================================================== -class _equalized_conv2d(th.nn.Module): - """ conv2d with the concept of equalized learning rate - Args: - :param c_in: input channels - :param c_out: output channels - :param k_size: kernel size (h, w) should be a tuple or a single integer - :param stride: stride for conv - :param pad: padding - :param bias: whether to use bias or not - """ - - def __init__(self, c_in, c_out, k_size, stride=1, pad=0, bias=True): - """ constructor for the class """ - from torch.nn.modules.utils import _pair - from numpy import sqrt, prod - - super().__init__() - - # define the weight and bias if to be used - self.weight = th.nn.Parameter(th.nn.init.normal_( - th.empty(c_out, c_in, *_pair(k_size)) - )) - - self.use_bias = bias - self.stride = stride - self.pad = pad - - if self.use_bias: - self.bias = th.nn.Parameter(th.FloatTensor(c_out).fill_(0)) - - fan_in = prod(_pair(k_size)) * c_in # value of fan_in - self.scale = sqrt(2) / sqrt(fan_in) - - def forward(self, x): - """ - forward pass of the network - :param x: input - :return: y => output - """ - from torch.nn.functional import conv2d - - return conv2d(input=x, - weight=self.weight * self.scale, # scale the weight on runtime - bias=self.bias if self.use_bias else None, - stride=self.stride, - padding=self.pad) - - def extra_repr(self): - return ", ".join(map(str, self.weight.shape)) - - -class _equalized_deconv2d(th.nn.Module): - """ Transpose convolution using the equalized learning rate - Args: - :param c_in: input channels - :param c_out: output channels - :param k_size: kernel size - :param stride: stride for convolution transpose - :param pad: padding - :param bias: whether to use bias or not - """ - - def __init__(self, c_in, c_out, k_size, stride=1, pad=0, bias=True): - """ constructor for the class """ - from torch.nn.modules.utils import _pair - from numpy import sqrt - - super().__init__() - - # define the weight and bias if to be used - self.weight = th.nn.Parameter(th.nn.init.normal_( - th.empty(c_in, c_out, *_pair(k_size)) - )) - - self.use_bias = bias - self.stride = stride - self.pad = pad - - if self.use_bias: - self.bias = th.nn.Parameter(th.FloatTensor(c_out).fill_(0)) - - fan_in = c_in # value of fan_in for deconv - self.scale = sqrt(2) / sqrt(fan_in) - - def forward(self, x): - """ - forward pass of the layer - :param x: input - :return: y => output - """ - from torch.nn.functional import conv_transpose2d - - return conv_transpose2d(input=x, - weight=self.weight * self.scale, # scale the weight on runtime - bias=self.bias if self.use_bias else None, - stride=self.stride, - padding=self.pad) - - def extra_repr(self): - return ", ".join(map(str, self.weight.shape)) - - - -#basic block of the encoding part of the genarater -#编码器的基本卷积块 -class conv_block(nn.Module): - """ - Convolution Block - with two convolution layers - """ - def __init__(self, in_ch, out_ch,use_eql=True): - super(conv_block, self).__init__() - - if use_eql: - self.conv_1= _equalized_conv2d(in_ch, out_ch, (1, 1), - pad=0, bias=True) - self.conv_2 = _equalized_conv2d(out_ch, out_ch, (3, 3), - pad=1, bias=True) - self.conv_3 = _equalized_conv2d(out_ch, out_ch, (3, 3), - pad=1, bias=True) - - else: - self.conv_1 = Conv2d(in_ch, out_ch, (3, 3), - padding=1, bias=True) - self.conv_2 = Conv2d(out_ch, out_ch, (3, 3), - padding=1, bias=True) - - # pixel_wise feature normalizer: - self.pixNorm = PixelwiseNorm() - - # leaky_relu: - self.lrelu = LeakyReLU(0.2) - - def forward(self, x): - """ - forward pass of the block - :param x: input - :return: y => output - """ - from torch.nn.functional import interpolate - - #y = interpolate(x, scale_factor=2) - y=self.conv_1(self.lrelu(self.pixNorm(x))) - residual=y - y=self.conv_2(self.lrelu(self.pixNorm(y))) - y=self.conv_3(self.lrelu(self.pixNorm(y))) - y=y+residual - - - return y - - - - -#basic up convolution block of the encoding part of the genarater -#编码器的基本卷积块 -class up_conv(nn.Module): - """ - Up Convolution Block - """ - def __init__(self, in_ch, out_ch,use_eql=True): - super(up_conv, self).__init__() - if use_eql: - self.conv_1= _equalized_conv2d(in_ch, out_ch, (1, 1), - pad=0, bias=True) - self.conv_2 = _equalized_conv2d(out_ch, out_ch, (3, 3), - pad=1, bias=True) - self.conv_3 = _equalized_conv2d(out_ch, out_ch, (3, 3), - pad=1, bias=True) - - else: - self.conv_1 = Conv2d(in_ch, out_ch, (3, 3), - padding=1, bias=True) - self.conv_2 = Conv2d(out_ch, out_ch, (3, 3), - padding=1, bias=True) - - # pixel_wise feature normalizer: - self.pixNorm = PixelwiseNorm() - - # leaky_relu: - self.lrelu = LeakyReLU(0.2) - - def forward(self, x): - """ - forward pass of the block - :param x: input - :return: y => output - """ - from torch.nn.functional import interpolate - - x = interpolate(x, scale_factor=2, mode="bilinear") - y=self.conv_1(self.lrelu(self.pixNorm(x))) - residual=y - y=self.conv_2(self.lrelu(self.pixNorm(y))) - y=self.conv_3(self.lrelu(self.pixNorm(y))) - y=y+residual - - return y - - - - -#判别器的最后一层 -class DisFinalBlock(th.nn.Module): - """ Final block for the Discriminator """ - - def __init__(self, in_channels, use_eql=True): - """ - constructor of the class - :param in_channels: number of input channels - :param use_eql: whether to use equalized learning rate - """ - from torch.nn import LeakyReLU - from torch.nn import Conv2d - - super().__init__() - - # declare the required modules for forward pass - self.batch_discriminator = MinibatchStdDev() - - if use_eql: - self.conv_1 = _equalized_conv2d(in_channels + 1, in_channels, (3, 3), - pad=1, bias=True) - self.conv_2 = _equalized_conv2d(in_channels, in_channels, (4, 4),stride=2,pad=1, - bias=True) - - # final layer emulates the fully connected layer - self.conv_3 = _equalized_conv2d(in_channels, 1, (1, 1), bias=True) - - else: - # modules required: - self.conv_1 = Conv2d(in_channels + 1, in_channels, (3, 3), padding=1, bias=True) - self.conv_2 = Conv2d(in_channels, in_channels, (4, 4), bias=True) - - # final conv layer emulates a fully connected layer - self.conv_3 = Conv2d(in_channels, 1, (1, 1), bias=True) - - # leaky_relu: - self.lrelu = LeakyReLU(0.2) - - def forward(self, x): - """ - forward pass of the FinalBlock - :param x: input - :return: y => output - """ - # minibatch_std_dev layer - y = self.batch_discriminator(x) - - # define the computations - y = self.lrelu(self.conv_1(y)) - y = self.lrelu(self.conv_2(y)) - - # fully connected layer - y = self.conv_3(y) # This layer has linear activation - - # flatten the output raw discriminator scores - return y - - - -#判别器基本卷积块 -class DisGeneralConvBlock(th.nn.Module): - """ General block in the discriminator """ - - def __init__(self, in_channels, out_channels, use_eql=True): - """ - constructor of the class - :param in_channels: number of input channels - :param out_channels: number of output channels - :param use_eql: whether to use equalized learning rate - """ - from torch.nn import AvgPool2d, LeakyReLU - from torch.nn import Conv2d - - super().__init__() - - if use_eql: - self.conv_1 = _equalized_conv2d(in_channels, in_channels, (3, 3), - pad=1, bias=True) - self.conv_2 = _equalized_conv2d(in_channels, out_channels, (3, 3), - pad=1, bias=True) - else: - # convolutional modules - self.conv_1 = Conv2d(in_channels, in_channels, (3, 3), - padding=1, bias=True) - self.conv_2 = Conv2d(in_channels, out_channels, (3, 3), - padding=1, bias=True) - - self.downSampler = AvgPool2d(2) # downsampler - - # leaky_relu: - self.lrelu = LeakyReLU(0.2) - - def forward(self, x): - """ - forward pass of the module - :param x: input - :return: y => output - """ - # define the computations - y = self.lrelu(self.conv_1(x)) - y = self.lrelu(self.conv_2(y)) - y = self.downSampler(y) - - return y - - - - - -class from_rgb(nn.Module): - """ - The RGB image is transformed into a multi-channel feature map to be concatenated with - the feature map with the same number of channels in the network - 把RGB图转换为多通道特征图,以便与网络中相同通道数的特征图拼接 - """ - def __init__(self, outchannels, use_eql=True): - super(from_rgb, self).__init__() - if use_eql: - self.conv_1 = _equalized_conv2d(3, outchannels, (1, 1), bias=True) - else: - self.conv_1 = nn.Conv2d(3, outchannels, (1, 1),bias=True) - # pixel_wise feature normalizer: - self.pixNorm = PixelwiseNorm() - - # leaky_relu: - self.lrelu = LeakyReLU(0.2) - - - def forward(self, x): - """ - forward pass of the block - :param x: input - :return: y => output - """ - y = self.pixNorm(self.lrelu(self.conv_1(x))) - return y - -class to_rgb(nn.Module): - """ - 把多通道特征图转换为RGB三通道图,以便输入判别器 - The multi-channel feature map is converted into RGB image for input to the discriminator - """ - def __init__(self, inchannels, use_eql=True): - super(to_rgb, self).__init__() - if use_eql: - self.conv_1 = _equalized_conv2d(inchannels, 3, (1, 1), bias=True) - else: - self.conv_1 = nn.Conv2d(inchannels, 3, (1, 1),bias=True) - - - - - - def forward(self, x): - """ - forward pass of the block - :param x: input - :return: y => output - """ - - y = self.conv_1(x) - - return y - -class Flatten(nn.Module): - def forward(self, x): - return x.view(x.size(0), -1) - - - -class CCA(nn.Module): - """ - CCA Block - """ - def __init__(self, F_g, F_x): - super().__init__() - self.mlp_x = nn.Sequential( - Flatten(), - nn.Linear(F_x, F_x)) - self.mlp_g = nn.Sequential( - Flatten(), - nn.Linear(F_g, F_x)) - self.relu = nn.ReLU(inplace=True) - - def forward(self, g, x): - # channel-wise attention - avg_pool_x = F.avg_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3))) - channel_att_x = self.mlp_x(avg_pool_x) - avg_pool_g = F.avg_pool2d( g, (g.size(2), g.size(3)), stride=(g.size(2), g.size(3))) - channel_att_g = self.mlp_g(avg_pool_g) - channel_att_sum = (channel_att_x + channel_att_g)/2.0 - scale = th.sigmoid(channel_att_sum).unsqueeze(2).unsqueeze(3).expand_as(x) - x_after_channel = x * scale - out = self.relu(x_after_channel) - return out \ No newline at end of file diff --git "a/spaces/Ameaou/academic-chatgpt3.1/crazy_functions/Latex\345\205\250\346\226\207\346\266\246\350\211\262.py" "b/spaces/Ameaou/academic-chatgpt3.1/crazy_functions/Latex\345\205\250\346\226\207\346\266\246\350\211\262.py" deleted file mode 100644 index c299e59d3894b7ac2d33df1502746adaef4a47b8..0000000000000000000000000000000000000000 --- "a/spaces/Ameaou/academic-chatgpt3.1/crazy_functions/Latex\345\205\250\346\226\207\346\266\246\350\211\262.py" +++ /dev/null @@ -1,175 +0,0 @@ -from toolbox import update_ui -from toolbox import CatchException, report_execption, write_results_to_file -fast_debug = False - -class PaperFileGroup(): - def __init__(self): - self.file_paths = [] - self.file_contents = [] - self.sp_file_contents = [] - self.sp_file_index = [] - self.sp_file_tag = [] - - # count_token - from request_llm.bridge_all import model_info - enc = model_info["gpt-3.5-turbo"]['tokenizer'] - def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) - self.get_token_num = get_token_num - - def run_file_split(self, max_token_limit=1900): - """ - 将长文本分离开来 - """ - for index, file_content in enumerate(self.file_contents): - if self.get_token_num(file_content) < max_token_limit: - self.sp_file_contents.append(file_content) - self.sp_file_index.append(index) - self.sp_file_tag.append(self.file_paths[index]) - else: - from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf - segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit) - for j, segment in enumerate(segments): - self.sp_file_contents.append(segment) - self.sp_file_index.append(index) - self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.tex") - - print('Segmentation: done') - -def 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'): - import time, os, re - from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency - - - # <-------- 读取Latex文件,删除其中的所有注释 ----------> - pfg = PaperFileGroup() - - for index, fp in enumerate(file_manifest): - with open(fp, 'r', encoding='utf-8', errors='replace') as f: - file_content = f.read() - # 定义注释的正则表达式 - comment_pattern = r'%.*' - # 使用正则表达式查找注释,并替换为空字符串 - clean_tex_content = re.sub(comment_pattern, '', file_content) - # 记录删除注释后的文本 - pfg.file_paths.append(fp) - pfg.file_contents.append(clean_tex_content) - - # <-------- 拆分过长的latex文件 ----------> - pfg.run_file_split(max_token_limit=1024) - n_split = len(pfg.sp_file_contents) - - # <-------- 抽取摘要 ----------> - # if language == 'en': - # abs_extract_inputs = f"Please write an abstract for this paper" - - # # 单线,获取文章meta信息 - # paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive( - # inputs=abs_extract_inputs, - # inputs_show_user=f"正在抽取摘要信息。", - # llm_kwargs=llm_kwargs, - # chatbot=chatbot, history=[], - # sys_prompt="Your job is to collect information from materials。", - # ) - - # <-------- 多线程润色开始 ----------> - if language == 'en': - inputs_array = ["Below is a section from an academic paper, polish this section to meet the academic standard, improve the grammar, clarity and overall readability, do not modify any latex command such as \section, \cite and equations:" + - f"\n\n{frag}" for frag in pfg.sp_file_contents] - inputs_show_user_array = [f"Polish {f}" for f in pfg.sp_file_tag] - sys_prompt_array = ["You are a professional academic paper writer." for _ in range(n_split)] - elif language == 'zh': - inputs_array = [f"以下是一篇学术论文中的一段内容,请将此部分润色以满足学术标准,提高语法、清晰度和整体可读性,不要修改任何LaTeX命令,例如\section,\cite和方程式:" + - f"\n\n{frag}" for frag in pfg.sp_file_contents] - inputs_show_user_array = [f"润色 {f}" for f in pfg.sp_file_tag] - sys_prompt_array=["你是一位专业的中文学术论文作家。" for _ in range(n_split)] - - - gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( - inputs_array=inputs_array, - inputs_show_user_array=inputs_show_user_array, - llm_kwargs=llm_kwargs, - chatbot=chatbot, - history_array=[[""] for _ in range(n_split)], - sys_prompt_array=sys_prompt_array, - # max_workers=5, # 并行任务数量限制,最多同时执行5个,其他的排队等待 - scroller_max_len = 80 - ) - - # <-------- 整理结果,退出 ----------> - create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md" - res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name) - history = gpt_response_collection - chatbot.append((f"{fp}完成了吗?", res)) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - -@CatchException -def Latex英文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - # 基本信息:功能、贡献者 - chatbot.append([ - "函数插件功能?", - "对整个Latex项目进行润色。函数插件贡献者: Binary-Husky"]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 尝试导入依赖,如果缺少依赖,则给出安装建议 - try: - import tiktoken - except: - report_execption(chatbot, history, - a=f"解析项目: {txt}", - b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - history = [] # 清空历史,以免输入溢出 - import glob, os - if os.path.exists(txt): - project_folder = txt - else: - if txt == "": txt = '空空如也的输入栏' - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] - if len(file_manifest) == 0: - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - yield from 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en') - - - - - - -@CatchException -def Latex中文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - # 基本信息:功能、贡献者 - chatbot.append([ - "函数插件功能?", - "对整个Latex项目进行润色。函数插件贡献者: Binary-Husky"]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 尝试导入依赖,如果缺少依赖,则给出安装建议 - try: - import tiktoken - except: - report_execption(chatbot, history, - a=f"解析项目: {txt}", - b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - history = [] # 清空历史,以免输入溢出 - import glob, os - if os.path.exists(txt): - project_folder = txt - else: - if txt == "": txt = '空空如也的输入栏' - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] - if len(file_manifest) == 0: - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - yield from 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh') \ No newline at end of file diff --git a/spaces/Andy1621/uniformer_image_detection/configs/ld/ld_r34_gflv1_r101_fpn_coco_1x.py b/spaces/Andy1621/uniformer_image_detection/configs/ld/ld_r34_gflv1_r101_fpn_coco_1x.py deleted file mode 100644 index 905651d1f1d7cd956147111bba6d427e59ce1895..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/ld/ld_r34_gflv1_r101_fpn_coco_1x.py +++ /dev/null @@ -1,19 +0,0 @@ -_base_ = ['./ld_r18_gflv1_r101_fpn_coco_1x.py'] -model = dict( - pretrained='torchvision://resnet34', - backbone=dict( - type='ResNet', - depth=34, - num_stages=4, - out_indices=(0, 1, 2, 3), - frozen_stages=1, - norm_cfg=dict(type='BN', requires_grad=True), - norm_eval=True, - style='pytorch'), - neck=dict( - type='FPN', - in_channels=[64, 128, 256, 512], - out_channels=256, - start_level=1, - add_extra_convs='on_output', - num_outs=5)) diff --git a/spaces/Anilegna/Colour-Personallity/app.py b/spaces/Anilegna/Colour-Personallity/app.py deleted file mode 100644 index b8e324b9c29780cc194b84219d4782bd519931d7..0000000000000000000000000000000000000000 --- a/spaces/Anilegna/Colour-Personallity/app.py +++ /dev/null @@ -1,172 +0,0 @@ -### ----------------------------- ### -### libraries ### -### ----------------------------- ### - -import gradio as gr -import pandas as pd -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.linear_model import LogisticRegression -from sklearn import metrics - - -### ------------------------------ ### -### data transformation ### -### ------------------------------ ### - -# load dataset -uncleaned_data = pd.read_csv('data.csv') - -# remove timestamp from dataset (always first column) -uncleaned_data = uncleaned_data.iloc[: , 1:] -data = pd.DataFrame() - -# keep track of which columns are categorical and what -# those columns' value mappings are -# structure: {colname1: {...}, colname2: {...} } -cat_value_dicts = {} -final_colname = uncleaned_data.columns[len(uncleaned_data.columns) - 1] - -# for each column... -for (colname, colval) in uncleaned_data.iteritems(): - - # check if col is already a number; if so, add col directly - # to new dataframe and skip to next column - if isinstance(colval.values[0], (np.integer, float)): - data[colname] = uncleaned_data[colname].copy() - continue - - # structure: {0: "lilac", 1: "blue", ...} - new_dict = {} - val = 0 # first index per column - transformed_col_vals = [] # new numeric datapoints - - # if not, for each item in that column... - for (row, item) in enumerate(colval.values): - - # if item is not in this col's dict... - if item not in new_dict: - new_dict[item] = val - val += 1 - - # then add numerical value to transformed dataframe - transformed_col_vals.append(new_dict[item]) - - # reverse dictionary only for final col (0, 1) => (vals) - if colname == final_colname: - new_dict = {value : key for (key, value) in new_dict.items()} - - cat_value_dicts[colname] = new_dict - data[colname] = transformed_col_vals - - -### -------------------------------- ### -### model training ### -### -------------------------------- ### - -# select features and predicton; automatically selects last column as prediction -cols = len(data.columns) -num_features = cols - 1 -x = data.iloc[: , :num_features] -y = data.iloc[: , num_features:] - -# split data into training and testing sets -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25) - -# instantiate the model (using default parameters) -model = LogisticRegression() -model.fit(x_train, y_train.values.ravel()) -y_pred = model.predict(x_test) - - -### -------------------------------- ### -### article generation ### -### -------------------------------- ### -# borrow file reading function from reader.py - -def get_feat(): - feats = [abs(x) for x in model.coef_[0]] - max_val = max(feats) - idx = feats.index(max_val) - return data.columns[idx] - -acc = str(round(metrics.accuracy_score(y_test, y_pred) * 100, 1)) + "%" -most_imp_feat = get_feat() -# info = get_article(acc, most_imp_feat) - - - -### ------------------------------- ### -### interface creation ### -### ------------------------------- ### - - -# predictor for generic number of features -def general_predictor(*args): - features = [] - - # transform categorical input - for colname, arg in zip(data.columns, args): - if (colname in cat_value_dicts): - features.append(cat_value_dicts[colname][arg]) - else: - features.append(arg) - - # predict single datapoint - new_input = [features] - result = model.predict(new_input) - return cat_value_dicts[final_colname][result[0]] - -# add data labels to replace those lost via star-args - - -block = gr.Blocks() - -with open('info.md') as f: - with block: - gr.Markdown(f.readline()) - gr.Markdown('Take the quiz to get a personalized recommendation using AI.') - - with gr.Row(): - with gr.Box(): - inputls = [] - for colname in data.columns: - # skip last column - if colname == final_colname: - continue - - # access categories dict if data is categorical - # otherwise, just use a number input - if colname in cat_value_dicts: - radio_options = list(cat_value_dicts[colname].keys()) - inputls.append(gr.inputs.Dropdown(choices=radio_options, type="value", label=colname)) - else: - # add numerical input - inputls.append(gr.inputs.Number(label=colname)) - gr.Markdown("
") - - submit = gr.Button("Click to see your personalized result!", variant="primary") - gr.Markdown("
") - output = gr.Textbox(label="Your recommendation:", placeholder="your recommendation will appear here") - - submit.click(fn=general_predictor, inputs=inputls, outputs=output) - gr.Markdown("
") - - with gr.Row(): - with gr.Box(): - gr.Markdown(f"

Accuracy:

{acc}") - with gr.Box(): - gr.Markdown(f"

Most important feature:

{most_imp_feat}") - - gr.Markdown("
") - - with gr.Box(): - gr.Markdown('''⭐ Note that model accuracy is based on the uploaded data.csv and reflects how well the AI model can give correct recommendations for that dataset. Model accuracy and most important feature can be helpful for understanding how the model works, but should not be considered absolute facts about the real world.''') - - with gr.Box(): - with open('info.md') as f: - f.readline() - gr.Markdown(f.read()) - -# show the interface -block.launch() \ No newline at end of file diff --git a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/utils.py b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/utils.py deleted file mode 100644 index e4eef224bbce1c22fc1595dfbba2fbfdc5d1752d..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/utils.py +++ /dev/null @@ -1,132 +0,0 @@ -import os -import re -from datetime import datetime -from pathlib import Path - -from modules import github, shared -from modules.logging_colors import logger - - -# Helper function to get multiple values from shared.gradio -def gradio(*keys): - if len(keys) == 1 and type(keys[0]) in [list, tuple]: - keys = keys[0] - - return [shared.gradio[k] for k in keys] - - -def save_file(fname, contents): - if fname == '': - logger.error('File name is empty!') - return - - root_folder = Path(__file__).resolve().parent.parent - abs_path = Path(fname).resolve() - rel_path = abs_path.relative_to(root_folder) - if rel_path.parts[0] == '..': - logger.error(f'Invalid file path: {fname}') - return - - with open(abs_path, 'w', encoding='utf-8') as f: - f.write(contents) - - logger.info(f'Saved {abs_path}.') - - -def delete_file(fname): - if fname == '': - logger.error('File name is empty!') - return - - root_folder = Path(__file__).resolve().parent.parent - abs_path = Path(fname).resolve() - rel_path = abs_path.relative_to(root_folder) - if rel_path.parts[0] == '..': - logger.error(f'Invalid file path: {fname}') - return - - if abs_path.exists(): - abs_path.unlink() - logger.info(f'Deleted {fname}.') - - -def current_time(): - return f"{datetime.now().strftime('%Y-%m-%d-%H%M%S')}" - - -def atoi(text): - return int(text) if text.isdigit() else text.lower() - - -# Replace multiple string pairs in a string -def replace_all(text, dic): - for i, j in dic.items(): - text = text.replace(i, j) - - return text - - -def natural_keys(text): - return [atoi(c) for c in re.split(r'(\d+)', text)] - - -def get_available_models(): - model_list = [] - for item in list(Path(f'{shared.args.model_dir}/').glob('*')): - if not item.name.endswith(('.txt', '-np', '.pt', '.json', '.yaml', '.py')) and 'llama-tokenizer' not in item.name: - model_list.append(re.sub('.pth$', '', item.name)) - - return sorted(model_list, key=natural_keys) - - -def get_available_presets(): - return sorted(set((k.stem for k in Path('presets').glob('*.yaml'))), key=natural_keys) - - -def get_available_prompts(): - prompts = [] - files = set((k.stem for k in Path('prompts').glob('*.txt'))) - prompts += sorted([k for k in files if re.match('^[0-9]', k)], key=natural_keys, reverse=True) - prompts += sorted([k for k in files if re.match('^[^0-9]', k)], key=natural_keys) - prompts += ['None'] - return prompts - - -def get_available_characters(): - paths = (x for x in Path('characters').iterdir() if x.suffix in ('.json', '.yaml', '.yml')) - return sorted(set((k.stem for k in paths)), key=natural_keys) - - -def get_available_instruction_templates(): - path = "instruction-templates" - paths = [] - if os.path.exists(path): - paths = (x for x in Path(path).iterdir() if x.suffix in ('.json', '.yaml', '.yml')) - - return ['None'] + sorted(set((k.stem for k in paths)), key=natural_keys) - - -def get_available_extensions(): - extensions = sorted(set(map(lambda x: x.parts[1], Path('extensions').glob('*/script.py'))), key=natural_keys) - extensions = [v for v in extensions if v not in github.new_extensions] - return extensions - - -def get_available_loras(): - return sorted([item.name for item in list(Path(shared.args.lora_dir).glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=natural_keys) - - -def get_datasets(path: str, ext: str): - # include subdirectories for raw txt files to allow training from a subdirectory of txt files - if ext == "txt": - return ['None'] + sorted(set([k.stem for k in list(Path(path).glob('txt')) + list(Path(path).glob('*/')) if k.stem != 'put-trainer-datasets-here']), key=natural_keys) - - return ['None'] + sorted(set([k.stem for k in Path(path).glob(f'*.{ext}') if k.stem != 'put-trainer-datasets-here']), key=natural_keys) - - -def get_available_chat_styles(): - return sorted(set(('-'.join(k.stem.split('-')[1:]) for k in Path('css').glob('chat_style*.css'))), key=natural_keys) - - -def get_available_grammars(): - return ['None'] + sorted([item.name for item in list(Path('grammars').glob('*.gbnf'))], key=natural_keys) diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/openpose/hand.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/openpose/hand.py deleted file mode 100644 index 3d0bf17165ad7eb225332b51f4a2aa16718664b2..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/openpose/hand.py +++ /dev/null @@ -1,86 +0,0 @@ -import cv2 -import json -import numpy as np -import math -import time -from scipy.ndimage.filters import gaussian_filter -import matplotlib.pyplot as plt -import matplotlib -import torch -from skimage.measure import label - -from .model import handpose_model -from . import util - -class Hand(object): - def __init__(self, model_path): - self.model = handpose_model() - if torch.cuda.is_available(): - self.model = self.model.cuda() - print('cuda') - model_dict = util.transfer(self.model, torch.load(model_path)) - self.model.load_state_dict(model_dict) - self.model.eval() - - def __call__(self, oriImg): - scale_search = [0.5, 1.0, 1.5, 2.0] - # scale_search = [0.5] - boxsize = 368 - stride = 8 - padValue = 128 - thre = 0.05 - multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search] - heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 22)) - # paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38)) - - for m in range(len(multiplier)): - scale = multiplier[m] - imageToTest = cv2.resize(oriImg, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC) - imageToTest_padded, pad = util.padRightDownCorner(imageToTest, stride, padValue) - im = np.transpose(np.float32(imageToTest_padded[:, :, :, np.newaxis]), (3, 2, 0, 1)) / 256 - 0.5 - im = np.ascontiguousarray(im) - - data = torch.from_numpy(im).float() - if torch.cuda.is_available(): - data = data.cuda() - # data = data.permute([2, 0, 1]).unsqueeze(0).float() - with torch.no_grad(): - output = self.model(data).cpu().numpy() - # output = self.model(data).numpy()q - - # extract outputs, resize, and remove padding - heatmap = np.transpose(np.squeeze(output), (1, 2, 0)) # output 1 is heatmaps - heatmap = cv2.resize(heatmap, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC) - heatmap = heatmap[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :] - heatmap = cv2.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv2.INTER_CUBIC) - - heatmap_avg += heatmap / len(multiplier) - - all_peaks = [] - for part in range(21): - map_ori = heatmap_avg[:, :, part] - one_heatmap = gaussian_filter(map_ori, sigma=3) - binary = np.ascontiguousarray(one_heatmap > thre, dtype=np.uint8) - # 全部小于阈值 - if np.sum(binary) == 0: - all_peaks.append([0, 0]) - continue - label_img, label_numbers = label(binary, return_num=True, connectivity=binary.ndim) - max_index = np.argmax([np.sum(map_ori[label_img == i]) for i in range(1, label_numbers + 1)]) + 1 - label_img[label_img != max_index] = 0 - map_ori[label_img == 0] = 0 - - y, x = util.npmax(map_ori) - all_peaks.append([x, y]) - return np.array(all_peaks) - -if __name__ == "__main__": - hand_estimation = Hand('../model/hand_pose_model.pth') - - # test_image = '../images/hand.jpg' - test_image = '../images/hand.jpg' - oriImg = cv2.imread(test_image) # B,G,R order - peaks = hand_estimation(oriImg) - canvas = util.draw_handpose(oriImg, peaks, True) - cv2.imshow('', canvas) - cv2.waitKey(0) \ No newline at end of file diff --git a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmseg/utils/logger.py b/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmseg/utils/logger.py deleted file mode 100644 index 4149d9eda3dfef07490352d22ac40c42460315e4..0000000000000000000000000000000000000000 --- a/spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmseg/utils/logger.py +++ /dev/null @@ -1,27 +0,0 @@ -import logging - -from annotator.uniformer.mmcv.utils import get_logger - - -def get_root_logger(log_file=None, log_level=logging.INFO): - """Get the root logger. - - The logger will be initialized if it has not been initialized. By default a - StreamHandler will be added. If `log_file` is specified, a FileHandler will - also be added. The name of the root logger is the top-level package name, - e.g., "mmseg". - - Args: - log_file (str | None): The log filename. If specified, a FileHandler - will be added to the root logger. - log_level (int): The root logger level. Note that only the process of - rank 0 is affected, while other processes will set the level to - "Error" and be silent most of the time. - - Returns: - logging.Logger: The root logger. - """ - - logger = get_logger(name='mmseg', log_file=log_file, log_level=log_level) - - return logger diff --git a/spaces/AsakuraMizu/moe-tts/attentions.py b/spaces/AsakuraMizu/moe-tts/attentions.py deleted file mode 100644 index 86bc73b5fe98cc7b443e9078553920346c996707..0000000000000000000000000000000000000000 --- a/spaces/AsakuraMizu/moe-tts/attentions.py +++ /dev/null @@ -1,300 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -from modules import LayerNorm - - -class Encoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init)) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels**-0.5 - self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1)) - if self.window_size is not None: - assert t_s == t_t, "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings) - scores_local = self._relative_position_to_absolute_position(rel_logits) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - assert t_s == t_t, "Local attention is only available for self-attention." - block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length) - scores = scores.masked_fill(block_mask == 0, -1e4) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) - output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings) - output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]])) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]])) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]])) - x_flat = x.view([batch, heads, length**2 + length*(length -1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - self.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(x * x_mask)) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/msgpack/fallback.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/msgpack/fallback.py deleted file mode 100644 index e8cebc1bef7870a5e772ea066c485eddf5c1c57c..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/msgpack/fallback.py +++ /dev/null @@ -1,1010 +0,0 @@ -"""Fallback pure Python implementation of msgpack""" -from datetime import datetime as _DateTime -import sys -import struct - - -PY2 = sys.version_info[0] == 2 -if PY2: - int_types = (int, long) - - def dict_iteritems(d): - return d.iteritems() - -else: - int_types = int - unicode = str - xrange = range - - def dict_iteritems(d): - return d.items() - - -if sys.version_info < (3, 5): - # Ugly hack... - RecursionError = RuntimeError - - def _is_recursionerror(e): - return ( - len(e.args) == 1 - and isinstance(e.args[0], str) - and e.args[0].startswith("maximum recursion depth exceeded") - ) - -else: - - def _is_recursionerror(e): - return True - - -if hasattr(sys, "pypy_version_info"): - # StringIO is slow on PyPy, StringIO is faster. However: PyPy's own - # StringBuilder is fastest. - from __pypy__ import newlist_hint - - try: - from __pypy__.builders import BytesBuilder as StringBuilder - except ImportError: - from __pypy__.builders import StringBuilder - USING_STRINGBUILDER = True - - class StringIO(object): - def __init__(self, s=b""): - if s: - self.builder = StringBuilder(len(s)) - self.builder.append(s) - else: - self.builder = StringBuilder() - - def write(self, s): - if isinstance(s, memoryview): - s = s.tobytes() - elif isinstance(s, bytearray): - s = bytes(s) - self.builder.append(s) - - def getvalue(self): - return self.builder.build() - -else: - USING_STRINGBUILDER = False - from io import BytesIO as StringIO - - newlist_hint = lambda size: [] - - -from .exceptions import BufferFull, OutOfData, ExtraData, FormatError, StackError - -from .ext import ExtType, Timestamp - - -EX_SKIP = 0 -EX_CONSTRUCT = 1 -EX_READ_ARRAY_HEADER = 2 -EX_READ_MAP_HEADER = 3 - -TYPE_IMMEDIATE = 0 -TYPE_ARRAY = 1 -TYPE_MAP = 2 -TYPE_RAW = 3 -TYPE_BIN = 4 -TYPE_EXT = 5 - -DEFAULT_RECURSE_LIMIT = 511 - - -def _check_type_strict(obj, t, type=type, tuple=tuple): - if type(t) is tuple: - return type(obj) in t - else: - return type(obj) is t - - -def _get_data_from_buffer(obj): - view = memoryview(obj) - if view.itemsize != 1: - raise ValueError("cannot unpack from multi-byte object") - return view - - -def unpackb(packed, **kwargs): - """ - Unpack an object from `packed`. - - Raises ``ExtraData`` when *packed* contains extra bytes. - Raises ``ValueError`` when *packed* is incomplete. - Raises ``FormatError`` when *packed* is not valid msgpack. - Raises ``StackError`` when *packed* contains too nested. - Other exceptions can be raised during unpacking. - - See :class:`Unpacker` for options. - """ - unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs) - unpacker.feed(packed) - try: - ret = unpacker._unpack() - except OutOfData: - raise ValueError("Unpack failed: incomplete input") - except RecursionError as e: - if _is_recursionerror(e): - raise StackError - raise - if unpacker._got_extradata(): - raise ExtraData(ret, unpacker._get_extradata()) - return ret - - -if sys.version_info < (2, 7, 6): - - def _unpack_from(f, b, o=0): - """Explicit type cast for legacy struct.unpack_from""" - return struct.unpack_from(f, bytes(b), o) - -else: - _unpack_from = struct.unpack_from - -_NO_FORMAT_USED = "" -_MSGPACK_HEADERS = { - 0xC4: (1, _NO_FORMAT_USED, TYPE_BIN), - 0xC5: (2, ">H", TYPE_BIN), - 0xC6: (4, ">I", TYPE_BIN), - 0xC7: (2, "Bb", TYPE_EXT), - 0xC8: (3, ">Hb", TYPE_EXT), - 0xC9: (5, ">Ib", TYPE_EXT), - 0xCA: (4, ">f"), - 0xCB: (8, ">d"), - 0xCC: (1, _NO_FORMAT_USED), - 0xCD: (2, ">H"), - 0xCE: (4, ">I"), - 0xCF: (8, ">Q"), - 0xD0: (1, "b"), - 0xD1: (2, ">h"), - 0xD2: (4, ">i"), - 0xD3: (8, ">q"), - 0xD4: (1, "b1s", TYPE_EXT), - 0xD5: (2, "b2s", TYPE_EXT), - 0xD6: (4, "b4s", TYPE_EXT), - 0xD7: (8, "b8s", TYPE_EXT), - 0xD8: (16, "b16s", TYPE_EXT), - 0xD9: (1, _NO_FORMAT_USED, TYPE_RAW), - 0xDA: (2, ">H", TYPE_RAW), - 0xDB: (4, ">I", TYPE_RAW), - 0xDC: (2, ">H", TYPE_ARRAY), - 0xDD: (4, ">I", TYPE_ARRAY), - 0xDE: (2, ">H", TYPE_MAP), - 0xDF: (4, ">I", TYPE_MAP), -} - - -class Unpacker(object): - """Streaming unpacker. - - Arguments: - - :param file_like: - File-like object having `.read(n)` method. - If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable. - - :param int read_size: - Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`) - - :param bool use_list: - If true, unpack msgpack array to Python list. - Otherwise, unpack to Python tuple. (default: True) - - :param bool raw: - If true, unpack msgpack raw to Python bytes. - Otherwise, unpack to Python str by decoding with UTF-8 encoding (default). - - :param int timestamp: - Control how timestamp type is unpacked: - - 0 - Timestamp - 1 - float (Seconds from the EPOCH) - 2 - int (Nanoseconds from the EPOCH) - 3 - datetime.datetime (UTC). Python 2 is not supported. - - :param bool strict_map_key: - If true (default), only str or bytes are accepted for map (dict) keys. - - :param callable object_hook: - When specified, it should be callable. - Unpacker calls it with a dict argument after unpacking msgpack map. - (See also simplejson) - - :param callable object_pairs_hook: - When specified, it should be callable. - Unpacker calls it with a list of key-value pairs after unpacking msgpack map. - (See also simplejson) - - :param str unicode_errors: - The error handler for decoding unicode. (default: 'strict') - This option should be used only when you have msgpack data which - contains invalid UTF-8 string. - - :param int max_buffer_size: - Limits size of data waiting unpacked. 0 means 2**32-1. - The default value is 100*1024*1024 (100MiB). - Raises `BufferFull` exception when it is insufficient. - You should set this parameter when unpacking data from untrusted source. - - :param int max_str_len: - Deprecated, use *max_buffer_size* instead. - Limits max length of str. (default: max_buffer_size) - - :param int max_bin_len: - Deprecated, use *max_buffer_size* instead. - Limits max length of bin. (default: max_buffer_size) - - :param int max_array_len: - Limits max length of array. - (default: max_buffer_size) - - :param int max_map_len: - Limits max length of map. - (default: max_buffer_size//2) - - :param int max_ext_len: - Deprecated, use *max_buffer_size* instead. - Limits max size of ext type. (default: max_buffer_size) - - Example of streaming deserialize from file-like object:: - - unpacker = Unpacker(file_like) - for o in unpacker: - process(o) - - Example of streaming deserialize from socket:: - - unpacker = Unpacker() - while True: - buf = sock.recv(1024**2) - if not buf: - break - unpacker.feed(buf) - for o in unpacker: - process(o) - - Raises ``ExtraData`` when *packed* contains extra bytes. - Raises ``OutOfData`` when *packed* is incomplete. - Raises ``FormatError`` when *packed* is not valid msgpack. - Raises ``StackError`` when *packed* contains too nested. - Other exceptions can be raised during unpacking. - """ - - def __init__( - self, - file_like=None, - read_size=0, - use_list=True, - raw=False, - timestamp=0, - strict_map_key=True, - object_hook=None, - object_pairs_hook=None, - list_hook=None, - unicode_errors=None, - max_buffer_size=100 * 1024 * 1024, - ext_hook=ExtType, - max_str_len=-1, - max_bin_len=-1, - max_array_len=-1, - max_map_len=-1, - max_ext_len=-1, - ): - if unicode_errors is None: - unicode_errors = "strict" - - if file_like is None: - self._feeding = True - else: - if not callable(file_like.read): - raise TypeError("`file_like.read` must be callable") - self.file_like = file_like - self._feeding = False - - #: array of bytes fed. - self._buffer = bytearray() - #: Which position we currently reads - self._buff_i = 0 - - # When Unpacker is used as an iterable, between the calls to next(), - # the buffer is not "consumed" completely, for efficiency sake. - # Instead, it is done sloppily. To make sure we raise BufferFull at - # the correct moments, we have to keep track of how sloppy we were. - # Furthermore, when the buffer is incomplete (that is: in the case - # we raise an OutOfData) we need to rollback the buffer to the correct - # state, which _buf_checkpoint records. - self._buf_checkpoint = 0 - - if not max_buffer_size: - max_buffer_size = 2**31 - 1 - if max_str_len == -1: - max_str_len = max_buffer_size - if max_bin_len == -1: - max_bin_len = max_buffer_size - if max_array_len == -1: - max_array_len = max_buffer_size - if max_map_len == -1: - max_map_len = max_buffer_size // 2 - if max_ext_len == -1: - max_ext_len = max_buffer_size - - self._max_buffer_size = max_buffer_size - if read_size > self._max_buffer_size: - raise ValueError("read_size must be smaller than max_buffer_size") - self._read_size = read_size or min(self._max_buffer_size, 16 * 1024) - self._raw = bool(raw) - self._strict_map_key = bool(strict_map_key) - self._unicode_errors = unicode_errors - self._use_list = use_list - if not (0 <= timestamp <= 3): - raise ValueError("timestamp must be 0..3") - self._timestamp = timestamp - self._list_hook = list_hook - self._object_hook = object_hook - self._object_pairs_hook = object_pairs_hook - self._ext_hook = ext_hook - self._max_str_len = max_str_len - self._max_bin_len = max_bin_len - self._max_array_len = max_array_len - self._max_map_len = max_map_len - self._max_ext_len = max_ext_len - self._stream_offset = 0 - - if list_hook is not None and not callable(list_hook): - raise TypeError("`list_hook` is not callable") - if object_hook is not None and not callable(object_hook): - raise TypeError("`object_hook` is not callable") - if object_pairs_hook is not None and not callable(object_pairs_hook): - raise TypeError("`object_pairs_hook` is not callable") - if object_hook is not None and object_pairs_hook is not None: - raise TypeError( - "object_pairs_hook and object_hook are mutually " "exclusive" - ) - if not callable(ext_hook): - raise TypeError("`ext_hook` is not callable") - - def feed(self, next_bytes): - assert self._feeding - view = _get_data_from_buffer(next_bytes) - if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size: - raise BufferFull - - # Strip buffer before checkpoint before reading file. - if self._buf_checkpoint > 0: - del self._buffer[: self._buf_checkpoint] - self._buff_i -= self._buf_checkpoint - self._buf_checkpoint = 0 - - # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython - self._buffer.extend(view) - - def _consume(self): - """Gets rid of the used parts of the buffer.""" - self._stream_offset += self._buff_i - self._buf_checkpoint - self._buf_checkpoint = self._buff_i - - def _got_extradata(self): - return self._buff_i < len(self._buffer) - - def _get_extradata(self): - return self._buffer[self._buff_i :] - - def read_bytes(self, n): - ret = self._read(n, raise_outofdata=False) - self._consume() - return ret - - def _read(self, n, raise_outofdata=True): - # (int) -> bytearray - self._reserve(n, raise_outofdata=raise_outofdata) - i = self._buff_i - ret = self._buffer[i : i + n] - self._buff_i = i + len(ret) - return ret - - def _reserve(self, n, raise_outofdata=True): - remain_bytes = len(self._buffer) - self._buff_i - n - - # Fast path: buffer has n bytes already - if remain_bytes >= 0: - return - - if self._feeding: - self._buff_i = self._buf_checkpoint - raise OutOfData - - # Strip buffer before checkpoint before reading file. - if self._buf_checkpoint > 0: - del self._buffer[: self._buf_checkpoint] - self._buff_i -= self._buf_checkpoint - self._buf_checkpoint = 0 - - # Read from file - remain_bytes = -remain_bytes - if remain_bytes + len(self._buffer) > self._max_buffer_size: - raise BufferFull - while remain_bytes > 0: - to_read_bytes = max(self._read_size, remain_bytes) - read_data = self.file_like.read(to_read_bytes) - if not read_data: - break - assert isinstance(read_data, bytes) - self._buffer += read_data - remain_bytes -= len(read_data) - - if len(self._buffer) < n + self._buff_i and raise_outofdata: - self._buff_i = 0 # rollback - raise OutOfData - - def _read_header(self): - typ = TYPE_IMMEDIATE - n = 0 - obj = None - self._reserve(1) - b = self._buffer[self._buff_i] - self._buff_i += 1 - if b & 0b10000000 == 0: - obj = b - elif b & 0b11100000 == 0b11100000: - obj = -1 - (b ^ 0xFF) - elif b & 0b11100000 == 0b10100000: - n = b & 0b00011111 - typ = TYPE_RAW - if n > self._max_str_len: - raise ValueError("%s exceeds max_str_len(%s)" % (n, self._max_str_len)) - obj = self._read(n) - elif b & 0b11110000 == 0b10010000: - n = b & 0b00001111 - typ = TYPE_ARRAY - if n > self._max_array_len: - raise ValueError( - "%s exceeds max_array_len(%s)" % (n, self._max_array_len) - ) - elif b & 0b11110000 == 0b10000000: - n = b & 0b00001111 - typ = TYPE_MAP - if n > self._max_map_len: - raise ValueError("%s exceeds max_map_len(%s)" % (n, self._max_map_len)) - elif b == 0xC0: - obj = None - elif b == 0xC2: - obj = False - elif b == 0xC3: - obj = True - elif 0xC4 <= b <= 0xC6: - size, fmt, typ = _MSGPACK_HEADERS[b] - self._reserve(size) - if len(fmt) > 0: - n = _unpack_from(fmt, self._buffer, self._buff_i)[0] - else: - n = self._buffer[self._buff_i] - self._buff_i += size - if n > self._max_bin_len: - raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len)) - obj = self._read(n) - elif 0xC7 <= b <= 0xC9: - size, fmt, typ = _MSGPACK_HEADERS[b] - self._reserve(size) - L, n = _unpack_from(fmt, self._buffer, self._buff_i) - self._buff_i += size - if L > self._max_ext_len: - raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len)) - obj = self._read(L) - elif 0xCA <= b <= 0xD3: - size, fmt = _MSGPACK_HEADERS[b] - self._reserve(size) - if len(fmt) > 0: - obj = _unpack_from(fmt, self._buffer, self._buff_i)[0] - else: - obj = self._buffer[self._buff_i] - self._buff_i += size - elif 0xD4 <= b <= 0xD8: - size, fmt, typ = _MSGPACK_HEADERS[b] - if self._max_ext_len < size: - raise ValueError( - "%s exceeds max_ext_len(%s)" % (size, self._max_ext_len) - ) - self._reserve(size + 1) - n, obj = _unpack_from(fmt, self._buffer, self._buff_i) - self._buff_i += size + 1 - elif 0xD9 <= b <= 0xDB: - size, fmt, typ = _MSGPACK_HEADERS[b] - self._reserve(size) - if len(fmt) > 0: - (n,) = _unpack_from(fmt, self._buffer, self._buff_i) - else: - n = self._buffer[self._buff_i] - self._buff_i += size - if n > self._max_str_len: - raise ValueError("%s exceeds max_str_len(%s)" % (n, self._max_str_len)) - obj = self._read(n) - elif 0xDC <= b <= 0xDD: - size, fmt, typ = _MSGPACK_HEADERS[b] - self._reserve(size) - (n,) = _unpack_from(fmt, self._buffer, self._buff_i) - self._buff_i += size - if n > self._max_array_len: - raise ValueError( - "%s exceeds max_array_len(%s)" % (n, self._max_array_len) - ) - elif 0xDE <= b <= 0xDF: - size, fmt, typ = _MSGPACK_HEADERS[b] - self._reserve(size) - (n,) = _unpack_from(fmt, self._buffer, self._buff_i) - self._buff_i += size - if n > self._max_map_len: - raise ValueError("%s exceeds max_map_len(%s)" % (n, self._max_map_len)) - else: - raise FormatError("Unknown header: 0x%x" % b) - return typ, n, obj - - def _unpack(self, execute=EX_CONSTRUCT): - typ, n, obj = self._read_header() - - if execute == EX_READ_ARRAY_HEADER: - if typ != TYPE_ARRAY: - raise ValueError("Expected array") - return n - if execute == EX_READ_MAP_HEADER: - if typ != TYPE_MAP: - raise ValueError("Expected map") - return n - # TODO should we eliminate the recursion? - if typ == TYPE_ARRAY: - if execute == EX_SKIP: - for i in xrange(n): - # TODO check whether we need to call `list_hook` - self._unpack(EX_SKIP) - return - ret = newlist_hint(n) - for i in xrange(n): - ret.append(self._unpack(EX_CONSTRUCT)) - if self._list_hook is not None: - ret = self._list_hook(ret) - # TODO is the interaction between `list_hook` and `use_list` ok? - return ret if self._use_list else tuple(ret) - if typ == TYPE_MAP: - if execute == EX_SKIP: - for i in xrange(n): - # TODO check whether we need to call hooks - self._unpack(EX_SKIP) - self._unpack(EX_SKIP) - return - if self._object_pairs_hook is not None: - ret = self._object_pairs_hook( - (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT)) - for _ in xrange(n) - ) - else: - ret = {} - for _ in xrange(n): - key = self._unpack(EX_CONSTRUCT) - if self._strict_map_key and type(key) not in (unicode, bytes): - raise ValueError( - "%s is not allowed for map key" % str(type(key)) - ) - if not PY2 and type(key) is str: - key = sys.intern(key) - ret[key] = self._unpack(EX_CONSTRUCT) - if self._object_hook is not None: - ret = self._object_hook(ret) - return ret - if execute == EX_SKIP: - return - if typ == TYPE_RAW: - if self._raw: - obj = bytes(obj) - else: - obj = obj.decode("utf_8", self._unicode_errors) - return obj - if typ == TYPE_BIN: - return bytes(obj) - if typ == TYPE_EXT: - if n == -1: # timestamp - ts = Timestamp.from_bytes(bytes(obj)) - if self._timestamp == 1: - return ts.to_unix() - elif self._timestamp == 2: - return ts.to_unix_nano() - elif self._timestamp == 3: - return ts.to_datetime() - else: - return ts - else: - return self._ext_hook(n, bytes(obj)) - assert typ == TYPE_IMMEDIATE - return obj - - def __iter__(self): - return self - - def __next__(self): - try: - ret = self._unpack(EX_CONSTRUCT) - self._consume() - return ret - except OutOfData: - self._consume() - raise StopIteration - except RecursionError: - raise StackError - - next = __next__ - - def skip(self): - self._unpack(EX_SKIP) - self._consume() - - def unpack(self): - try: - ret = self._unpack(EX_CONSTRUCT) - except RecursionError: - raise StackError - self._consume() - return ret - - def read_array_header(self): - ret = self._unpack(EX_READ_ARRAY_HEADER) - self._consume() - return ret - - def read_map_header(self): - ret = self._unpack(EX_READ_MAP_HEADER) - self._consume() - return ret - - def tell(self): - return self._stream_offset - - -class Packer(object): - """ - MessagePack Packer - - Usage:: - - packer = Packer() - astream.write(packer.pack(a)) - astream.write(packer.pack(b)) - - Packer's constructor has some keyword arguments: - - :param callable default: - Convert user type to builtin type that Packer supports. - See also simplejson's document. - - :param bool use_single_float: - Use single precision float type for float. (default: False) - - :param bool autoreset: - Reset buffer after each pack and return its content as `bytes`. (default: True). - If set this to false, use `bytes()` to get content and `.reset()` to clear buffer. - - :param bool use_bin_type: - Use bin type introduced in msgpack spec 2.0 for bytes. - It also enables str8 type for unicode. (default: True) - - :param bool strict_types: - If set to true, types will be checked to be exact. Derived classes - from serializable types will not be serialized and will be - treated as unsupported type and forwarded to default. - Additionally tuples will not be serialized as lists. - This is useful when trying to implement accurate serialization - for python types. - - :param bool datetime: - If set to true, datetime with tzinfo is packed into Timestamp type. - Note that the tzinfo is stripped in the timestamp. - You can get UTC datetime with `timestamp=3` option of the Unpacker. - (Python 2 is not supported). - - :param str unicode_errors: - The error handler for encoding unicode. (default: 'strict') - DO NOT USE THIS!! This option is kept for very specific usage. - - Example of streaming deserialize from file-like object:: - - unpacker = Unpacker(file_like) - for o in unpacker: - process(o) - - Example of streaming deserialize from socket:: - - unpacker = Unpacker() - while True: - buf = sock.recv(1024**2) - if not buf: - break - unpacker.feed(buf) - for o in unpacker: - process(o) - - Raises ``ExtraData`` when *packed* contains extra bytes. - Raises ``OutOfData`` when *packed* is incomplete. - Raises ``FormatError`` when *packed* is not valid msgpack. - Raises ``StackError`` when *packed* contains too nested. - Other exceptions can be raised during unpacking. - """ - - def __init__( - self, - default=None, - use_single_float=False, - autoreset=True, - use_bin_type=True, - strict_types=False, - datetime=False, - unicode_errors=None, - ): - self._strict_types = strict_types - self._use_float = use_single_float - self._autoreset = autoreset - self._use_bin_type = use_bin_type - self._buffer = StringIO() - if PY2 and datetime: - raise ValueError("datetime is not supported in Python 2") - self._datetime = bool(datetime) - self._unicode_errors = unicode_errors or "strict" - if default is not None: - if not callable(default): - raise TypeError("default must be callable") - self._default = default - - def _pack( - self, - obj, - nest_limit=DEFAULT_RECURSE_LIMIT, - check=isinstance, - check_type_strict=_check_type_strict, - ): - default_used = False - if self._strict_types: - check = check_type_strict - list_types = list - else: - list_types = (list, tuple) - while True: - if nest_limit < 0: - raise ValueError("recursion limit exceeded") - if obj is None: - return self._buffer.write(b"\xc0") - if check(obj, bool): - if obj: - return self._buffer.write(b"\xc3") - return self._buffer.write(b"\xc2") - if check(obj, int_types): - if 0 <= obj < 0x80: - return self._buffer.write(struct.pack("B", obj)) - if -0x20 <= obj < 0: - return self._buffer.write(struct.pack("b", obj)) - if 0x80 <= obj <= 0xFF: - return self._buffer.write(struct.pack("BB", 0xCC, obj)) - if -0x80 <= obj < 0: - return self._buffer.write(struct.pack(">Bb", 0xD0, obj)) - if 0xFF < obj <= 0xFFFF: - return self._buffer.write(struct.pack(">BH", 0xCD, obj)) - if -0x8000 <= obj < -0x80: - return self._buffer.write(struct.pack(">Bh", 0xD1, obj)) - if 0xFFFF < obj <= 0xFFFFFFFF: - return self._buffer.write(struct.pack(">BI", 0xCE, obj)) - if -0x80000000 <= obj < -0x8000: - return self._buffer.write(struct.pack(">Bi", 0xD2, obj)) - if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF: - return self._buffer.write(struct.pack(">BQ", 0xCF, obj)) - if -0x8000000000000000 <= obj < -0x80000000: - return self._buffer.write(struct.pack(">Bq", 0xD3, obj)) - if not default_used and self._default is not None: - obj = self._default(obj) - default_used = True - continue - raise OverflowError("Integer value out of range") - if check(obj, (bytes, bytearray)): - n = len(obj) - if n >= 2**32: - raise ValueError("%s is too large" % type(obj).__name__) - self._pack_bin_header(n) - return self._buffer.write(obj) - if check(obj, unicode): - obj = obj.encode("utf-8", self._unicode_errors) - n = len(obj) - if n >= 2**32: - raise ValueError("String is too large") - self._pack_raw_header(n) - return self._buffer.write(obj) - if check(obj, memoryview): - n = obj.nbytes - if n >= 2**32: - raise ValueError("Memoryview is too large") - self._pack_bin_header(n) - return self._buffer.write(obj) - if check(obj, float): - if self._use_float: - return self._buffer.write(struct.pack(">Bf", 0xCA, obj)) - return self._buffer.write(struct.pack(">Bd", 0xCB, obj)) - if check(obj, (ExtType, Timestamp)): - if check(obj, Timestamp): - code = -1 - data = obj.to_bytes() - else: - code = obj.code - data = obj.data - assert isinstance(code, int) - assert isinstance(data, bytes) - L = len(data) - if L == 1: - self._buffer.write(b"\xd4") - elif L == 2: - self._buffer.write(b"\xd5") - elif L == 4: - self._buffer.write(b"\xd6") - elif L == 8: - self._buffer.write(b"\xd7") - elif L == 16: - self._buffer.write(b"\xd8") - elif L <= 0xFF: - self._buffer.write(struct.pack(">BB", 0xC7, L)) - elif L <= 0xFFFF: - self._buffer.write(struct.pack(">BH", 0xC8, L)) - else: - self._buffer.write(struct.pack(">BI", 0xC9, L)) - self._buffer.write(struct.pack("b", code)) - self._buffer.write(data) - return - if check(obj, list_types): - n = len(obj) - self._pack_array_header(n) - for i in xrange(n): - self._pack(obj[i], nest_limit - 1) - return - if check(obj, dict): - return self._pack_map_pairs( - len(obj), dict_iteritems(obj), nest_limit - 1 - ) - - if self._datetime and check(obj, _DateTime) and obj.tzinfo is not None: - obj = Timestamp.from_datetime(obj) - default_used = 1 - continue - - if not default_used and self._default is not None: - obj = self._default(obj) - default_used = 1 - continue - - if self._datetime and check(obj, _DateTime): - raise ValueError("Cannot serialize %r where tzinfo=None" % (obj,)) - - raise TypeError("Cannot serialize %r" % (obj,)) - - def pack(self, obj): - try: - self._pack(obj) - except: - self._buffer = StringIO() # force reset - raise - if self._autoreset: - ret = self._buffer.getvalue() - self._buffer = StringIO() - return ret - - def pack_map_pairs(self, pairs): - self._pack_map_pairs(len(pairs), pairs) - if self._autoreset: - ret = self._buffer.getvalue() - self._buffer = StringIO() - return ret - - def pack_array_header(self, n): - if n >= 2**32: - raise ValueError - self._pack_array_header(n) - if self._autoreset: - ret = self._buffer.getvalue() - self._buffer = StringIO() - return ret - - def pack_map_header(self, n): - if n >= 2**32: - raise ValueError - self._pack_map_header(n) - if self._autoreset: - ret = self._buffer.getvalue() - self._buffer = StringIO() - return ret - - def pack_ext_type(self, typecode, data): - if not isinstance(typecode, int): - raise TypeError("typecode must have int type.") - if not 0 <= typecode <= 127: - raise ValueError("typecode should be 0-127") - if not isinstance(data, bytes): - raise TypeError("data must have bytes type") - L = len(data) - if L > 0xFFFFFFFF: - raise ValueError("Too large data") - if L == 1: - self._buffer.write(b"\xd4") - elif L == 2: - self._buffer.write(b"\xd5") - elif L == 4: - self._buffer.write(b"\xd6") - elif L == 8: - self._buffer.write(b"\xd7") - elif L == 16: - self._buffer.write(b"\xd8") - elif L <= 0xFF: - self._buffer.write(b"\xc7" + struct.pack("B", L)) - elif L <= 0xFFFF: - self._buffer.write(b"\xc8" + struct.pack(">H", L)) - else: - self._buffer.write(b"\xc9" + struct.pack(">I", L)) - self._buffer.write(struct.pack("B", typecode)) - self._buffer.write(data) - - def _pack_array_header(self, n): - if n <= 0x0F: - return self._buffer.write(struct.pack("B", 0x90 + n)) - if n <= 0xFFFF: - return self._buffer.write(struct.pack(">BH", 0xDC, n)) - if n <= 0xFFFFFFFF: - return self._buffer.write(struct.pack(">BI", 0xDD, n)) - raise ValueError("Array is too large") - - def _pack_map_header(self, n): - if n <= 0x0F: - return self._buffer.write(struct.pack("B", 0x80 + n)) - if n <= 0xFFFF: - return self._buffer.write(struct.pack(">BH", 0xDE, n)) - if n <= 0xFFFFFFFF: - return self._buffer.write(struct.pack(">BI", 0xDF, n)) - raise ValueError("Dict is too large") - - def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT): - self._pack_map_header(n) - for (k, v) in pairs: - self._pack(k, nest_limit - 1) - self._pack(v, nest_limit - 1) - - def _pack_raw_header(self, n): - if n <= 0x1F: - self._buffer.write(struct.pack("B", 0xA0 + n)) - elif self._use_bin_type and n <= 0xFF: - self._buffer.write(struct.pack(">BB", 0xD9, n)) - elif n <= 0xFFFF: - self._buffer.write(struct.pack(">BH", 0xDA, n)) - elif n <= 0xFFFFFFFF: - self._buffer.write(struct.pack(">BI", 0xDB, n)) - else: - raise ValueError("Raw is too large") - - def _pack_bin_header(self, n): - if not self._use_bin_type: - return self._pack_raw_header(n) - elif n <= 0xFF: - return self._buffer.write(struct.pack(">BB", 0xC4, n)) - elif n <= 0xFFFF: - return self._buffer.write(struct.pack(">BH", 0xC5, n)) - elif n <= 0xFFFFFFFF: - return self._buffer.write(struct.pack(">BI", 0xC6, n)) - else: - raise ValueError("Bin is too large") - - def bytes(self): - """Return internal buffer contents as bytes object""" - return self._buffer.getvalue() - - def reset(self): - """Reset internal buffer. - - This method is useful only when autoreset=False. - """ - self._buffer = StringIO() - - def getbuffer(self): - """Return view of internal buffer.""" - if USING_STRINGBUILDER or PY2: - return memoryview(self.bytes()) - else: - return self._buffer.getbuffer() diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/__init__.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/__init__.py deleted file mode 100644 index a4776248038b04305b116015b9a4edf0fa98c617..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/requests/__init__.py +++ /dev/null @@ -1,182 +0,0 @@ -# __ -# /__) _ _ _ _ _/ _ -# / ( (- (/ (/ (- _) / _) -# / - -""" -Requests HTTP Library -~~~~~~~~~~~~~~~~~~~~~ - -Requests is an HTTP library, written in Python, for human beings. -Basic GET usage: - - >>> import requests - >>> r = requests.get('https://www.python.org') - >>> r.status_code - 200 - >>> b'Python is a programming language' in r.content - True - -... or POST: - - >>> payload = dict(key1='value1', key2='value2') - >>> r = requests.post('https://httpbin.org/post', data=payload) - >>> print(r.text) - { - ... - "form": { - "key1": "value1", - "key2": "value2" - }, - ... - } - -The other HTTP methods are supported - see `requests.api`. Full documentation -is at . - -:copyright: (c) 2017 by Kenneth Reitz. -:license: Apache 2.0, see LICENSE for more details. -""" - -import warnings - -from pip._vendor import urllib3 - -from .exceptions import RequestsDependencyWarning - -charset_normalizer_version = None - -try: - from pip._vendor.chardet import __version__ as chardet_version -except ImportError: - chardet_version = None - - -def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version): - urllib3_version = urllib3_version.split(".") - assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git. - - # Sometimes, urllib3 only reports its version as 16.1. - if len(urllib3_version) == 2: - urllib3_version.append("0") - - # Check urllib3 for compatibility. - major, minor, patch = urllib3_version # noqa: F811 - major, minor, patch = int(major), int(minor), int(patch) - # urllib3 >= 1.21.1, <= 1.26 - assert major == 1 - assert minor >= 21 - assert minor <= 26 - - # Check charset_normalizer for compatibility. - if chardet_version: - major, minor, patch = chardet_version.split(".")[:3] - major, minor, patch = int(major), int(minor), int(patch) - # chardet_version >= 3.0.2, < 6.0.0 - assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0) - elif charset_normalizer_version: - major, minor, patch = charset_normalizer_version.split(".")[:3] - major, minor, patch = int(major), int(minor), int(patch) - # charset_normalizer >= 2.0.0 < 4.0.0 - assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0) - else: - raise Exception("You need either charset_normalizer or chardet installed") - - -def _check_cryptography(cryptography_version): - # cryptography < 1.3.4 - try: - cryptography_version = list(map(int, cryptography_version.split("."))) - except ValueError: - return - - if cryptography_version < [1, 3, 4]: - warning = "Old version of cryptography ({}) may cause slowdown.".format( - cryptography_version - ) - warnings.warn(warning, RequestsDependencyWarning) - - -# Check imported dependencies for compatibility. -try: - check_compatibility( - urllib3.__version__, chardet_version, charset_normalizer_version - ) -except (AssertionError, ValueError): - warnings.warn( - "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " - "version!".format( - urllib3.__version__, chardet_version, charset_normalizer_version - ), - RequestsDependencyWarning, - ) - -# Attempt to enable urllib3's fallback for SNI support -# if the standard library doesn't support SNI or the -# 'ssl' library isn't available. -try: - # Note: This logic prevents upgrading cryptography on Windows, if imported - # as part of pip. - from pip._internal.utils.compat import WINDOWS - if not WINDOWS: - raise ImportError("pip internals: don't import cryptography on Windows") - try: - import ssl - except ImportError: - ssl = None - - if not getattr(ssl, "HAS_SNI", False): - from pip._vendor.urllib3.contrib import pyopenssl - - pyopenssl.inject_into_urllib3() - - # Check cryptography version - from cryptography import __version__ as cryptography_version - - _check_cryptography(cryptography_version) -except ImportError: - pass - -# urllib3's DependencyWarnings should be silenced. -from pip._vendor.urllib3.exceptions import DependencyWarning - -warnings.simplefilter("ignore", DependencyWarning) - -# Set default logging handler to avoid "No handler found" warnings. -import logging -from logging import NullHandler - -from . import packages, utils -from .__version__ import ( - __author__, - __author_email__, - __build__, - __cake__, - __copyright__, - __description__, - __license__, - __title__, - __url__, - __version__, -) -from .api import delete, get, head, options, patch, post, put, request -from .exceptions import ( - ConnectionError, - ConnectTimeout, - FileModeWarning, - HTTPError, - JSONDecodeError, - ReadTimeout, - RequestException, - Timeout, - TooManyRedirects, - URLRequired, -) -from .models import PreparedRequest, Request, Response -from .sessions import Session, session -from .status_codes import codes - -logging.getLogger(__name__).addHandler(NullHandler()) - -# FileModeWarnings go off per the default. -warnings.simplefilter("default", FileModeWarning, append=True) diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/pyparsing/diagram/__init__.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/pyparsing/diagram/__init__.py deleted file mode 100644 index 898644755cbbf9a8d4df562663114a7eb7e11fd1..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/pyparsing/diagram/__init__.py +++ /dev/null @@ -1,642 +0,0 @@ -import railroad -import pyparsing -import typing -from typing import ( - List, - NamedTuple, - Generic, - TypeVar, - Dict, - Callable, - Set, - Iterable, -) -from jinja2 import Template -from io import StringIO -import inspect - - -jinja2_template_source = """\ - - - - {% if not head %} - - {% else %} - {{ head | safe }} - {% endif %} - - -{{ body | safe }} -{% for diagram in diagrams %} -
-

{{ diagram.title }}

-
{{ diagram.text }}
-
- {{ diagram.svg }} -
-
-{% endfor %} - - -""" - -template = Template(jinja2_template_source) - -# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet -NamedDiagram = NamedTuple( - "NamedDiagram", - [("name", str), ("diagram", typing.Optional[railroad.DiagramItem]), ("index", int)], -) -""" -A simple structure for associating a name with a railroad diagram -""" - -T = TypeVar("T") - - -class EachItem(railroad.Group): - """ - Custom railroad item to compose a: - - Group containing a - - OneOrMore containing a - - Choice of the elements in the Each - with the group label indicating that all must be matched - """ - - all_label = "[ALL]" - - def __init__(self, *items): - choice_item = railroad.Choice(len(items) - 1, *items) - one_or_more_item = railroad.OneOrMore(item=choice_item) - super().__init__(one_or_more_item, label=self.all_label) - - -class AnnotatedItem(railroad.Group): - """ - Simple subclass of Group that creates an annotation label - """ - - def __init__(self, label: str, item): - super().__init__(item=item, label="[{}]".format(label) if label else label) - - -class EditablePartial(Generic[T]): - """ - Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been - constructed. - """ - - # We need this here because the railroad constructors actually transform the data, so can't be called until the - # entire tree is assembled - - def __init__(self, func: Callable[..., T], args: list, kwargs: dict): - self.func = func - self.args = args - self.kwargs = kwargs - - @classmethod - def from_call(cls, func: Callable[..., T], *args, **kwargs) -> "EditablePartial[T]": - """ - If you call this function in the same way that you would call the constructor, it will store the arguments - as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3) - """ - return EditablePartial(func=func, args=list(args), kwargs=kwargs) - - @property - def name(self): - return self.kwargs["name"] - - def __call__(self) -> T: - """ - Evaluate the partial and return the result - """ - args = self.args.copy() - kwargs = self.kwargs.copy() - - # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g. - # args=['list', 'of', 'things']) - arg_spec = inspect.getfullargspec(self.func) - if arg_spec.varargs in self.kwargs: - args += kwargs.pop(arg_spec.varargs) - - return self.func(*args, **kwargs) - - -def railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str: - """ - Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams - :params kwargs: kwargs to be passed in to the template - """ - data = [] - for diagram in diagrams: - if diagram.diagram is None: - continue - io = StringIO() - diagram.diagram.writeSvg(io.write) - title = diagram.name - if diagram.index == 0: - title += " (root)" - data.append({"title": title, "text": "", "svg": io.getvalue()}) - - return template.render(diagrams=data, **kwargs) - - -def resolve_partial(partial: "EditablePartial[T]") -> T: - """ - Recursively resolves a collection of Partials into whatever type they are - """ - if isinstance(partial, EditablePartial): - partial.args = resolve_partial(partial.args) - partial.kwargs = resolve_partial(partial.kwargs) - return partial() - elif isinstance(partial, list): - return [resolve_partial(x) for x in partial] - elif isinstance(partial, dict): - return {key: resolve_partial(x) for key, x in partial.items()} - else: - return partial - - -def to_railroad( - element: pyparsing.ParserElement, - diagram_kwargs: typing.Optional[dict] = None, - vertical: int = 3, - show_results_names: bool = False, - show_groups: bool = False, -) -> List[NamedDiagram]: - """ - Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram - creation if you want to access the Railroad tree before it is converted to HTML - :param element: base element of the parser being diagrammed - :param diagram_kwargs: kwargs to pass to the Diagram() constructor - :param vertical: (optional) - int - limit at which number of alternatives should be - shown vertically instead of horizontally - :param show_results_names - bool to indicate whether results name annotations should be - included in the diagram - :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled - surrounding box - """ - # Convert the whole tree underneath the root - lookup = ConverterState(diagram_kwargs=diagram_kwargs or {}) - _to_diagram_element( - element, - lookup=lookup, - parent=None, - vertical=vertical, - show_results_names=show_results_names, - show_groups=show_groups, - ) - - root_id = id(element) - # Convert the root if it hasn't been already - if root_id in lookup: - if not element.customName: - lookup[root_id].name = "" - lookup[root_id].mark_for_extraction(root_id, lookup, force=True) - - # Now that we're finished, we can convert from intermediate structures into Railroad elements - diags = list(lookup.diagrams.values()) - if len(diags) > 1: - # collapse out duplicate diags with the same name - seen = set() - deduped_diags = [] - for d in diags: - # don't extract SkipTo elements, they are uninformative as subdiagrams - if d.name == "...": - continue - if d.name is not None and d.name not in seen: - seen.add(d.name) - deduped_diags.append(d) - resolved = [resolve_partial(partial) for partial in deduped_diags] - else: - # special case - if just one diagram, always display it, even if - # it has no name - resolved = [resolve_partial(partial) for partial in diags] - return sorted(resolved, key=lambda diag: diag.index) - - -def _should_vertical( - specification: int, exprs: Iterable[pyparsing.ParserElement] -) -> bool: - """ - Returns true if we should return a vertical list of elements - """ - if specification is None: - return False - else: - return len(_visible_exprs(exprs)) >= specification - - -class ElementState: - """ - State recorded for an individual pyparsing Element - """ - - # Note: this should be a dataclass, but we have to support Python 3.5 - def __init__( - self, - element: pyparsing.ParserElement, - converted: EditablePartial, - parent: EditablePartial, - number: int, - name: str = None, - parent_index: typing.Optional[int] = None, - ): - #: The pyparsing element that this represents - self.element: pyparsing.ParserElement = element - #: The name of the element - self.name: typing.Optional[str] = name - #: The output Railroad element in an unconverted state - self.converted: EditablePartial = converted - #: The parent Railroad element, which we store so that we can extract this if it's duplicated - self.parent: EditablePartial = parent - #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram - self.number: int = number - #: The index of this inside its parent - self.parent_index: typing.Optional[int] = parent_index - #: If true, we should extract this out into a subdiagram - self.extract: bool = False - #: If true, all of this element's children have been filled out - self.complete: bool = False - - def mark_for_extraction( - self, el_id: int, state: "ConverterState", name: str = None, force: bool = False - ): - """ - Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram - :param el_id: id of the element - :param state: element/diagram state tracker - :param name: name to use for this element's text - :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the - root element when we know we're finished - """ - self.extract = True - - # Set the name - if not self.name: - if name: - # Allow forcing a custom name - self.name = name - elif self.element.customName: - self.name = self.element.customName - else: - self.name = "" - - # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children - # to be added - # Also, if this is just a string literal etc, don't bother extracting it - if force or (self.complete and _worth_extracting(self.element)): - state.extract_into_diagram(el_id) - - -class ConverterState: - """ - Stores some state that persists between recursions into the element tree - """ - - def __init__(self, diagram_kwargs: typing.Optional[dict] = None): - #: A dictionary mapping ParserElements to state relating to them - self._element_diagram_states: Dict[int, ElementState] = {} - #: A dictionary mapping ParserElement IDs to subdiagrams generated from them - self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {} - #: The index of the next unnamed element - self.unnamed_index: int = 1 - #: The index of the next element. This is used for sorting - self.index: int = 0 - #: Shared kwargs that are used to customize the construction of diagrams - self.diagram_kwargs: dict = diagram_kwargs or {} - self.extracted_diagram_names: Set[str] = set() - - def __setitem__(self, key: int, value: ElementState): - self._element_diagram_states[key] = value - - def __getitem__(self, key: int) -> ElementState: - return self._element_diagram_states[key] - - def __delitem__(self, key: int): - del self._element_diagram_states[key] - - def __contains__(self, key: int): - return key in self._element_diagram_states - - def generate_unnamed(self) -> int: - """ - Generate a number used in the name of an otherwise unnamed diagram - """ - self.unnamed_index += 1 - return self.unnamed_index - - def generate_index(self) -> int: - """ - Generate a number used to index a diagram - """ - self.index += 1 - return self.index - - def extract_into_diagram(self, el_id: int): - """ - Used when we encounter the same token twice in the same tree. When this - happens, we replace all instances of that token with a terminal, and - create a new subdiagram for the token - """ - position = self[el_id] - - # Replace the original definition of this element with a regular block - if position.parent: - ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name) - if "item" in position.parent.kwargs: - position.parent.kwargs["item"] = ret - elif "items" in position.parent.kwargs: - position.parent.kwargs["items"][position.parent_index] = ret - - # If the element we're extracting is a group, skip to its content but keep the title - if position.converted.func == railroad.Group: - content = position.converted.kwargs["item"] - else: - content = position.converted - - self.diagrams[el_id] = EditablePartial.from_call( - NamedDiagram, - name=position.name, - diagram=EditablePartial.from_call( - railroad.Diagram, content, **self.diagram_kwargs - ), - index=position.number, - ) - - del self[el_id] - - -def _worth_extracting(element: pyparsing.ParserElement) -> bool: - """ - Returns true if this element is worth having its own sub-diagram. Simply, if any of its children - themselves have children, then its complex enough to extract - """ - children = element.recurse() - return any(child.recurse() for child in children) - - -def _apply_diagram_item_enhancements(fn): - """ - decorator to ensure enhancements to a diagram item (such as results name annotations) - get applied on return from _to_diagram_element (we do this since there are several - returns in _to_diagram_element) - """ - - def _inner( - element: pyparsing.ParserElement, - parent: typing.Optional[EditablePartial], - lookup: ConverterState = None, - vertical: int = None, - index: int = 0, - name_hint: str = None, - show_results_names: bool = False, - show_groups: bool = False, - ) -> typing.Optional[EditablePartial]: - - ret = fn( - element, - parent, - lookup, - vertical, - index, - name_hint, - show_results_names, - show_groups, - ) - - # apply annotation for results name, if present - if show_results_names and ret is not None: - element_results_name = element.resultsName - if element_results_name: - # add "*" to indicate if this is a "list all results" name - element_results_name += "" if element.modalResults else "*" - ret = EditablePartial.from_call( - railroad.Group, item=ret, label=element_results_name - ) - - return ret - - return _inner - - -def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]): - non_diagramming_exprs = ( - pyparsing.ParseElementEnhance, - pyparsing.PositionToken, - pyparsing.And._ErrorStop, - ) - return [ - e - for e in exprs - if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs)) - ] - - -@_apply_diagram_item_enhancements -def _to_diagram_element( - element: pyparsing.ParserElement, - parent: typing.Optional[EditablePartial], - lookup: ConverterState = None, - vertical: int = None, - index: int = 0, - name_hint: str = None, - show_results_names: bool = False, - show_groups: bool = False, -) -> typing.Optional[EditablePartial]: - """ - Recursively converts a PyParsing Element to a railroad Element - :param lookup: The shared converter state that keeps track of useful things - :param index: The index of this element within the parent - :param parent: The parent of this element in the output tree - :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default), - it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never - do so - :param name_hint: If provided, this will override the generated name - :param show_results_names: bool flag indicating whether to add annotations for results names - :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed - :param show_groups: bool flag indicating whether to show groups using bounding box - """ - exprs = element.recurse() - name = name_hint or element.customName or element.__class__.__name__ - - # Python's id() is used to provide a unique identifier for elements - el_id = id(element) - - element_results_name = element.resultsName - - # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram - if not element.customName: - if isinstance( - element, - ( - # pyparsing.TokenConverter, - # pyparsing.Forward, - pyparsing.Located, - ), - ): - # However, if this element has a useful custom name, and its child does not, we can pass it on to the child - if exprs: - if not exprs[0].customName: - propagated_name = name - else: - propagated_name = None - - return _to_diagram_element( - element.expr, - parent=parent, - lookup=lookup, - vertical=vertical, - index=index, - name_hint=propagated_name, - show_results_names=show_results_names, - show_groups=show_groups, - ) - - # If the element isn't worth extracting, we always treat it as the first time we say it - if _worth_extracting(element): - if el_id in lookup: - # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate, - # so we have to extract it into a new diagram. - looked_up = lookup[el_id] - looked_up.mark_for_extraction(el_id, lookup, name=name_hint) - ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name) - return ret - - elif el_id in lookup.diagrams: - # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we - # just put in a marker element that refers to the sub-diagram - ret = EditablePartial.from_call( - railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"] - ) - return ret - - # Recursively convert child elements - # Here we find the most relevant Railroad element for matching pyparsing Element - # We use ``items=[]`` here to hold the place for where the child elements will go once created - if isinstance(element, pyparsing.And): - # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat - # (all will have the same name, and resultsName) - if not exprs: - return None - if len(set((e.name, e.resultsName) for e in exprs)) == 1: - ret = EditablePartial.from_call( - railroad.OneOrMore, item="", repeat=str(len(exprs)) - ) - elif _should_vertical(vertical, exprs): - ret = EditablePartial.from_call(railroad.Stack, items=[]) - else: - ret = EditablePartial.from_call(railroad.Sequence, items=[]) - elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)): - if not exprs: - return None - if _should_vertical(vertical, exprs): - ret = EditablePartial.from_call(railroad.Choice, 0, items=[]) - else: - ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[]) - elif isinstance(element, pyparsing.Each): - if not exprs: - return None - ret = EditablePartial.from_call(EachItem, items=[]) - elif isinstance(element, pyparsing.NotAny): - ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="") - elif isinstance(element, pyparsing.FollowedBy): - ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="") - elif isinstance(element, pyparsing.PrecededBy): - ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="") - elif isinstance(element, pyparsing.Group): - if show_groups: - ret = EditablePartial.from_call(AnnotatedItem, label="", item="") - else: - ret = EditablePartial.from_call(railroad.Group, label="", item="") - elif isinstance(element, pyparsing.TokenConverter): - ret = EditablePartial.from_call( - AnnotatedItem, label=type(element).__name__.lower(), item="" - ) - elif isinstance(element, pyparsing.Opt): - ret = EditablePartial.from_call(railroad.Optional, item="") - elif isinstance(element, pyparsing.OneOrMore): - ret = EditablePartial.from_call(railroad.OneOrMore, item="") - elif isinstance(element, pyparsing.ZeroOrMore): - ret = EditablePartial.from_call(railroad.ZeroOrMore, item="") - elif isinstance(element, pyparsing.Group): - ret = EditablePartial.from_call( - railroad.Group, item=None, label=element_results_name - ) - elif isinstance(element, pyparsing.Empty) and not element.customName: - # Skip unnamed "Empty" elements - ret = None - elif len(exprs) > 1: - ret = EditablePartial.from_call(railroad.Sequence, items=[]) - elif len(exprs) > 0 and not element_results_name: - ret = EditablePartial.from_call(railroad.Group, item="", label=name) - else: - terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName) - ret = terminal - - if ret is None: - return - - # Indicate this element's position in the tree so we can extract it if necessary - lookup[el_id] = ElementState( - element=element, - converted=ret, - parent=parent, - parent_index=index, - number=lookup.generate_index(), - ) - if element.customName: - lookup[el_id].mark_for_extraction(el_id, lookup, element.customName) - - i = 0 - for expr in exprs: - # Add a placeholder index in case we have to extract the child before we even add it to the parent - if "items" in ret.kwargs: - ret.kwargs["items"].insert(i, None) - - item = _to_diagram_element( - expr, - parent=ret, - lookup=lookup, - vertical=vertical, - index=i, - show_results_names=show_results_names, - show_groups=show_groups, - ) - - # Some elements don't need to be shown in the diagram - if item is not None: - if "item" in ret.kwargs: - ret.kwargs["item"] = item - elif "items" in ret.kwargs: - # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal - ret.kwargs["items"][i] = item - i += 1 - elif "items" in ret.kwargs: - # If we're supposed to skip this element, remove it from the parent - del ret.kwargs["items"][i] - - # If all this items children are none, skip this item - if ret and ( - ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0) - or ("item" in ret.kwargs and ret.kwargs["item"] is None) - ): - ret = EditablePartial.from_call(railroad.Terminal, name) - - # Mark this element as "complete", ie it has all of its children - if el_id in lookup: - lookup[el_id].complete = True - - if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete: - lookup.extract_into_diagram(el_id) - if ret is not None: - ret = EditablePartial.from_call( - railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"] - ) - - return ret diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/config/_validate_pyproject/__init__.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/config/_validate_pyproject/__init__.py deleted file mode 100644 index dbe6cb4ca471f146b431d2fbb558d47317a103f0..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/config/_validate_pyproject/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -from functools import reduce -from typing import Any, Callable, Dict - -from . import formats -from .error_reporting import detailed_errors, ValidationError -from .extra_validations import EXTRA_VALIDATIONS -from .fastjsonschema_exceptions import JsonSchemaException, JsonSchemaValueException -from .fastjsonschema_validations import validate as _validate - -__all__ = [ - "validate", - "FORMAT_FUNCTIONS", - "EXTRA_VALIDATIONS", - "ValidationError", - "JsonSchemaException", - "JsonSchemaValueException", -] - - -FORMAT_FUNCTIONS: Dict[str, Callable[[str], bool]] = { - fn.__name__.replace("_", "-"): fn - for fn in formats.__dict__.values() - if callable(fn) and not fn.__name__.startswith("_") -} - - -def validate(data: Any) -> bool: - """Validate the given ``data`` object using JSON Schema - This function raises ``ValidationError`` if ``data`` is invalid. - """ - with detailed_errors(): - _validate(data, custom_formats=FORMAT_FUNCTIONS) - reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data) - return True diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/export/api.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/export/api.py deleted file mode 100644 index ad4272183f2a533dbb68f6e65cf42144f4b69fc4..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/export/api.py +++ /dev/null @@ -1,235 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import copy -import logging -import os -import torch -from caffe2.proto import caffe2_pb2 -from torch import nn - -from detectron2.config import CfgNode -from detectron2.utils.file_io import PathManager - -from .caffe2_inference import ProtobufDetectionModel -from .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_batched_inputs_to_c2_format -from .shared import get_pb_arg_vali, get_pb_arg_vals, save_graph - -__all__ = [ - "add_export_config", - "Caffe2Model", - "Caffe2Tracer", -] - - -def add_export_config(cfg): - return cfg - - -class Caffe2Tracer: - """ - Make a detectron2 model traceable with Caffe2 operators. - This class creates a traceable version of a detectron2 model which: - - 1. Rewrite parts of the model using ops in Caffe2. Note that some ops do - not have GPU implementation in Caffe2. - 2. Remove post-processing and only produce raw layer outputs - - After making a traceable model, the class provide methods to export such a - model to different deployment formats. - Exported graph produced by this class take two input tensors: - - 1. (1, C, H, W) float "data" which is an image (usually in [0, 255]). - (H, W) often has to be padded to multiple of 32 (depend on the model - architecture). - 2. 1x3 float "im_info", each row of which is (height, width, 1.0). - Height and width are true image shapes before padding. - - The class currently only supports models using builtin meta architectures. - Batch inference is not supported, and contributions are welcome. - """ - - def __init__(self, cfg: CfgNode, model: nn.Module, inputs): - """ - Args: - cfg (CfgNode): a detectron2 config used to construct caffe2-compatible model. - model (nn.Module): An original pytorch model. Must be among a few official models - in detectron2 that can be converted to become caffe2-compatible automatically. - Weights have to be already loaded to this model. - inputs: sample inputs that the given model takes for inference. - Will be used to trace the model. For most models, random inputs with - no detected objects will not work as they lead to wrong traces. - """ - assert isinstance(cfg, CfgNode), cfg - assert isinstance(model, torch.nn.Module), type(model) - - # TODO make it support custom models, by passing in c2 model directly - C2MetaArch = META_ARCH_CAFFE2_EXPORT_TYPE_MAP[cfg.MODEL.META_ARCHITECTURE] - self.traceable_model = C2MetaArch(cfg, copy.deepcopy(model)) - self.inputs = inputs - self.traceable_inputs = self.traceable_model.get_caffe2_inputs(inputs) - - def export_caffe2(self): - """ - Export the model to Caffe2's protobuf format. - The returned object can be saved with its :meth:`.save_protobuf()` method. - The result can be loaded and executed using Caffe2 runtime. - - Returns: - :class:`Caffe2Model` - """ - from .caffe2_export import export_caffe2_detection_model - - predict_net, init_net = export_caffe2_detection_model( - self.traceable_model, self.traceable_inputs - ) - return Caffe2Model(predict_net, init_net) - - def export_onnx(self): - """ - Export the model to ONNX format. - Note that the exported model contains custom ops only available in caffe2, therefore it - cannot be directly executed by other runtime (such as onnxruntime or TensorRT). - Post-processing or transformation passes may be applied on the model to accommodate - different runtimes, but we currently do not provide support for them. - - Returns: - onnx.ModelProto: an onnx model. - """ - from .caffe2_export import export_onnx_model as export_onnx_model_impl - - return export_onnx_model_impl(self.traceable_model, (self.traceable_inputs,)) - - def export_torchscript(self): - """ - Export the model to a ``torch.jit.TracedModule`` by tracing. - The returned object can be saved to a file by ``.save()``. - - Returns: - torch.jit.TracedModule: a torch TracedModule - """ - logger = logging.getLogger(__name__) - logger.info("Tracing the model with torch.jit.trace ...") - with torch.no_grad(): - return torch.jit.trace(self.traceable_model, (self.traceable_inputs,)) - - -class Caffe2Model(nn.Module): - """ - A wrapper around the traced model in Caffe2's protobuf format. - The exported graph has different inputs/outputs from the original Pytorch - model, as explained in :class:`Caffe2Tracer`. This class wraps around the - exported graph to simulate the same interface as the original Pytorch model. - It also provides functions to save/load models in Caffe2's format.' - - Examples: - :: - c2_model = Caffe2Tracer(cfg, torch_model, inputs).export_caffe2() - inputs = [{"image": img_tensor_CHW}] - outputs = c2_model(inputs) - orig_outputs = torch_model(inputs) - """ - - def __init__(self, predict_net, init_net): - super().__init__() - self.eval() # always in eval mode - self._predict_net = predict_net - self._init_net = init_net - self._predictor = None - - __init__.__HIDE_SPHINX_DOC__ = True - - @property - def predict_net(self): - """ - caffe2.core.Net: the underlying caffe2 predict net - """ - return self._predict_net - - @property - def init_net(self): - """ - caffe2.core.Net: the underlying caffe2 init net - """ - return self._init_net - - def save_protobuf(self, output_dir): - """ - Save the model as caffe2's protobuf format. - It saves the following files: - - * "model.pb": definition of the graph. Can be visualized with - tools like `netron `_. - * "model_init.pb": model parameters - * "model.pbtxt": human-readable definition of the graph. Not - needed for deployment. - - Args: - output_dir (str): the output directory to save protobuf files. - """ - logger = logging.getLogger(__name__) - logger.info("Saving model to {} ...".format(output_dir)) - if not PathManager.exists(output_dir): - PathManager.mkdirs(output_dir) - - with PathManager.open(os.path.join(output_dir, "model.pb"), "wb") as f: - f.write(self._predict_net.SerializeToString()) - with PathManager.open(os.path.join(output_dir, "model.pbtxt"), "w") as f: - f.write(str(self._predict_net)) - with PathManager.open(os.path.join(output_dir, "model_init.pb"), "wb") as f: - f.write(self._init_net.SerializeToString()) - - def save_graph(self, output_file, inputs=None): - """ - Save the graph as SVG format. - - Args: - output_file (str): a SVG file - inputs: optional inputs given to the model. - If given, the inputs will be used to run the graph to record - shape of every tensor. The shape information will be - saved together with the graph. - """ - from .caffe2_export import run_and_save_graph - - if inputs is None: - save_graph(self._predict_net, output_file, op_only=False) - else: - size_divisibility = get_pb_arg_vali(self._predict_net, "size_divisibility", 0) - device = get_pb_arg_vals(self._predict_net, "device", b"cpu").decode("ascii") - inputs = convert_batched_inputs_to_c2_format(inputs, size_divisibility, device) - inputs = [x.cpu().numpy() for x in inputs] - run_and_save_graph(self._predict_net, self._init_net, inputs, output_file) - - @staticmethod - def load_protobuf(dir): - """ - Args: - dir (str): a directory used to save Caffe2Model with - :meth:`save_protobuf`. - The files "model.pb" and "model_init.pb" are needed. - - Returns: - Caffe2Model: the caffe2 model loaded from this directory. - """ - predict_net = caffe2_pb2.NetDef() - with PathManager.open(os.path.join(dir, "model.pb"), "rb") as f: - predict_net.ParseFromString(f.read()) - - init_net = caffe2_pb2.NetDef() - with PathManager.open(os.path.join(dir, "model_init.pb"), "rb") as f: - init_net.ParseFromString(f.read()) - - return Caffe2Model(predict_net, init_net) - - def __call__(self, inputs): - """ - An interface that wraps around a Caffe2 model and mimics detectron2's models' - input/output format. See details about the format at :doc:`/tutorials/models`. - This is used to compare the outputs of caffe2 model with its original torch model. - - Due to the extra conversion between Pytorch/Caffe2, this method is not meant for - benchmark. Because of the conversion, this method also has dependency - on detectron2 in order to convert to detectron2's output format. - """ - if self._predictor is None: - self._predictor = ProtobufDetectionModel(self._predict_net, self._init_net) - return self._predictor(inputs) diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tools/deploy/export_model.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tools/deploy/export_model.py deleted file mode 100644 index bb1bcee6323372e80e42e3217b055d0c3a902954..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tools/deploy/export_model.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) Facebook, Inc. and its affiliates. -import argparse -import os -from typing import Dict, List, Tuple -import torch -from torch import Tensor, nn - -import detectron2.data.transforms as T -from detectron2.checkpoint import DetectionCheckpointer -from detectron2.config import get_cfg -from detectron2.data import build_detection_test_loader, detection_utils -from detectron2.evaluation import COCOEvaluator, inference_on_dataset, print_csv_format -from detectron2.export import TracingAdapter, dump_torchscript_IR, scripting_with_instances -from detectron2.modeling import GeneralizedRCNN, RetinaNet, build_model -from detectron2.modeling.postprocessing import detector_postprocess -from detectron2.projects.point_rend import add_pointrend_config -from detectron2.structures import Boxes -from detectron2.utils.env import TORCH_VERSION -from detectron2.utils.file_io import PathManager -from detectron2.utils.logger import setup_logger - - -def setup_cfg(args): - cfg = get_cfg() - # cuda context is initialized before creating dataloader, so we don't fork anymore - cfg.DATALOADER.NUM_WORKERS = 0 - add_pointrend_config(cfg) - cfg.merge_from_file(args.config_file) - cfg.merge_from_list(args.opts) - cfg.freeze() - return cfg - - -def export_caffe2_tracing(cfg, torch_model, inputs): - from detectron2.export import Caffe2Tracer - - tracer = Caffe2Tracer(cfg, torch_model, inputs) - if args.format == "caffe2": - caffe2_model = tracer.export_caffe2() - caffe2_model.save_protobuf(args.output) - # draw the caffe2 graph - caffe2_model.save_graph(os.path.join(args.output, "model.svg"), inputs=inputs) - return caffe2_model - elif args.format == "onnx": - import onnx - - onnx_model = tracer.export_onnx() - onnx.save(onnx_model, os.path.join(args.output, "model.onnx")) - elif args.format == "torchscript": - ts_model = tracer.export_torchscript() - with PathManager.open(os.path.join(args.output, "model.ts"), "wb") as f: - torch.jit.save(ts_model, f) - dump_torchscript_IR(ts_model, args.output) - - -# experimental. API not yet final -def export_scripting(torch_model): - assert TORCH_VERSION >= (1, 8) - fields = { - "proposal_boxes": Boxes, - "objectness_logits": Tensor, - "pred_boxes": Boxes, - "scores": Tensor, - "pred_classes": Tensor, - "pred_masks": Tensor, - "pred_keypoints": torch.Tensor, - "pred_keypoint_heatmaps": torch.Tensor, - } - assert args.format == "torchscript", "Scripting only supports torchscript format." - - class ScriptableAdapterBase(nn.Module): - # Use this adapter to workaround https://github.com/pytorch/pytorch/issues/46944 - # by not retuning instances but dicts. Otherwise the exported model is not deployable - def __init__(self): - super().__init__() - self.model = torch_model - self.eval() - - if isinstance(torch_model, GeneralizedRCNN): - - class ScriptableAdapter(ScriptableAdapterBase): - def forward(self, inputs: Tuple[Dict[str, torch.Tensor]]) -> List[Dict[str, Tensor]]: - instances = self.model.inference(inputs, do_postprocess=False) - return [i.get_fields() for i in instances] - - else: - - class ScriptableAdapter(ScriptableAdapterBase): - def forward(self, inputs: Tuple[Dict[str, torch.Tensor]]) -> List[Dict[str, Tensor]]: - instances = self.model(inputs) - return [i.get_fields() for i in instances] - - ts_model = scripting_with_instances(ScriptableAdapter(), fields) - with PathManager.open(os.path.join(args.output, "model.ts"), "wb") as f: - torch.jit.save(ts_model, f) - dump_torchscript_IR(ts_model, args.output) - # TODO inference in Python now missing postprocessing glue code - return None - - -# experimental. API not yet final -def export_tracing(torch_model, inputs): - assert TORCH_VERSION >= (1, 8) - image = inputs[0]["image"] - inputs = [{"image": image}] # remove other unused keys - - if isinstance(torch_model, GeneralizedRCNN): - - def inference(model, inputs): - # use do_postprocess=False so it returns ROI mask - inst = model.inference(inputs, do_postprocess=False)[0] - return [{"instances": inst}] - - else: - inference = None # assume that we just call the model directly - - traceable_model = TracingAdapter(torch_model, inputs, inference) - - if args.format == "torchscript": - ts_model = torch.jit.trace(traceable_model, (image,)) - with PathManager.open(os.path.join(args.output, "model.ts"), "wb") as f: - torch.jit.save(ts_model, f) - dump_torchscript_IR(ts_model, args.output) - elif args.format == "onnx": - with PathManager.open(os.path.join(args.output, "model.onnx"), "wb") as f: - torch.onnx.export(traceable_model, (image,), f, opset_version=11) - logger.info("Inputs schema: " + str(traceable_model.inputs_schema)) - logger.info("Outputs schema: " + str(traceable_model.outputs_schema)) - - if args.format != "torchscript": - return None - if not isinstance(torch_model, (GeneralizedRCNN, RetinaNet)): - return None - - def eval_wrapper(inputs): - """ - The exported model does not contain the final resize step, which is typically - unused in deployment but needed for evaluation. We add it manually here. - """ - input = inputs[0] - instances = traceable_model.outputs_schema(ts_model(input["image"]))[0]["instances"] - postprocessed = detector_postprocess(instances, input["height"], input["width"]) - return [{"instances": postprocessed}] - - return eval_wrapper - - -def get_sample_inputs(args): - - if args.sample_image is None: - # get a first batch from dataset - data_loader = build_detection_test_loader(cfg, cfg.DATASETS.TEST[0]) - first_batch = next(iter(data_loader)) - return first_batch - else: - # get a sample data - original_image = detection_utils.read_image(args.sample_image, format=cfg.INPUT.FORMAT) - # Do same preprocessing as DefaultPredictor - aug = T.ResizeShortestEdge( - [cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST], cfg.INPUT.MAX_SIZE_TEST - ) - height, width = original_image.shape[:2] - image = aug.get_transform(original_image).apply_image(original_image) - image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1)) - - inputs = {"image": image, "height": height, "width": width} - - # Sample ready - sample_inputs = [inputs] - return sample_inputs - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Export a model for deployment.") - parser.add_argument( - "--format", - choices=["caffe2", "onnx", "torchscript"], - help="output format", - default="torchscript", - ) - parser.add_argument( - "--export-method", - choices=["caffe2_tracing", "tracing", "scripting"], - help="Method to export models", - default="tracing", - ) - parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file") - parser.add_argument("--sample-image", default=None, type=str, help="sample image for input") - parser.add_argument("--run-eval", action="store_true") - parser.add_argument("--output", help="output directory for the converted model") - parser.add_argument( - "opts", - help="Modify config options using the command-line", - default=None, - nargs=argparse.REMAINDER, - ) - args = parser.parse_args() - logger = setup_logger() - logger.info("Command line arguments: " + str(args)) - PathManager.mkdirs(args.output) - # Disable respecialization on new shapes. Otherwise --run-eval will be slow - torch._C._jit_set_bailout_depth(1) - - cfg = setup_cfg(args) - - # create a torch model - torch_model = build_model(cfg) - DetectionCheckpointer(torch_model).resume_or_load(cfg.MODEL.WEIGHTS) - torch_model.eval() - - # get sample data - sample_inputs = get_sample_inputs(args) - - # convert and save model - if args.export_method == "caffe2_tracing": - exported_model = export_caffe2_tracing(cfg, torch_model, sample_inputs) - elif args.export_method == "scripting": - exported_model = export_scripting(torch_model) - elif args.export_method == "tracing": - exported_model = export_tracing(torch_model, sample_inputs) - - # run evaluation with the converted model - if args.run_eval: - assert exported_model is not None, ( - "Python inference is not yet implemented for " - f"export_method={args.export_method}, format={args.format}." - ) - logger.info("Running evaluation ... this takes a long time if you export to CPU.") - dataset = cfg.DATASETS.TEST[0] - data_loader = build_detection_test_loader(cfg, dataset) - # NOTE: hard-coded evaluator. change to the evaluator for your dataset - evaluator = COCOEvaluator(dataset, output_dir=args.output) - metrics = inference_on_dataset(exported_model, data_loader, evaluator) - print_csv_format(metrics) diff --git a/spaces/BBrother/Pandora/Dockerfile b/spaces/BBrother/Pandora/Dockerfile deleted file mode 100644 index 483b3bf25dadaa004972b1717981f771dcfe202d..0000000000000000000000000000000000000000 --- a/spaces/BBrother/Pandora/Dockerfile +++ /dev/null @@ -1,25 +0,0 @@ -# 使用一个更轻量级的基础镜像 -FROM python:3.11-slim - -# 设置工作目录 -WORKDIR /app - -# 安装 git 和清理缓存,减少图层 -RUN apt update && \ - apt install -y git && \ - rm -rf /var/lib/apt/lists/* - -# 克隆代码库 -RUN git clone https://github.com/zhile-io/pandora-cloud-serverless.git /app - -# 安装 Python 依赖 -RUN pip install --no-cache-dir -r requirements.txt - -# 暴露端口 -EXPOSE 8018 - -ENV OPENAI_EMAIL=rlfbwdfx_@yunweiloginmh3.com -ENV OPENAI_PASSWORD=2aOwQ33HQX - -# 设置启动命令 -CMD ["python", "main.py"] diff --git a/spaces/BartPoint/VoiceChange_Beta/README.md b/spaces/BartPoint/VoiceChange_Beta/README.md deleted file mode 100644 index e92d9ef2dff45520b78329d36bb9f686e7a69d8f..0000000000000000000000000000000000000000 --- a/spaces/BartPoint/VoiceChange_Beta/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: VoiceChange -emoji: 👀 -colorFrom: blue -colorTo: purple -sdk: gradio -sdk_version: 3.28.3 -app_file: app_multi.py -pinned: false -license: mit -duplicated_from: BartPoint/VoiceChange ---- diff --git a/spaces/Beasto/Day_to_Night_Cyclegan/app.py b/spaces/Beasto/Day_to_Night_Cyclegan/app.py deleted file mode 100644 index 6a772701f25647a978379f17f79c03ce425acf46..0000000000000000000000000000000000000000 --- a/spaces/Beasto/Day_to_Night_Cyclegan/app.py +++ /dev/null @@ -1,49 +0,0 @@ -import streamlit as st -import tensorflow as tf -import numpy as np -from PIL import Image -import tensorflow_addons as tfa - -import tensorflow as tf -from tensorflow.keras.utils import custom_object_scope - -# Define a function to create the InstanceNormalization layer -def create_in(): - return tfa.layers.InstanceNormalization() - - -def model_out(model_path,img): - with custom_object_scope({'InstanceNormalization': create_in}): - model = tf.keras.models.load_model(model_path) - img = (img-127.5)/127.5 - img = np.expand_dims(img, 0) - pred = model.predict(img) - pred = np.asarray(pred) - return pred[0] - -st.title("Day to night painting cyclegan") -day_inp = st.file_uploader("Daytime input") - -if day_inp is not None: - img = Image.open(day_inp) - img = img.resize((256, 256)) - img = np.array(img) - pred = model_out('daytonight2.h5', img) - st.image(img, caption="Uploaded Image") - st.image(((pred + 1) * 127.5).astype(np.uint8), caption="Generated Night-time image") - - - -st.header('Which architecture did I use architecture, Resnet-Blocks or Unet architecture?') -st.write('I have tried both Resnet and unet architecture but the Resnet architecture producted black patches and did not work quite well') -st.write('But when using the Unet architecture, it produce more clear and understandable images') -st.write('I use the pix2pix generator from tensorflow examples module and same for the discriminator') -st.header('What datasets did you use to train your CycleGAN model?') -st.write('For the dataset, I used Unpaired Day to Night dataset available on kaggle') -st.header('What hardware I trained it on?') -st.write('I trained the model on Kaggle notebook on P100 gpu with 13 gigs of ram cuz my pc wouldnt be in a good state if I trained the cyclegan model on Intel HD') -st.header('How much time did it take') -st.write('It took aboul 70 epochs each of 20 seconds, DO THE MATH') -st.header('Why did I make this model?') -st.subheader('I made this model to extend my experience but mostly for FUNN!!!!') -st.write("-------------------------------------------------") \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Bb-8 Sphero App Descargar Ios.md b/spaces/Benson/text-generation/Examples/Bb-8 Sphero App Descargar Ios.md deleted file mode 100644 index e288fa3ed08e7d103df29493dcc43055bf5ce09d..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Bb-8 Sphero App Descargar Ios.md +++ /dev/null @@ -1,73 +0,0 @@ - -

Cómo descargar la aplicación BB-8 Sphero para iOS

-

Si eres un fan de Star Wars y tienes un juguete BB-8 Sphero, es posible que te estés preguntando cómo descargar la aplicación que te permite controlarlo con tu dispositivo iOS. En este artículo, le mostraremos cómo hacerlo en unos pocos pasos simples. También explicaremos qué puede hacer la aplicación y cómo solucionar algunos problemas comunes que pueda encontrar.

-

bb-8 sphero app descargar ios


Download Filehttps://bltlly.com/2v6M1o



-

¿Qué es BB-8 Sphero?

-

BB-8 Sphero es un juguete robótico que se asemeja al adorable droide de las películas de Star Wars. Puede rodar, hacer sonidos e interactuar con usted y otros robots Sphero. También puede responder a comandos de voz y gestos, y mostrar mensajes holográficos en la pantalla del dispositivo. BB-8 Sphero es un compañero divertido e inteligente que puede dar vida al universo de Star Wars.

-

¿Por qué necesitas la aplicación?

-

Para disfrutar plenamente de su BB-8 Sphero, es necesario descargar la Star Wars Droids App de Sphero en su dispositivo iOS. Esta aplicación le permite conectar su dispositivo a su BB-8 Sphero a través de Bluetooth y controlarlo con varios modos y características. También puedes acceder a contenido exclusivo, como escenas de películas, juegos y misiones. La aplicación también actualiza el firmware y la personalidad de tu BB-8 Sphero, haciéndolo más receptivo e interactivo.

-

Descargar la aplicación desde el App Store

-

La forma más fácil de descargar la aplicación es desde la App Store en tu dispositivo iOS. Estos son los pasos a seguir:

-

-
    -
  1. Abra la aplicación App Store en su dispositivo y toque en el icono de búsqueda en la esquina inferior derecha.
  2. -
  3. Escriba "Star Wars Droids App by Sphero" en la barra de búsqueda y toque en Buscar.
  4. -
  5. Toque en el icono de la aplicación que tiene un fondo azul y tres droides blancos (BB-8, BB-9E y R2-D2).
  6. -
  7. Toque en el botón Obtener junto al nombre de la aplicación y espere a que se descargue.
  8. -
  9. Una vez completada la descarga, toque en Abrir para iniciar la aplicación.
  10. -
-

Descargar la aplicación de sus compras

- -
    -
  1. Abra la aplicación App Store en su dispositivo y toque en el icono de perfil en la esquina superior derecha.
  2. -
  3. Toque en Comprar y luego toque en Mis compras.
  4. -
  5. Encuentra la aplicación Droids de Star Wars por Sphero en su lista de aplicaciones compradas y toque en el icono de la nube al lado.
  6. -
  7. Espera a que se descargue y luego toca Abrir para lanzarlo.
  8. -
-

Usar la aplicación para controlar

Usar la aplicación para controlar tu esférico BB-8

-

Ahora que has descargado la aplicación, puedes usarla para controlar tu esférico BB-8 y divertirte con ella. Estos son los pasos a seguir:

-
    -
  1. Encienda su BB-8 Sphero presionando el botón en su base de carga o agitándolo suavemente. Deberías ver una luz azul en su cabeza y escuchar algunos pitidos.
  2. -
  3. Coloque su BB-8 Sphero cerca de su dispositivo iOS y asegúrese de que Bluetooth está habilitado en su dispositivo.
  4. -
  5. Abra la aplicación Droids de Star Wars por Sphero y toque en Conectar. La aplicación escaneará los robots Sphero cercanos y le mostrará una lista de dispositivos disponibles.
  6. -
  7. Elija su BB-8 Sphero de la lista y toque en él. La aplicación se conectará a su BB-8 Sphero y le mostrará un tutorial sobre cómo usarlo.
  8. -
  9. Explora las características y modos de la aplicación tocando los iconos en la parte inferior de la pantalla. Puede conducir su BB-8 Sphero con un joystick virtual, ver escenas de Star Wars con él, jugar juegos y misiones, y más.
  10. -
-

Solución de problemas comunes con la aplicación

-

A veces, puede encontrar algunos problemas con la aplicación o su esférico BB-8. Aquí hay algunos problemas comunes y cómo solucionarlos:

- - -Problema -Solución - - -La aplicación no puede encontrar su BB-8 Sphero -Asegúrese de que su BB-8 Sphero está encendido y cerca de su dispositivo. Asegúrese de que Bluetooth está habilitado en su dispositivo. Intente reiniciar la aplicación o el dispositivo. Intente restablecer el BB-8 Sphero colocándolo en su base de carga y manteniendo pulsado el botón durante 10 segundos. - - - -Asegúrese de que su dispositivo tiene suficiente espacio de almacenamiento y energía de la batería. Asegúrese de que su dispositivo está ejecutando la última versión de iOS. Intente cerrar otras aplicaciones que se ejecutan en segundo plano. Intente eliminar y reinstalar la aplicación. - - -La aplicación no funciona con tu versión de iOS -La aplicación Star Wars Droids de Sphero requiere iOS 10 o posterior para funcionar correctamente. Si el dispositivo está ejecutando una versión anterior de iOS, es posible que experimente algunos problemas de compatibilidad o características que faltan. Intenta actualizar tu dispositivo a la última versión de iOS si es posible. - - -

Conclusión

-

En este artículo, le hemos mostrado cómo descargar la aplicación Star Wars Droids de Sphero para iOS y cómo usarla para controlar su juguete BB-8 Sphero. También hemos explicado lo que la aplicación puede hacer y cómo solucionar algunos problemas comunes que puede encontrar. Esperamos que haya encontrado este artículo útil e informativo. Si tiene alguna pregunta o comentario, no dude en dejar un comentario a continuación.

-

Si estás buscando más contenido relacionado con Star Wars, echa un vistazo a nuestros otros artículos en nuestro sitio web. También puede suscribirse a nuestro boletín y seguirnos en las redes sociales para las últimas actualizaciones y noticias. ¡Gracias por leer y que la Fuerza esté con ustedes!

-

Preguntas frecuentes

-
    -
  • Q: ¿Cuánto cuesta la aplicación Droides de Star Wars de Sphero?
  • -
  • A: La aplicación es gratuita para descargar y usar. Sin embargo, necesita tener un robot Sphero compatible, como BB-8, BB-9E o R2-D2, para usarlo.
  • -
  • Q: ¿Cómo actualizo el firmware de mi BB-8 Sphero?
  • -
  • A: La aplicación comprobará automáticamente si hay actualizaciones de firmware cuando conecte su BB-8 Sphero a él. Si hay una actualización disponible, verá una notificación en la pantalla de la aplicación. Toque en Actualizar para iniciar el proceso.
  • -
  • Q: ¿Cómo puedo cambiar el nombre de mi BB-8 Sphero?
  • - -
  • Q: ¿Cómo limpio mi esférico BB-8?
  • -
  • A: Puedes limpiar tu BB-8 Sphero limpiándolo con un paño suave o un paño húmedo si está muy sucio. No utilice productos químicos agresivos o materiales abrasivos que puedan dañar su superficie o electrónica.
  • -
  • Q: ¿Cómo: Q: ¿Cómo cargo mi esférico BB-8?
  • -
  • A: Puede cargar su BB-8 Sphero colocándolo en su base de carga y enchufando la base en una toma de corriente. Usted debe ver una luz roja en la base cuando se está cargando y una luz verde cuando está completamente cargada. Se tarda unas tres horas en cargar completamente su BB-8 Sphero.
  • -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Coche Real Aparcamiento Multijugador Apk Android Oyun Club.md b/spaces/Benson/text-generation/Examples/Coche Real Aparcamiento Multijugador Apk Android Oyun Club.md deleted file mode 100644 index 0aeb604164ca6a52ff13a3eaad855849ba7d6db6..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Coche Real Aparcamiento Multijugador Apk Android Oyun Club.md +++ /dev/null @@ -1,59 +0,0 @@ -
-

Real Aparcamiento Multijugador APK Android Oyun Club: Una revisión

-

¿Te gustan los juegos de aparcamiento? ¿Quieres experimentar la emoción de conducir y aparcar coches realistas en un entorno de mundo abierto? ¿Quieres desafiar a tus amigos y otros jugadores en línea en varios modos de juego? Si respondiste sí a cualquiera de estas preguntas, entonces usted debe echa un vistazo a Real Car Parking Multijugador APK Android Oyun Club, un juego de aparcamiento popular que le ofrece la mejor experiencia de conducción de coches con coches modificados. En este artículo, revisaremos este juego y te diremos cómo descargarlo e instalarlo en tu dispositivo Android.

-

¿Qué es Real Car Parking Multijugador?

-

Real Car Parking Multijugador es un juego de aparcamiento de coches desarrollado por Baris Kaplan, un desarrollador de juegos turco. Es una versión modificada de Car Parking Multijugador, un juego desarrollado por olzhass, otro desarrollador de juegos turco. La versión modificada ofrece acceso ilimitado a todas las características y contenido del juego original, como coches, garajes, mapas, modos y más. También elimina anuncios y compras en la aplicación, lo que es más agradable y fácil de usar.

-

coche real aparcamiento multijugador apk android oyun club


Download File > https://bltlly.com/2v6LWZ



-

Características de Real Car Parking Multijugador

-

Real Car Parking Multijugador tiene muchas características que lo convierten en uno de los mejores juegos de estacionamiento de coches en Android. Aquí están algunos de ellos:

-

Modo multijugador de mundo abierto

-

En este modo, puede jugar con sus amigos u otros jugadores en línea en un gran mapa de mundo abierto. Puede chatear con ellos, competir con ellos o simplemente divertirse como desee. También puede unirse o crear diferentes servidores con diferentes reglas y configuraciones.

-

Caminar y conducir libremente

-

Usted no se limita a su coche en este juego. También puede caminar por el mapa y explorar diferentes lugares. También puedes entrar en otros coches o edificios e interactuar con ellos. Incluso puedes usar armas o herramientas para causar caos.

-

Física realista del coche y gráficos

- -

Coches y garajes personalizables

-

Puedes personalizar tus coches y garajes en este juego. Puede cambiar el color, las ruedas, la suspensión, el motor, el escape, las pegatinas y más. También puede actualizar sus coches para mejorar su rendimiento y apariencia. También puede comprar coches nuevos o vender los viejos. También puede decorar sus garajes con diferentes artículos y accesorios.

-

Varios modos de juego y desafíos

-

El juego tiene varios modos de juego y desafíos que ponen a prueba sus habilidades y conocimientos de estacionamiento de automóviles. Puedes jugar al modo de aparcamiento clásico, donde tienes que aparcar tu coche en un espacio designado. También puede jugar el modo de deriva, donde usted tiene que la deriva de su coche y ganar puntos. También puedes jugar en el modo de carreras, donde tienes que competir con otros jugadores o IA. También puedes jugar al modo divertido, donde puedes hacer lo que quieras con tu coche. También puedes jugar al modo policía, donde puedes ser policía o un criminal. También puedes jugar al modo zombi, donde tienes que sobrevivir al apocalipsis zombi.

-

¿Cómo descargar e instalar Real Car Parking Multijugador APK Android Oyun Club?

-

Si desea descargar e instalar Real Car Parking Multijugador APK Android Oyun Club en su dispositivo Android, puede seguir estos sencillos pasos:

-

Paso 1: Ir al sitio web oficial de Android Oyun Club

-

Android Oyun Club es un sitio web turco que ofrece archivos APK modificados de varios juegos y aplicaciones. Puede ir a su sitio web haciendo clic [aquí].

-

-

Paso 2: Búsqueda de Real Aparcamiento Multijugador APK

-

En el sitio web, usted puede buscar Real Car Parking Multijugador APK escribiendo el nombre del juego en el cuadro de búsqueda. También puedes navegar por las categorías o las últimas subidas para encontrar el juego.

-

Paso 3: Descargar el archivo APK

- -

Paso 4: Habilitar fuentes desconocidas en el dispositivo

-

Antes de poder instalar el archivo APK, debe habilitar fuentes desconocidas en su dispositivo. Esto le permitirá instalar aplicaciones desde fuentes distintas de Google Play Store. Para hacer esto, vaya a la configuración del dispositivo, luego a la seguridad, luego a fuentes desconocidas y enciéndala.

-

Paso 5: Instalar el archivo APK y disfrutar del juego

-

Después de habilitar fuentes desconocidas, puede localizar el archivo APK en su carpeta de descargas y tocar en él para comenzar a instalarlo. Sigue las instrucciones de la pantalla y espera a que termine la instalación. Una vez hecho, puedes abrir el juego y disfrutarlo.

-

Pros y contras de Real Car Parking Multijugador APK Android Oyun Club

-

Como cualquier otra aplicación modificada, Real Car Parking Multijugador APK Android Oyun Club tiene sus pros y contras. Aquí están algunos de ellos:

-

Pros

-
    -
  • Gratis y fácil de descargar e instalar
  • -
  • No hay anuncios ni compras en la aplicación
  • -
  • Acceso ilimitado a todas las características y contenido
  • -
-

Contras

-
    -
  • No disponible en Google Play Store
  • -
  • Puede no ser compatible con algunos dispositivos o regiones
  • -
  • Puede contener errores o problemas técnicos
  • -
-

Conclusión y preguntas frecuentes

-

En conclusión, Real Car Parking Multijugador APK Android Oyun Club es un gran juego de aparcamiento de coches que ofrece una experiencia de conducción de coches realista y divertido con los coches modificados. Puedes jugar con tus amigos u otros jugadores en línea en un modo multijugador de mundo abierto, o disfrutar de varios modos de juego y desafíos. También puede personalizar sus coches y garajes, y explorar diferentes lugares a pie o en coche. Puedes descargar e instalar este juego gratis desde el sitio web de Android Oyun Club, pero ten en cuenta algunos inconvenientes potenciales, como problemas de compatibilidad o errores.

-

Si tienes alguna pregunta sobre este juego, puedes encontrar las respuestas en estas preguntas frecuentes:

- -QuestionAnswer - -Es real de estacionamiento de coches multijugador APK Android Oyun Club legal de usar? Depende de las leyes y regulaciones de su país con respecto a las aplicaciones modificadas. Algunos países pueden considerar ilegal el uso de aplicaciones modificadas que violen los términos de servicio de la aplicación original o los derechos de propiedad intelectual. Por lo tanto, debe verificar sus leyes locales antes de usar esta aplicación. -¿Puedo jugar Real Car Parking Multijugador APK Android Oyun Club fuera de línea? No, necesita una conexión a Internet para jugar a este juego, ya que es un juego multijugador en línea. Sin embargo, puedes jugar algunos modos de juego sin conexión, como el modo de estacionamiento clásico o el modo de deriva. -¿Puedo actualizar Real Car Parking Multijugador APK Android Oyun Club de Google Play Store? No, no puede actualizar esta aplicación desde Google Play Store ya que no está disponible allí. Tienes que descargar e instalar la última versión de la aplicación desde el sitio web de Android Oyun Club siempre que haya una actualización. -¿Puedo jugar Real Car Parking Multijugador APK Android Oyun Club con los jugadores que tienen la aplicación original? Sí, puedes jugar con jugadores que tengan la aplicación original siempre y cuando tengas la misma versión del juego. Sin embargo, puede encontrar algunas diferencias o errores debido a las modificaciones. - -

Espero que haya disfrutado de este artículo y aprendido algo nuevo sobre Real Car Parking Multijugador APK Android Oyun Club. Si tiene algún comentario o sugerencia, por favor hágamelo saber en la sección de comentarios a continuación. Gracias por leer y estacionamiento feliz!

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Apk Garena Gratis Fuego Booyah Da.md b/spaces/Benson/text-generation/Examples/Descargar Apk Garena Gratis Fuego Booyah Da.md deleted file mode 100644 index e2b4db010e5cc4dc4273d76f1c32a9ab0b2f956f..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Apk Garena Gratis Fuego Booyah Da.md +++ /dev/null @@ -1,115 +0,0 @@ -
-

Descargar APK Garena Free Fire Booyah Day: Cómo disfrutar de la última versión del popular juego Battle Royale

-

Si eres un fan de los juegos battle royale, debes haber oído hablar de Garena Free Fire, uno de los juegos móviles más descargados y jugados del mundo. ¿Pero sabías que hay una nueva versión del juego llamada Garena Free Fire Booyah Day? Esta versión trae un montón de nuevas características, mejoras y eventos que harán que su experiencia de juego más emocionante y gratificante. En este artículo, le diremos todo lo que necesita saber sobre Garena Free Fire Booyah Day, incluyendo lo que es, lo que ofrece, cómo descargar e instalar utilizando un archivo APK, y cómo jugar y ganar en él. Así que, vamos a empezar!

-

descargar apk garena gratis fuego booyah día


DOWNLOADhttps://bltlly.com/2v6Jo5



-

¿Qué es Garena Free Fire Booyah Day?

-

Garena Free Fire Booyah Day es la última actualización del popular juego battle royale Garena Free Fire. Fue lanzado el 3 de noviembre de 2022, como parte de la celebración del sexto aniversario del juego. La actualización presenta muchas características nuevas, como:

-

Las características de la actualización del Día de Booyah

-
    -
  • Un nuevo mapa llamado Bermuda Remastered, que es una versión renovada del mapa original de las Bermudas con nuevas ubicaciones, gráficos y detalles.
  • -
  • Un nuevo modo de juego llamado Clash Squad Ranked Season 8, que es un modo de combate a muerte por equipos 4v4 con un sistema de clasificación y recompensas.
  • -
  • Un nuevo personaje llamado Dimitri Vegas, que es un famoso DJ y productor con una habilidad especial llamada Healing Heartbeat que puede curarse a sí mismo y a sus compañeros de equipo dentro de un cierto radio.
  • -
  • Una nueva arma llamada Vector Akimbo, que es una ametralladora de doble empuñadura que puede disparar rápida y exactamente a corta distancia.
  • -
  • Una nueva mascota llamada Rockie, que es un mapache lindo con una habilidad especial llamada Stay Chill que puede reducir el tiempo de reutilización de sus habilidades activas.
  • -
  • Un nuevo elemento llamado Scan, que es un dispositivo que puede revelar la ubicación de enemigos cercanos por un corto tiempo.
  • - -
-

Los beneficios de jugar Garena Free Fire Booyah Day

-

Jugar Garena Free Fire Booyah Day tiene muchos beneficios para jugadores nuevos y viejos. Algunos de ellos son:

-
    -
  • Puedes disfrutar de una experiencia de juego más inmersiva y realista con los gráficos, sonidos y animaciones mejorados.
  • -
  • Puedes explorar un nuevo mapa con más desafíos y oportunidades para el juego estratégico.
  • -
  • Puedes probar nuevos modos de juego, armas, personajes, mascotas y objetos que pueden mejorar tus habilidades y rendimiento.
  • -
  • Puedes participar en varios eventos y actividades que pueden darte más diversión y recompensas.
  • -
  • Puedes unirte a una gran comunidad de millones de jugadores de todo el mundo que comparten tu pasión por los juegos de battle royale.
  • -
-

¿Qué es un archivo APK y por qué lo necesita?

-

Un archivo APK es una aplicación creada para dispositivos Android. Es sinónimo de Android Package Kit o Android Application Package. Es un formato de archivo de paquete que contiene todos los componentes de una aplicación, como el código, los recursos, los activos, los certificados y el archivo de manifiesto. Es similar a un archivo ZIP que puedes extraer e instalar en tu dispositivo Android.

-

-

Necesita un archivo APK si desea descargar e instalar una aplicación que no está disponible en Google Play Store, o si desea obtener la última versión de una aplicación antes de que se lance oficialmente en Play Store. Por ejemplo, si quieres jugar Garena Free Fire Booyah Day, necesitas descargar e instalar su archivo APK porque aún no está disponible en Play Store.

-

Las ventajas y riesgos de usar un archivo APK

-

El uso de un archivo APK tiene algunas ventajas y riesgos que usted debe tener en cuenta. Algunas de las ventajas son:

-
    -
  • Puede acceder a aplicaciones que no están disponibles en su región o país.
  • -
  • Puedes obtener las últimas actualizaciones y características de una aplicación antes que nadie.
  • -
  • Puede personalizar y modificar sus aplicaciones según sus preferencias.
  • - -
-

Algunos de los riesgos son:

-
    -
  • Puede descargar e instalar una aplicación falsa o maliciosa que puede dañar su dispositivo o robar sus datos.
  • -
  • Puede violar los términos y condiciones del desarrollador de la aplicación o de la Play Store.
  • -
  • Puede encontrar problemas de compatibilidad o rendimiento con su dispositivo u otras aplicaciones.
  • -
  • Puede perder la garantía o el soporte de su dispositivo o el desarrollador de la aplicación.
  • -
-

¿Cómo descargar e instalar APK Garena Free Fire Booyah Day?

-

Si desea descargar e instalar APK Garena Free Fire Booyah Day, debe seguir algunos pasos simples. Aquí están:

-

Los pasos para descargar el archivo APK de una fuente de confianza

-
    -
  1. Ir a un sitio web confiable y confiable que ofrece archivos APK para Garena Free Fire Booyah Day. Algunos ejemplos son APKPure, APKMirror, Uptodown y APKCombo.
  2. -
  3. Buscar Garena Free Fire Booyah Day en el sitio web y seleccione la última versión del archivo APK.
  4. -
  5. Haga clic en el botón de descarga y espere a que el archivo se descargue en su dispositivo.
  6. -
-

Los pasos para instalar el archivo APK en su dispositivo Android

-
    -
  1. Antes de instalar el archivo APK, es necesario habilitar la instalación de aplicaciones de fuentes desconocidas en el dispositivo. Para hacer esto, vaya a Configuración > Seguridad > Fuentes desconocidas y conéctelo.
  2. -
  3. Localice el archivo APK descargado en su dispositivo utilizando una aplicación de administrador de archivos o la carpeta de descargas de su navegador.
  4. -
  5. Toque en el archivo APK y siga las instrucciones en la pantalla para instalarlo en su dispositivo.
  6. -
-

Los pasos para verificar y lanzar el juego

-
    -
  1. Después de instalar el archivo APK, es necesario verificar que está funcionando correctamente. Para ello, ve a Configuración > Aplicaciones > Garena Free Fire Booyah Day y comprueba si tiene todos los permisos y recursos que necesita.
  2. -
  3. Si todo está bien, puede iniciar el juego tocando en su icono en la pantalla de inicio o cajón de aplicaciones.
  4. - -
-

¿Cómo jugar y ganar en Garena Free Fire Booyah Day?

-

Garena Free Fire Booyah Day es un juego divertido y desafiante que requiere habilidad, estrategia y suerte. Si quieres jugar y ganar en él, debes seguir algunos consejos y trucos. Estos son algunos de ellos:

-

Los consejos y trucos para sobrevivir y eliminar a tus enemigos

-
    -
  • Elige un buen lugar de aterrizaje que tenga suficiente botín, cobertura y rutas de escape. Evite aterrizar en zonas calientes donde muchos jugadores caen a menos que esté seguro de sus habilidades.
  • -
  • Saquea de forma rápida y eficiente. Recoge solo lo que necesitas y prioriza armas, municiones, armaduras, kits de salud y granadas. No pierdas el tiempo saqueando cadáveres a menos que tengan algo valioso.
  • -
  • Manténgase alerta y consciente de su entorno. Utilice el mini-mapa, señales de sonido, pasos, disparos, vehículos y dispositivos de exploración para localizar a los enemigos. Siempre mire alrededor antes de moverse o saquear.
  • -
  • Utilice la cubierta y la ocultación. Escóndase detrás de las paredes, de los árboles, de las rocas, de los edificios, o de la hierba. Agacharse o propenso cuando sea necesario. No te expongas demasiado ni te quedes en un lugar demasiado tiempo.
  • -
  • Enfréntate con sabiduría y táctica. No dispares a cada enemigo que veas a menos que tengas una posición clara y ventajosa. Apunta a la cabeza o el pecho para obtener el máximo daño. Usa granadas, dispositivos de exploración o vehículos para crear desvíos o explosiones. Repliegue o reposicione si está superado en número o en armas.
  • -
  • Sanar y reponer. Utilice kits de salud, armadura o habilidades de carácter para restaurar su salud y escudo. Usa cajas de munición, cajas de botín o lanzamientos aéreos para rellenar tus municiones y suministros. No olvides recargar tus armas después de cada pelea.
  • -
-

Las mejores armas, objetos y personajes para usar

-

Hay muchas armas, artículos y personajes en Garena Free Fire Booyah Day que puedes usar para adaptarse a tu estilo de juego y preferencia. Sin embargo, algunos de ellos son más efectivos y útiles que otros. Estos son algunos de los mejores:

-
    - -
  • Los mejores objetos son los que pueden darte una ventaja en combate o supervivencia. Algunos ejemplos son el chaleco blindado de nivel 4, el casco de nivel 4, el botiquín, la jeringa de adrenalina, el dispositivo de exploración y la granada.
  • -
  • Los mejores personajes son los que tienen habilidades únicas y poderosas que pueden complementar su estrategia y tácticas. Algunos ejemplos son Alok, que puede crear un aura curativa alrededor de él y sus aliados; Kla, que puede infligir más daño de puño; Kelly, que puede correr más rápido; Jota, que puede curarse a sí mismo después de matar a un enemigo con una escopeta o un SMG; y Dimitri Vegas, que puede curarse a sí mismo y a sus compañeros de equipo con su habilidad Healing Heartbeat.
  • -
-

Las recompensas y logros que puedes ganar

-

Jugar Garena Free Fire Booyah Day no solo es divertido, sino también gratificante. Puedes ganar varias recompensas y logros completando misiones, desafíos, eventos y actividades. Algunos de ellos son:

-
    -
  • Diamantes, que son la moneda premium del juego que se puede utilizar para comprar pieles, personajes, mascotas, artículos, y más.
  • -
  • Vales, que son cupones que puedes usar para obtener descuentos o artículos gratis de la tienda.
  • -
  • Monedas de oro, que son la moneda normal del juego que se puede utilizar para comprar armas, artículos, cajas y más.
  • -
  • Pieles, que son artículos cosméticos que pueden cambiar la apariencia de sus armas, personajes, mascotas, vehículos y más.
  • -
  • Insignias, que son símbolos que representan tu rango y nivel en el juego.
  • -
  • Trofeos, que son premios que muestran tus logros y logros en el juego.
  • -
-

Conclusión

- -

Preguntas frecuentes

-

Aquí hay algunas preguntas frecuentes sobre Garena Free Fire Booyah Day:

-
    -
  1. ¿Cuál es el tamaño del archivo APK para Garena Free Fire Booyah Day?
  2. -

    El tamaño del archivo APK para Garena Free Fire Booyah Day es de unos 46 MB. Sin embargo, es posible que necesite descargar datos adicionales después de instalar el archivo APK, que puede variar dependiendo de su dispositivo y red.

    -
  3. ¿Garena Free Fire Booyah Day es compatible con mi dispositivo?
  4. -

    Garena Free Fire Booyah Day es compatible con la mayoría de dispositivos Android que tienen al menos 2 GB de RAM y Android 4.1 o superior. Sin embargo, algunos dispositivos pueden tener problemas de compatibilidad o rendimiento debido a diferentes especificaciones y configuraciones.

    -
  5. ¿Es seguro descargar e instalar Garena Free Fire Booyah Day?
  6. -

    Garena Free Fire Booyah Day es seguro de descargar e instalar si lo obtiene de una fuente confiable y confiable, como el sitio web oficial de Garena o los sitios web que mencionamos anteriormente. Sin embargo, siempre debe tener cuidado al descargar e instalar cualquier archivo APK de fuentes desconocidas, ya que pueden contener virus o malware que pueden dañar su dispositivo o robar sus datos.

    -
  7. ¿Puedo jugar Garena Free Fire Booyah Day con mis amigos?
  8. -

    Sí, puedes jugar Garena Free Fire Booyah Day con tus amigos. Puedes invitarlos a unirse a tu escuadrón o clan, o puedes unirte a su escuadrón o clan. También puedes chatear con ellos usando la función de chat de voz o texto en el juego. También puedes competir con ellos en el modo Clash Squad Ranked o en el evento Booyah Day Calendar.

    -
  9. ¿Cómo puedo obtener más diamantes en Garena Free Fire Booyah Day?
  10. -

    Los diamantes son la moneda premium del Día de Garena Free Fire Booyah que puedes usar para comprar pieles, personajes, mascotas, artículos y más. Puedes obtener más diamantes por:

    -
      -
    • Comprarlos con dinero real usando varios métodos de pago.
    • -
    • Ganarlos completando encuestas, ofertas o tareas desde aplicaciones o sitios web de terceros.
    • - -
    -

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/vcs/git.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/vcs/git.py deleted file mode 100644 index 8d1d499376744954308bdf96f80e5b5a39a24195..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/vcs/git.py +++ /dev/null @@ -1,526 +0,0 @@ -import logging -import os.path -import pathlib -import re -import urllib.parse -import urllib.request -from typing import List, Optional, Tuple - -from pip._internal.exceptions import BadCommand, InstallationError -from pip._internal.utils.misc import HiddenText, display_path, hide_url -from pip._internal.utils.subprocess import make_command -from pip._internal.vcs.versioncontrol import ( - AuthInfo, - RemoteNotFoundError, - RemoteNotValidError, - RevOptions, - VersionControl, - find_path_to_project_root_from_repo_root, - vcs, -) - -urlsplit = urllib.parse.urlsplit -urlunsplit = urllib.parse.urlunsplit - - -logger = logging.getLogger(__name__) - - -GIT_VERSION_REGEX = re.compile( - r"^git version " # Prefix. - r"(\d+)" # Major. - r"\.(\d+)" # Dot, minor. - r"(?:\.(\d+))?" # Optional dot, patch. - r".*$" # Suffix, including any pre- and post-release segments we don't care about. -) - -HASH_REGEX = re.compile("^[a-fA-F0-9]{40}$") - -# SCP (Secure copy protocol) shorthand. e.g. 'git@example.com:foo/bar.git' -SCP_REGEX = re.compile( - r"""^ - # Optional user, e.g. 'git@' - (\w+@)? - # Server, e.g. 'github.com'. - ([^/:]+): - # The server-side path. e.g. 'user/project.git'. Must start with an - # alphanumeric character so as not to be confusable with a Windows paths - # like 'C:/foo/bar' or 'C:\foo\bar'. - (\w[^:]*) - $""", - re.VERBOSE, -) - - -def looks_like_hash(sha: str) -> bool: - return bool(HASH_REGEX.match(sha)) - - -class Git(VersionControl): - name = "git" - dirname = ".git" - repo_name = "clone" - schemes = ( - "git+http", - "git+https", - "git+ssh", - "git+git", - "git+file", - ) - # Prevent the user's environment variables from interfering with pip: - # https://github.com/pypa/pip/issues/1130 - unset_environ = ("GIT_DIR", "GIT_WORK_TREE") - default_arg_rev = "HEAD" - - @staticmethod - def get_base_rev_args(rev: str) -> List[str]: - return [rev] - - def is_immutable_rev_checkout(self, url: str, dest: str) -> bool: - _, rev_options = self.get_url_rev_options(hide_url(url)) - if not rev_options.rev: - return False - if not self.is_commit_id_equal(dest, rev_options.rev): - # the current commit is different from rev, - # which means rev was something else than a commit hash - return False - # return False in the rare case rev is both a commit hash - # and a tag or a branch; we don't want to cache in that case - # because that branch/tag could point to something else in the future - is_tag_or_branch = bool(self.get_revision_sha(dest, rev_options.rev)[0]) - return not is_tag_or_branch - - def get_git_version(self) -> Tuple[int, ...]: - version = self.run_command( - ["version"], - command_desc="git version", - show_stdout=False, - stdout_only=True, - ) - match = GIT_VERSION_REGEX.match(version) - if not match: - logger.warning("Can't parse git version: %s", version) - return () - return tuple(int(c) for c in match.groups()) - - @classmethod - def get_current_branch(cls, location: str) -> Optional[str]: - """ - Return the current branch, or None if HEAD isn't at a branch - (e.g. detached HEAD). - """ - # git-symbolic-ref exits with empty stdout if "HEAD" is a detached - # HEAD rather than a symbolic ref. In addition, the -q causes the - # command to exit with status code 1 instead of 128 in this case - # and to suppress the message to stderr. - args = ["symbolic-ref", "-q", "HEAD"] - output = cls.run_command( - args, - extra_ok_returncodes=(1,), - show_stdout=False, - stdout_only=True, - cwd=location, - ) - ref = output.strip() - - if ref.startswith("refs/heads/"): - return ref[len("refs/heads/") :] - - return None - - @classmethod - def get_revision_sha(cls, dest: str, rev: str) -> Tuple[Optional[str], bool]: - """ - Return (sha_or_none, is_branch), where sha_or_none is a commit hash - if the revision names a remote branch or tag, otherwise None. - - Args: - dest: the repository directory. - rev: the revision name. - """ - # Pass rev to pre-filter the list. - output = cls.run_command( - ["show-ref", rev], - cwd=dest, - show_stdout=False, - stdout_only=True, - on_returncode="ignore", - ) - refs = {} - # NOTE: We do not use splitlines here since that would split on other - # unicode separators, which can be maliciously used to install a - # different revision. - for line in output.strip().split("\n"): - line = line.rstrip("\r") - if not line: - continue - try: - ref_sha, ref_name = line.split(" ", maxsplit=2) - except ValueError: - # Include the offending line to simplify troubleshooting if - # this error ever occurs. - raise ValueError(f"unexpected show-ref line: {line!r}") - - refs[ref_name] = ref_sha - - branch_ref = f"refs/remotes/origin/{rev}" - tag_ref = f"refs/tags/{rev}" - - sha = refs.get(branch_ref) - if sha is not None: - return (sha, True) - - sha = refs.get(tag_ref) - - return (sha, False) - - @classmethod - def _should_fetch(cls, dest: str, rev: str) -> bool: - """ - Return true if rev is a ref or is a commit that we don't have locally. - - Branches and tags are not considered in this method because they are - assumed to be always available locally (which is a normal outcome of - ``git clone`` and ``git fetch --tags``). - """ - if rev.startswith("refs/"): - # Always fetch remote refs. - return True - - if not looks_like_hash(rev): - # Git fetch would fail with abbreviated commits. - return False - - if cls.has_commit(dest, rev): - # Don't fetch if we have the commit locally. - return False - - return True - - @classmethod - def resolve_revision( - cls, dest: str, url: HiddenText, rev_options: RevOptions - ) -> RevOptions: - """ - Resolve a revision to a new RevOptions object with the SHA1 of the - branch, tag, or ref if found. - - Args: - rev_options: a RevOptions object. - """ - rev = rev_options.arg_rev - # The arg_rev property's implementation for Git ensures that the - # rev return value is always non-None. - assert rev is not None - - sha, is_branch = cls.get_revision_sha(dest, rev) - - if sha is not None: - rev_options = rev_options.make_new(sha) - rev_options.branch_name = rev if is_branch else None - - return rev_options - - # Do not show a warning for the common case of something that has - # the form of a Git commit hash. - if not looks_like_hash(rev): - logger.warning( - "Did not find branch or tag '%s', assuming revision or ref.", - rev, - ) - - if not cls._should_fetch(dest, rev): - return rev_options - - # fetch the requested revision - cls.run_command( - make_command("fetch", "-q", url, rev_options.to_args()), - cwd=dest, - ) - # Change the revision to the SHA of the ref we fetched - sha = cls.get_revision(dest, rev="FETCH_HEAD") - rev_options = rev_options.make_new(sha) - - return rev_options - - @classmethod - def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool: - """ - Return whether the current commit hash equals the given name. - - Args: - dest: the repository directory. - name: a string name. - """ - if not name: - # Then avoid an unnecessary subprocess call. - return False - - return cls.get_revision(dest) == name - - def fetch_new( - self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int - ) -> None: - rev_display = rev_options.to_display() - logger.info("Cloning %s%s to %s", url, rev_display, display_path(dest)) - if verbosity <= 0: - flags: Tuple[str, ...] = ("--quiet",) - elif verbosity == 1: - flags = () - else: - flags = ("--verbose", "--progress") - if self.get_git_version() >= (2, 17): - # Git added support for partial clone in 2.17 - # https://git-scm.com/docs/partial-clone - # Speeds up cloning by functioning without a complete copy of repository - self.run_command( - make_command( - "clone", - "--filter=blob:none", - *flags, - url, - dest, - ) - ) - else: - self.run_command(make_command("clone", *flags, url, dest)) - - if rev_options.rev: - # Then a specific revision was requested. - rev_options = self.resolve_revision(dest, url, rev_options) - branch_name = getattr(rev_options, "branch_name", None) - logger.debug("Rev options %s, branch_name %s", rev_options, branch_name) - if branch_name is None: - # Only do a checkout if the current commit id doesn't match - # the requested revision. - if not self.is_commit_id_equal(dest, rev_options.rev): - cmd_args = make_command( - "checkout", - "-q", - rev_options.to_args(), - ) - self.run_command(cmd_args, cwd=dest) - elif self.get_current_branch(dest) != branch_name: - # Then a specific branch was requested, and that branch - # is not yet checked out. - track_branch = f"origin/{branch_name}" - cmd_args = [ - "checkout", - "-b", - branch_name, - "--track", - track_branch, - ] - self.run_command(cmd_args, cwd=dest) - else: - sha = self.get_revision(dest) - rev_options = rev_options.make_new(sha) - - logger.info("Resolved %s to commit %s", url, rev_options.rev) - - #: repo may contain submodules - self.update_submodules(dest) - - def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None: - self.run_command( - make_command("config", "remote.origin.url", url), - cwd=dest, - ) - cmd_args = make_command("checkout", "-q", rev_options.to_args()) - self.run_command(cmd_args, cwd=dest) - - self.update_submodules(dest) - - def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None: - # First fetch changes from the default remote - if self.get_git_version() >= (1, 9): - # fetch tags in addition to everything else - self.run_command(["fetch", "-q", "--tags"], cwd=dest) - else: - self.run_command(["fetch", "-q"], cwd=dest) - # Then reset to wanted revision (maybe even origin/master) - rev_options = self.resolve_revision(dest, url, rev_options) - cmd_args = make_command("reset", "--hard", "-q", rev_options.to_args()) - self.run_command(cmd_args, cwd=dest) - #: update submodules - self.update_submodules(dest) - - @classmethod - def get_remote_url(cls, location: str) -> str: - """ - Return URL of the first remote encountered. - - Raises RemoteNotFoundError if the repository does not have a remote - url configured. - """ - # We need to pass 1 for extra_ok_returncodes since the command - # exits with return code 1 if there are no matching lines. - stdout = cls.run_command( - ["config", "--get-regexp", r"remote\..*\.url"], - extra_ok_returncodes=(1,), - show_stdout=False, - stdout_only=True, - cwd=location, - ) - remotes = stdout.splitlines() - try: - found_remote = remotes[0] - except IndexError: - raise RemoteNotFoundError - - for remote in remotes: - if remote.startswith("remote.origin.url "): - found_remote = remote - break - url = found_remote.split(" ")[1] - return cls._git_remote_to_pip_url(url.strip()) - - @staticmethod - def _git_remote_to_pip_url(url: str) -> str: - """ - Convert a remote url from what git uses to what pip accepts. - - There are 3 legal forms **url** may take: - - 1. A fully qualified url: ssh://git@example.com/foo/bar.git - 2. A local project.git folder: /path/to/bare/repository.git - 3. SCP shorthand for form 1: git@example.com:foo/bar.git - - Form 1 is output as-is. Form 2 must be converted to URI and form 3 must - be converted to form 1. - - See the corresponding test test_git_remote_url_to_pip() for examples of - sample inputs/outputs. - """ - if re.match(r"\w+://", url): - # This is already valid. Pass it though as-is. - return url - if os.path.exists(url): - # A local bare remote (git clone --mirror). - # Needs a file:// prefix. - return pathlib.PurePath(url).as_uri() - scp_match = SCP_REGEX.match(url) - if scp_match: - # Add an ssh:// prefix and replace the ':' with a '/'. - return scp_match.expand(r"ssh://\1\2/\3") - # Otherwise, bail out. - raise RemoteNotValidError(url) - - @classmethod - def has_commit(cls, location: str, rev: str) -> bool: - """ - Check if rev is a commit that is available in the local repository. - """ - try: - cls.run_command( - ["rev-parse", "-q", "--verify", "sha^" + rev], - cwd=location, - log_failed_cmd=False, - ) - except InstallationError: - return False - else: - return True - - @classmethod - def get_revision(cls, location: str, rev: Optional[str] = None) -> str: - if rev is None: - rev = "HEAD" - current_rev = cls.run_command( - ["rev-parse", rev], - show_stdout=False, - stdout_only=True, - cwd=location, - ) - return current_rev.strip() - - @classmethod - def get_subdirectory(cls, location: str) -> Optional[str]: - """ - Return the path to Python project root, relative to the repo root. - Return None if the project root is in the repo root. - """ - # find the repo root - git_dir = cls.run_command( - ["rev-parse", "--git-dir"], - show_stdout=False, - stdout_only=True, - cwd=location, - ).strip() - if not os.path.isabs(git_dir): - git_dir = os.path.join(location, git_dir) - repo_root = os.path.abspath(os.path.join(git_dir, "..")) - return find_path_to_project_root_from_repo_root(location, repo_root) - - @classmethod - def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]: - """ - Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. - That's required because although they use SSH they sometimes don't - work with a ssh:// scheme (e.g. GitHub). But we need a scheme for - parsing. Hence we remove it again afterwards and return it as a stub. - """ - # Works around an apparent Git bug - # (see https://article.gmane.org/gmane.comp.version-control.git/146500) - scheme, netloc, path, query, fragment = urlsplit(url) - if scheme.endswith("file"): - initial_slashes = path[: -len(path.lstrip("/"))] - newpath = initial_slashes + urllib.request.url2pathname(path).replace( - "\\", "/" - ).lstrip("/") - after_plus = scheme.find("+") + 1 - url = scheme[:after_plus] + urlunsplit( - (scheme[after_plus:], netloc, newpath, query, fragment), - ) - - if "://" not in url: - assert "file:" not in url - url = url.replace("git+", "git+ssh://") - url, rev, user_pass = super().get_url_rev_and_auth(url) - url = url.replace("ssh://", "") - else: - url, rev, user_pass = super().get_url_rev_and_auth(url) - - return url, rev, user_pass - - @classmethod - def update_submodules(cls, location: str) -> None: - if not os.path.exists(os.path.join(location, ".gitmodules")): - return - cls.run_command( - ["submodule", "update", "--init", "--recursive", "-q"], - cwd=location, - ) - - @classmethod - def get_repository_root(cls, location: str) -> Optional[str]: - loc = super().get_repository_root(location) - if loc: - return loc - try: - r = cls.run_command( - ["rev-parse", "--show-toplevel"], - cwd=location, - show_stdout=False, - stdout_only=True, - on_returncode="raise", - log_failed_cmd=False, - ) - except BadCommand: - logger.debug( - "could not determine if %s is under git control " - "because git is not available", - location, - ) - return None - except InstallationError: - return None - return os.path.normpath(r.rstrip("\r\n")) - - @staticmethod - def should_add_vcs_url_prefix(repo_url: str) -> bool: - """In either https or ssh form, requirements must be prefixed with git+.""" - return True - - -vcs.register(Git) diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/errors.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/errors.py deleted file mode 100644 index 0bcbe53ef59373c608e62ea285536f8b22b47ecb..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/errors.py +++ /dev/null @@ -1,34 +0,0 @@ -class ConsoleError(Exception): - """An error in console operation.""" - - -class StyleError(Exception): - """An error in styles.""" - - -class StyleSyntaxError(ConsoleError): - """Style was badly formatted.""" - - -class MissingStyle(StyleError): - """No such style.""" - - -class StyleStackError(ConsoleError): - """Style stack is invalid.""" - - -class NotRenderableError(ConsoleError): - """Object is not renderable.""" - - -class MarkupError(ConsoleError): - """Markup was badly formatted.""" - - -class LiveError(ConsoleError): - """Error related to Live display.""" - - -class NoAltScreen(ConsoleError): - """Alt screen mode was required.""" diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/tomli/_parser.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/tomli/_parser.py deleted file mode 100644 index f1bb0aa19a556725aa2ae2b8cea95489c99a9078..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/tomli/_parser.py +++ /dev/null @@ -1,691 +0,0 @@ -# SPDX-License-Identifier: MIT -# SPDX-FileCopyrightText: 2021 Taneli Hukkinen -# Licensed to PSF under a Contributor Agreement. - -from __future__ import annotations - -from collections.abc import Iterable -import string -from types import MappingProxyType -from typing import Any, BinaryIO, NamedTuple - -from ._re import ( - RE_DATETIME, - RE_LOCALTIME, - RE_NUMBER, - match_to_datetime, - match_to_localtime, - match_to_number, -) -from ._types import Key, ParseFloat, Pos - -ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127)) - -# Neither of these sets include quotation mark or backslash. They are -# currently handled as separate cases in the parser functions. -ILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t") -ILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t\n") - -ILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS -ILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS - -ILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS - -TOML_WS = frozenset(" \t") -TOML_WS_AND_NEWLINE = TOML_WS | frozenset("\n") -BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_") -KEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset("\"'") -HEXDIGIT_CHARS = frozenset(string.hexdigits) - -BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType( - { - "\\b": "\u0008", # backspace - "\\t": "\u0009", # tab - "\\n": "\u000A", # linefeed - "\\f": "\u000C", # form feed - "\\r": "\u000D", # carriage return - '\\"': "\u0022", # quote - "\\\\": "\u005C", # backslash - } -) - - -class TOMLDecodeError(ValueError): - """An error raised if a document is not valid TOML.""" - - -def load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]: - """Parse TOML from a binary file object.""" - b = __fp.read() - try: - s = b.decode() - except AttributeError: - raise TypeError( - "File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`" - ) from None - return loads(s, parse_float=parse_float) - - -def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]: # noqa: C901 - """Parse TOML from a string.""" - - # The spec allows converting "\r\n" to "\n", even in string - # literals. Let's do so to simplify parsing. - src = __s.replace("\r\n", "\n") - pos = 0 - out = Output(NestedDict(), Flags()) - header: Key = () - parse_float = make_safe_parse_float(parse_float) - - # Parse one statement at a time - # (typically means one line in TOML source) - while True: - # 1. Skip line leading whitespace - pos = skip_chars(src, pos, TOML_WS) - - # 2. Parse rules. Expect one of the following: - # - end of file - # - end of line - # - comment - # - key/value pair - # - append dict to list (and move to its namespace) - # - create dict (and move to its namespace) - # Skip trailing whitespace when applicable. - try: - char = src[pos] - except IndexError: - break - if char == "\n": - pos += 1 - continue - if char in KEY_INITIAL_CHARS: - pos = key_value_rule(src, pos, out, header, parse_float) - pos = skip_chars(src, pos, TOML_WS) - elif char == "[": - try: - second_char: str | None = src[pos + 1] - except IndexError: - second_char = None - out.flags.finalize_pending() - if second_char == "[": - pos, header = create_list_rule(src, pos, out) - else: - pos, header = create_dict_rule(src, pos, out) - pos = skip_chars(src, pos, TOML_WS) - elif char != "#": - raise suffixed_err(src, pos, "Invalid statement") - - # 3. Skip comment - pos = skip_comment(src, pos) - - # 4. Expect end of line or end of file - try: - char = src[pos] - except IndexError: - break - if char != "\n": - raise suffixed_err( - src, pos, "Expected newline or end of document after a statement" - ) - pos += 1 - - return out.data.dict - - -class Flags: - """Flags that map to parsed keys/namespaces.""" - - # Marks an immutable namespace (inline array or inline table). - FROZEN = 0 - # Marks a nest that has been explicitly created and can no longer - # be opened using the "[table]" syntax. - EXPLICIT_NEST = 1 - - def __init__(self) -> None: - self._flags: dict[str, dict] = {} - self._pending_flags: set[tuple[Key, int]] = set() - - def add_pending(self, key: Key, flag: int) -> None: - self._pending_flags.add((key, flag)) - - def finalize_pending(self) -> None: - for key, flag in self._pending_flags: - self.set(key, flag, recursive=False) - self._pending_flags.clear() - - def unset_all(self, key: Key) -> None: - cont = self._flags - for k in key[:-1]: - if k not in cont: - return - cont = cont[k]["nested"] - cont.pop(key[-1], None) - - def set(self, key: Key, flag: int, *, recursive: bool) -> None: # noqa: A003 - cont = self._flags - key_parent, key_stem = key[:-1], key[-1] - for k in key_parent: - if k not in cont: - cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}} - cont = cont[k]["nested"] - if key_stem not in cont: - cont[key_stem] = {"flags": set(), "recursive_flags": set(), "nested": {}} - cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag) - - def is_(self, key: Key, flag: int) -> bool: - if not key: - return False # document root has no flags - cont = self._flags - for k in key[:-1]: - if k not in cont: - return False - inner_cont = cont[k] - if flag in inner_cont["recursive_flags"]: - return True - cont = inner_cont["nested"] - key_stem = key[-1] - if key_stem in cont: - cont = cont[key_stem] - return flag in cont["flags"] or flag in cont["recursive_flags"] - return False - - -class NestedDict: - def __init__(self) -> None: - # The parsed content of the TOML document - self.dict: dict[str, Any] = {} - - def get_or_create_nest( - self, - key: Key, - *, - access_lists: bool = True, - ) -> dict: - cont: Any = self.dict - for k in key: - if k not in cont: - cont[k] = {} - cont = cont[k] - if access_lists and isinstance(cont, list): - cont = cont[-1] - if not isinstance(cont, dict): - raise KeyError("There is no nest behind this key") - return cont - - def append_nest_to_list(self, key: Key) -> None: - cont = self.get_or_create_nest(key[:-1]) - last_key = key[-1] - if last_key in cont: - list_ = cont[last_key] - if not isinstance(list_, list): - raise KeyError("An object other than list found behind this key") - list_.append({}) - else: - cont[last_key] = [{}] - - -class Output(NamedTuple): - data: NestedDict - flags: Flags - - -def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos: - try: - while src[pos] in chars: - pos += 1 - except IndexError: - pass - return pos - - -def skip_until( - src: str, - pos: Pos, - expect: str, - *, - error_on: frozenset[str], - error_on_eof: bool, -) -> Pos: - try: - new_pos = src.index(expect, pos) - except ValueError: - new_pos = len(src) - if error_on_eof: - raise suffixed_err(src, new_pos, f"Expected {expect!r}") from None - - if not error_on.isdisjoint(src[pos:new_pos]): - while src[pos] not in error_on: - pos += 1 - raise suffixed_err(src, pos, f"Found invalid character {src[pos]!r}") - return new_pos - - -def skip_comment(src: str, pos: Pos) -> Pos: - try: - char: str | None = src[pos] - except IndexError: - char = None - if char == "#": - return skip_until( - src, pos + 1, "\n", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False - ) - return pos - - -def skip_comments_and_array_ws(src: str, pos: Pos) -> Pos: - while True: - pos_before_skip = pos - pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE) - pos = skip_comment(src, pos) - if pos == pos_before_skip: - return pos - - -def create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]: - pos += 1 # Skip "[" - pos = skip_chars(src, pos, TOML_WS) - pos, key = parse_key(src, pos) - - if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN): - raise suffixed_err(src, pos, f"Cannot declare {key} twice") - out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False) - try: - out.data.get_or_create_nest(key) - except KeyError: - raise suffixed_err(src, pos, "Cannot overwrite a value") from None - - if not src.startswith("]", pos): - raise suffixed_err(src, pos, "Expected ']' at the end of a table declaration") - return pos + 1, key - - -def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]: - pos += 2 # Skip "[[" - pos = skip_chars(src, pos, TOML_WS) - pos, key = parse_key(src, pos) - - if out.flags.is_(key, Flags.FROZEN): - raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}") - # Free the namespace now that it points to another empty list item... - out.flags.unset_all(key) - # ...but this key precisely is still prohibited from table declaration - out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False) - try: - out.data.append_nest_to_list(key) - except KeyError: - raise suffixed_err(src, pos, "Cannot overwrite a value") from None - - if not src.startswith("]]", pos): - raise suffixed_err(src, pos, "Expected ']]' at the end of an array declaration") - return pos + 2, key - - -def key_value_rule( - src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat -) -> Pos: - pos, key, value = parse_key_value_pair(src, pos, parse_float) - key_parent, key_stem = key[:-1], key[-1] - abs_key_parent = header + key_parent - - relative_path_cont_keys = (header + key[:i] for i in range(1, len(key))) - for cont_key in relative_path_cont_keys: - # Check that dotted key syntax does not redefine an existing table - if out.flags.is_(cont_key, Flags.EXPLICIT_NEST): - raise suffixed_err(src, pos, f"Cannot redefine namespace {cont_key}") - # Containers in the relative path can't be opened with the table syntax or - # dotted key/value syntax in following table sections. - out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST) - - if out.flags.is_(abs_key_parent, Flags.FROZEN): - raise suffixed_err( - src, pos, f"Cannot mutate immutable namespace {abs_key_parent}" - ) - - try: - nest = out.data.get_or_create_nest(abs_key_parent) - except KeyError: - raise suffixed_err(src, pos, "Cannot overwrite a value") from None - if key_stem in nest: - raise suffixed_err(src, pos, "Cannot overwrite a value") - # Mark inline table and array namespaces recursively immutable - if isinstance(value, (dict, list)): - out.flags.set(header + key, Flags.FROZEN, recursive=True) - nest[key_stem] = value - return pos - - -def parse_key_value_pair( - src: str, pos: Pos, parse_float: ParseFloat -) -> tuple[Pos, Key, Any]: - pos, key = parse_key(src, pos) - try: - char: str | None = src[pos] - except IndexError: - char = None - if char != "=": - raise suffixed_err(src, pos, "Expected '=' after a key in a key/value pair") - pos += 1 - pos = skip_chars(src, pos, TOML_WS) - pos, value = parse_value(src, pos, parse_float) - return pos, key, value - - -def parse_key(src: str, pos: Pos) -> tuple[Pos, Key]: - pos, key_part = parse_key_part(src, pos) - key: Key = (key_part,) - pos = skip_chars(src, pos, TOML_WS) - while True: - try: - char: str | None = src[pos] - except IndexError: - char = None - if char != ".": - return pos, key - pos += 1 - pos = skip_chars(src, pos, TOML_WS) - pos, key_part = parse_key_part(src, pos) - key += (key_part,) - pos = skip_chars(src, pos, TOML_WS) - - -def parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]: - try: - char: str | None = src[pos] - except IndexError: - char = None - if char in BARE_KEY_CHARS: - start_pos = pos - pos = skip_chars(src, pos, BARE_KEY_CHARS) - return pos, src[start_pos:pos] - if char == "'": - return parse_literal_str(src, pos) - if char == '"': - return parse_one_line_basic_str(src, pos) - raise suffixed_err(src, pos, "Invalid initial character for a key part") - - -def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]: - pos += 1 - return parse_basic_str(src, pos, multiline=False) - - -def parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]: - pos += 1 - array: list = [] - - pos = skip_comments_and_array_ws(src, pos) - if src.startswith("]", pos): - return pos + 1, array - while True: - pos, val = parse_value(src, pos, parse_float) - array.append(val) - pos = skip_comments_and_array_ws(src, pos) - - c = src[pos : pos + 1] - if c == "]": - return pos + 1, array - if c != ",": - raise suffixed_err(src, pos, "Unclosed array") - pos += 1 - - pos = skip_comments_and_array_ws(src, pos) - if src.startswith("]", pos): - return pos + 1, array - - -def parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, dict]: - pos += 1 - nested_dict = NestedDict() - flags = Flags() - - pos = skip_chars(src, pos, TOML_WS) - if src.startswith("}", pos): - return pos + 1, nested_dict.dict - while True: - pos, key, value = parse_key_value_pair(src, pos, parse_float) - key_parent, key_stem = key[:-1], key[-1] - if flags.is_(key, Flags.FROZEN): - raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}") - try: - nest = nested_dict.get_or_create_nest(key_parent, access_lists=False) - except KeyError: - raise suffixed_err(src, pos, "Cannot overwrite a value") from None - if key_stem in nest: - raise suffixed_err(src, pos, f"Duplicate inline table key {key_stem!r}") - nest[key_stem] = value - pos = skip_chars(src, pos, TOML_WS) - c = src[pos : pos + 1] - if c == "}": - return pos + 1, nested_dict.dict - if c != ",": - raise suffixed_err(src, pos, "Unclosed inline table") - if isinstance(value, (dict, list)): - flags.set(key, Flags.FROZEN, recursive=True) - pos += 1 - pos = skip_chars(src, pos, TOML_WS) - - -def parse_basic_str_escape( - src: str, pos: Pos, *, multiline: bool = False -) -> tuple[Pos, str]: - escape_id = src[pos : pos + 2] - pos += 2 - if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}: - # Skip whitespace until next non-whitespace character or end of - # the doc. Error if non-whitespace is found before newline. - if escape_id != "\\\n": - pos = skip_chars(src, pos, TOML_WS) - try: - char = src[pos] - except IndexError: - return pos, "" - if char != "\n": - raise suffixed_err(src, pos, "Unescaped '\\' in a string") - pos += 1 - pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE) - return pos, "" - if escape_id == "\\u": - return parse_hex_char(src, pos, 4) - if escape_id == "\\U": - return parse_hex_char(src, pos, 8) - try: - return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id] - except KeyError: - raise suffixed_err(src, pos, "Unescaped '\\' in a string") from None - - -def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]: - return parse_basic_str_escape(src, pos, multiline=True) - - -def parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]: - hex_str = src[pos : pos + hex_len] - if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str): - raise suffixed_err(src, pos, "Invalid hex value") - pos += hex_len - hex_int = int(hex_str, 16) - if not is_unicode_scalar_value(hex_int): - raise suffixed_err(src, pos, "Escaped character is not a Unicode scalar value") - return pos, chr(hex_int) - - -def parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]: - pos += 1 # Skip starting apostrophe - start_pos = pos - pos = skip_until( - src, pos, "'", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True - ) - return pos + 1, src[start_pos:pos] # Skip ending apostrophe - - -def parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]: - pos += 3 - if src.startswith("\n", pos): - pos += 1 - - if literal: - delim = "'" - end_pos = skip_until( - src, - pos, - "'''", - error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS, - error_on_eof=True, - ) - result = src[pos:end_pos] - pos = end_pos + 3 - else: - delim = '"' - pos, result = parse_basic_str(src, pos, multiline=True) - - # Add at maximum two extra apostrophes/quotes if the end sequence - # is 4 or 5 chars long instead of just 3. - if not src.startswith(delim, pos): - return pos, result - pos += 1 - if not src.startswith(delim, pos): - return pos, result + delim - pos += 1 - return pos, result + (delim * 2) - - -def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]: - if multiline: - error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS - parse_escapes = parse_basic_str_escape_multiline - else: - error_on = ILLEGAL_BASIC_STR_CHARS - parse_escapes = parse_basic_str_escape - result = "" - start_pos = pos - while True: - try: - char = src[pos] - except IndexError: - raise suffixed_err(src, pos, "Unterminated string") from None - if char == '"': - if not multiline: - return pos + 1, result + src[start_pos:pos] - if src.startswith('"""', pos): - return pos + 3, result + src[start_pos:pos] - pos += 1 - continue - if char == "\\": - result += src[start_pos:pos] - pos, parsed_escape = parse_escapes(src, pos) - result += parsed_escape - start_pos = pos - continue - if char in error_on: - raise suffixed_err(src, pos, f"Illegal character {char!r}") - pos += 1 - - -def parse_value( # noqa: C901 - src: str, pos: Pos, parse_float: ParseFloat -) -> tuple[Pos, Any]: - try: - char: str | None = src[pos] - except IndexError: - char = None - - # IMPORTANT: order conditions based on speed of checking and likelihood - - # Basic strings - if char == '"': - if src.startswith('"""', pos): - return parse_multiline_str(src, pos, literal=False) - return parse_one_line_basic_str(src, pos) - - # Literal strings - if char == "'": - if src.startswith("'''", pos): - return parse_multiline_str(src, pos, literal=True) - return parse_literal_str(src, pos) - - # Booleans - if char == "t": - if src.startswith("true", pos): - return pos + 4, True - if char == "f": - if src.startswith("false", pos): - return pos + 5, False - - # Arrays - if char == "[": - return parse_array(src, pos, parse_float) - - # Inline tables - if char == "{": - return parse_inline_table(src, pos, parse_float) - - # Dates and times - datetime_match = RE_DATETIME.match(src, pos) - if datetime_match: - try: - datetime_obj = match_to_datetime(datetime_match) - except ValueError as e: - raise suffixed_err(src, pos, "Invalid date or datetime") from e - return datetime_match.end(), datetime_obj - localtime_match = RE_LOCALTIME.match(src, pos) - if localtime_match: - return localtime_match.end(), match_to_localtime(localtime_match) - - # Integers and "normal" floats. - # The regex will greedily match any type starting with a decimal - # char, so needs to be located after handling of dates and times. - number_match = RE_NUMBER.match(src, pos) - if number_match: - return number_match.end(), match_to_number(number_match, parse_float) - - # Special floats - first_three = src[pos : pos + 3] - if first_three in {"inf", "nan"}: - return pos + 3, parse_float(first_three) - first_four = src[pos : pos + 4] - if first_four in {"-inf", "+inf", "-nan", "+nan"}: - return pos + 4, parse_float(first_four) - - raise suffixed_err(src, pos, "Invalid value") - - -def suffixed_err(src: str, pos: Pos, msg: str) -> TOMLDecodeError: - """Return a `TOMLDecodeError` where error message is suffixed with - coordinates in source.""" - - def coord_repr(src: str, pos: Pos) -> str: - if pos >= len(src): - return "end of document" - line = src.count("\n", 0, pos) + 1 - if line == 1: - column = pos + 1 - else: - column = pos - src.rindex("\n", 0, pos) - return f"line {line}, column {column}" - - return TOMLDecodeError(f"{msg} (at {coord_repr(src, pos)})") - - -def is_unicode_scalar_value(codepoint: int) -> bool: - return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111) - - -def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat: - """A decorator to make `parse_float` safe. - - `parse_float` must not return dicts or lists, because these types - would be mixed with parsed TOML tables and arrays, thus confusing - the parser. The returned decorated callable raises `ValueError` - instead of returning illegal types. - """ - # The default `float` callable never returns illegal types. Optimize it. - if parse_float is float: # type: ignore[comparison-overlap] - return float - - def safe_parse_float(float_str: str) -> Any: - float_value = parse_float(float_str) - if isinstance(float_value, (dict, list)): - raise ValueError("parse_float must not return dicts or lists") - return float_value - - return safe_parse_float diff --git a/spaces/BigSalmon/Paraphrase/app.py b/spaces/BigSalmon/Paraphrase/app.py deleted file mode 100644 index 7497d2f8a25e9f20cf7b93b9dfffe3508f59122b..0000000000000000000000000000000000000000 --- a/spaces/BigSalmon/Paraphrase/app.py +++ /dev/null @@ -1,41 +0,0 @@ -import torch -from transformers import T5ForConditionalGeneration, AutoTokenizer, AutoModelForSeq2SeqLM -import streamlit as st -st.title("Paraphrase") -model_name = st.text_input("Pick a Model", "geckos/pegasus-fined-tuned-on-paraphrase") -model = AutoModelForSeq2SeqLM.from_pretrained(model_name) -tokenizer = AutoTokenizer.from_pretrained("geckos/pegasus-fined-tuned-on-paraphrase") - -device = torch.device("cuda" if torch.cuda.is_available() else "cpu") -model = model.to(device) -temp = st.sidebar.slider("Temperature", 0.7, 1.5) -number_of_outputs = st.sidebar.slider("Number of Outputs", 1, 10) - -def translate_to_english(model, tokenizer, text): - translated_text = [] - text = text + " " - encoding = tokenizer.encode_plus(text,pad_to_max_length=True, return_tensors="pt") - input_ids, attention_masks = encoding["input_ids"].to(device), encoding["attention_mask"].to(device) - beam_outputs = model.generate( - input_ids=input_ids, attention_mask=attention_masks, - do_sample=True, - max_length=256, - temperature = temp, - top_k=120, - top_p=0.98, - early_stopping=True, - num_return_sequences=number_of_outputs, - ) - for beam_output in beam_outputs: - sent = tokenizer.decode(beam_output, skip_special_tokens=True,clean_up_tokenization_spaces=True) - print(sent) - translated_text.append(sent) - return translated_text - -text = st.text_input("Okay") -st.text("What you wrote: ") -st.write(text) -st.text("Output: ") -if text: - translated_text = translate_to_english(model, tokenizer, text) - st.write(translated_text if translated_text else "No translation found") diff --git a/spaces/CVPR/Bamboo_ViT-B16_demo/app.py b/spaces/CVPR/Bamboo_ViT-B16_demo/app.py deleted file mode 100644 index f03981129ed996ef72c778f0694bbbc7410849df..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Bamboo_ViT-B16_demo/app.py +++ /dev/null @@ -1,105 +0,0 @@ -import argparse -import requests -import gradio as gr -import numpy as np -import cv2 -import torch -import torch.nn as nn -from PIL import Image -import torchvision -from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD -from timm.data import create_transform - -from timmvit import timmvit -import json -from timm.models.hub import download_cached_file -from PIL import Image - -def pil_loader(filepath): - with Image.open(filepath) as img: - img = img.convert('RGB') - return img - -def build_transforms(input_size, center_crop=True): - transform = torchvision.transforms.Compose([ - torchvision.transforms.ToPILImage(), - torchvision.transforms.Resize(input_size * 8 // 7), - torchvision.transforms.CenterCrop(input_size), - torchvision.transforms.ToTensor(), - torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) - ]) - return transform - -# Download human-readable labels for Bamboo. -with open('./trainid2name.json') as f: - id2name = json.load(f) - - -''' -build model -''' -model = timmvit(pretrain_path='./Bamboo_v0-1_ViT-B16.pth.tar.convert') -model.eval() - -''' -borrow code from here: https://github.com/jacobgil/pytorch-grad-cam/blob/master/pytorch_grad_cam/utils/image.py -''' -def show_cam_on_image(img: np.ndarray, - mask: np.ndarray, - use_rgb: bool = False, - colormap: int = cv2.COLORMAP_JET) -> np.ndarray: - """ This function overlays the cam mask on the image as an heatmap. - By default the heatmap is in BGR format. - :param img: The base image in RGB or BGR format. - :param mask: The cam mask. - :param use_rgb: Whether to use an RGB or BGR heatmap, this should be set to True if 'img' is in RGB format. - :param colormap: The OpenCV colormap to be used. - :returns: The default image with the cam overlay. - """ - heatmap = cv2.applyColorMap(np.uint8(255 * mask), colormap) - if use_rgb: - heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) - heatmap = np.float32(heatmap) / 255 - - if np.max(img) > 1: - raise Exception( - "The input image should np.float32 in the range [0, 1]") - - cam = 0.7*heatmap + 0.3*img - # cam = cam / np.max(cam) - return np.uint8(255 * cam) - - - - -def recognize_image(image): - img_t = eval_transforms(image) - # compute output - output = model(img_t.unsqueeze(0)) - prediction = output.softmax(-1).flatten() - _,top5_idx = torch.topk(prediction, 5) - return {id2name[str(i)][0]: float(prediction[i]) for i in top5_idx.tolist()} - -eval_transforms = build_transforms(224) - - -image = gr.inputs.Image() -label = gr.outputs.Label(num_top_classes=5) - -gr.Interface( - description="Bamboo for Image Recognition Demo (https://github.com/Davidzhangyuanhan/Bamboo). Bamboo knows what this object is and what you are doing in a very fine-grain granularity: fratercula arctica (fig.5) and dribbler (fig.2)).", - fn=recognize_image, - inputs=["image"], - outputs=[ - label, - ], - examples=[ - ["./examples/playing_mahjong.jpg"], - ["./examples/dribbler.jpg"], - ["./examples/Ferrari-F355.jpg"], - ["./examples/northern_oriole.jpg"], - ["./examples/fratercula_arctica.jpg"], - ["./examples/husky.jpg"], - ["./examples/taraxacum_erythrospermum.jpg"], - ], -).launch() \ No newline at end of file diff --git a/spaces/CVPR/LIVE/pybind11/.github/ISSUE_TEMPLATE/feature-request.md b/spaces/CVPR/LIVE/pybind11/.github/ISSUE_TEMPLATE/feature-request.md deleted file mode 100644 index 5f6ec81ec972b13e38520ef2e37d85022c2642c9..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/.github/ISSUE_TEMPLATE/feature-request.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: Feature Request -about: File an issue about adding a feature -title: "[FEAT] " ---- - - -Make sure you've completed the following steps before submitting your issue -- thank you! - -1. Check if your feature has already been mentioned / rejected / planned in other issues. -2. If those resources didn't help, consider asking in the [Gitter chat room][] to see if this is interesting / useful to a larger audience and possible to implement reasonably, -4. If you have a useful feature that passes the previous items (or not suitable for chat), please fill in the details below. - -[Gitter chat room]: https://gitter.im/pybind/Lobby - -*After reading, remove this checklist.* diff --git a/spaces/CVPR/WALT/mmdet/models/backbones/resnet.py b/spaces/CVPR/WALT/mmdet/models/backbones/resnet.py deleted file mode 100644 index 3826815a6d94fdc4c54001d4c186d10ca3380e80..0000000000000000000000000000000000000000 --- a/spaces/CVPR/WALT/mmdet/models/backbones/resnet.py +++ /dev/null @@ -1,663 +0,0 @@ -import torch.nn as nn -import torch.utils.checkpoint as cp -from mmcv.cnn import (build_conv_layer, build_norm_layer, build_plugin_layer, - constant_init, kaiming_init) -from mmcv.runner import load_checkpoint -from torch.nn.modules.batchnorm import _BatchNorm - -from mmdet.utils import get_root_logger -from ..builder import BACKBONES -from ..utils import ResLayer - - -class BasicBlock(nn.Module): - expansion = 1 - - def __init__(self, - inplanes, - planes, - stride=1, - dilation=1, - downsample=None, - style='pytorch', - with_cp=False, - conv_cfg=None, - norm_cfg=dict(type='BN'), - dcn=None, - plugins=None): - super(BasicBlock, self).__init__() - assert dcn is None, 'Not implemented yet.' - assert plugins is None, 'Not implemented yet.' - - self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) - self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2) - - self.conv1 = build_conv_layer( - conv_cfg, - inplanes, - planes, - 3, - stride=stride, - padding=dilation, - dilation=dilation, - bias=False) - self.add_module(self.norm1_name, norm1) - self.conv2 = build_conv_layer( - conv_cfg, planes, planes, 3, padding=1, bias=False) - self.add_module(self.norm2_name, norm2) - - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - self.stride = stride - self.dilation = dilation - self.with_cp = with_cp - - @property - def norm1(self): - """nn.Module: normalization layer after the first convolution layer""" - return getattr(self, self.norm1_name) - - @property - def norm2(self): - """nn.Module: normalization layer after the second convolution layer""" - return getattr(self, self.norm2_name) - - def forward(self, x): - """Forward function.""" - - def _inner_forward(x): - identity = x - - out = self.conv1(x) - out = self.norm1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.norm2(out) - - if self.downsample is not None: - identity = self.downsample(x) - - out += identity - - return out - - if self.with_cp and x.requires_grad: - out = cp.checkpoint(_inner_forward, x) - else: - out = _inner_forward(x) - - out = self.relu(out) - - return out - - -class Bottleneck(nn.Module): - expansion = 4 - - def __init__(self, - inplanes, - planes, - stride=1, - dilation=1, - downsample=None, - style='pytorch', - with_cp=False, - conv_cfg=None, - norm_cfg=dict(type='BN'), - dcn=None, - plugins=None): - """Bottleneck block for ResNet. - - If style is "pytorch", the stride-two layer is the 3x3 conv layer, if - it is "caffe", the stride-two layer is the first 1x1 conv layer. - """ - super(Bottleneck, self).__init__() - assert style in ['pytorch', 'caffe'] - assert dcn is None or isinstance(dcn, dict) - assert plugins is None or isinstance(plugins, list) - if plugins is not None: - allowed_position = ['after_conv1', 'after_conv2', 'after_conv3'] - assert all(p['position'] in allowed_position for p in plugins) - - self.inplanes = inplanes - self.planes = planes - self.stride = stride - self.dilation = dilation - self.style = style - self.with_cp = with_cp - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.dcn = dcn - self.with_dcn = dcn is not None - self.plugins = plugins - self.with_plugins = plugins is not None - - if self.with_plugins: - # collect plugins for conv1/conv2/conv3 - self.after_conv1_plugins = [ - plugin['cfg'] for plugin in plugins - if plugin['position'] == 'after_conv1' - ] - self.after_conv2_plugins = [ - plugin['cfg'] for plugin in plugins - if plugin['position'] == 'after_conv2' - ] - self.after_conv3_plugins = [ - plugin['cfg'] for plugin in plugins - if plugin['position'] == 'after_conv3' - ] - - if self.style == 'pytorch': - self.conv1_stride = 1 - self.conv2_stride = stride - else: - self.conv1_stride = stride - self.conv2_stride = 1 - - self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) - self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2) - self.norm3_name, norm3 = build_norm_layer( - norm_cfg, planes * self.expansion, postfix=3) - - self.conv1 = build_conv_layer( - conv_cfg, - inplanes, - planes, - kernel_size=1, - stride=self.conv1_stride, - bias=False) - self.add_module(self.norm1_name, norm1) - fallback_on_stride = False - if self.with_dcn: - fallback_on_stride = dcn.pop('fallback_on_stride', False) - if not self.with_dcn or fallback_on_stride: - self.conv2 = build_conv_layer( - conv_cfg, - planes, - planes, - kernel_size=3, - stride=self.conv2_stride, - padding=dilation, - dilation=dilation, - bias=False) - else: - assert self.conv_cfg is None, 'conv_cfg must be None for DCN' - self.conv2 = build_conv_layer( - dcn, - planes, - planes, - kernel_size=3, - stride=self.conv2_stride, - padding=dilation, - dilation=dilation, - bias=False) - - self.add_module(self.norm2_name, norm2) - self.conv3 = build_conv_layer( - conv_cfg, - planes, - planes * self.expansion, - kernel_size=1, - bias=False) - self.add_module(self.norm3_name, norm3) - - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - - if self.with_plugins: - self.after_conv1_plugin_names = self.make_block_plugins( - planes, self.after_conv1_plugins) - self.after_conv2_plugin_names = self.make_block_plugins( - planes, self.after_conv2_plugins) - self.after_conv3_plugin_names = self.make_block_plugins( - planes * self.expansion, self.after_conv3_plugins) - - def make_block_plugins(self, in_channels, plugins): - """make plugins for block. - - Args: - in_channels (int): Input channels of plugin. - plugins (list[dict]): List of plugins cfg to build. - - Returns: - list[str]: List of the names of plugin. - """ - assert isinstance(plugins, list) - plugin_names = [] - for plugin in plugins: - plugin = plugin.copy() - name, layer = build_plugin_layer( - plugin, - in_channels=in_channels, - postfix=plugin.pop('postfix', '')) - assert not hasattr(self, name), f'duplicate plugin {name}' - self.add_module(name, layer) - plugin_names.append(name) - return plugin_names - - def forward_plugin(self, x, plugin_names): - out = x - for name in plugin_names: - out = getattr(self, name)(x) - return out - - @property - def norm1(self): - """nn.Module: normalization layer after the first convolution layer""" - return getattr(self, self.norm1_name) - - @property - def norm2(self): - """nn.Module: normalization layer after the second convolution layer""" - return getattr(self, self.norm2_name) - - @property - def norm3(self): - """nn.Module: normalization layer after the third convolution layer""" - return getattr(self, self.norm3_name) - - def forward(self, x): - """Forward function.""" - - def _inner_forward(x): - identity = x - out = self.conv1(x) - out = self.norm1(out) - out = self.relu(out) - - if self.with_plugins: - out = self.forward_plugin(out, self.after_conv1_plugin_names) - - out = self.conv2(out) - out = self.norm2(out) - out = self.relu(out) - - if self.with_plugins: - out = self.forward_plugin(out, self.after_conv2_plugin_names) - - out = self.conv3(out) - out = self.norm3(out) - - if self.with_plugins: - out = self.forward_plugin(out, self.after_conv3_plugin_names) - - if self.downsample is not None: - identity = self.downsample(x) - - out += identity - - return out - - if self.with_cp and x.requires_grad: - out = cp.checkpoint(_inner_forward, x) - else: - out = _inner_forward(x) - - out = self.relu(out) - - return out - - -@BACKBONES.register_module() -class ResNet(nn.Module): - """ResNet backbone. - - Args: - depth (int): Depth of resnet, from {18, 34, 50, 101, 152}. - stem_channels (int | None): Number of stem channels. If not specified, - it will be the same as `base_channels`. Default: None. - base_channels (int): Number of base channels of res layer. Default: 64. - in_channels (int): Number of input image channels. Default: 3. - num_stages (int): Resnet stages. Default: 4. - strides (Sequence[int]): Strides of the first block of each stage. - dilations (Sequence[int]): Dilation of each stage. - out_indices (Sequence[int]): Output from which stages. - style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two - layer is the 3x3 conv layer, otherwise the stride-two layer is - the first 1x1 conv layer. - deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv - avg_down (bool): Use AvgPool instead of stride conv when - downsampling in the bottleneck. - frozen_stages (int): Stages to be frozen (stop grad and set eval mode). - -1 means not freezing any parameters. - norm_cfg (dict): Dictionary to construct and config norm layer. - norm_eval (bool): Whether to set norm layers to eval mode, namely, - freeze running stats (mean and var). Note: Effect on Batch Norm - and its variants only. - plugins (list[dict]): List of plugins for stages, each dict contains: - - - cfg (dict, required): Cfg dict to build plugin. - - position (str, required): Position inside block to insert - plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'. - - stages (tuple[bool], optional): Stages to apply plugin, length - should be same as 'num_stages'. - with_cp (bool): Use checkpoint or not. Using checkpoint will save some - memory while slowing down the training speed. - zero_init_residual (bool): Whether to use zero init for last norm layer - in resblocks to let them behave as identity. - - Example: - >>> from mmdet.models import ResNet - >>> import torch - >>> self = ResNet(depth=18) - >>> self.eval() - >>> inputs = torch.rand(1, 3, 32, 32) - >>> level_outputs = self.forward(inputs) - >>> for level_out in level_outputs: - ... print(tuple(level_out.shape)) - (1, 64, 8, 8) - (1, 128, 4, 4) - (1, 256, 2, 2) - (1, 512, 1, 1) - """ - - arch_settings = { - 18: (BasicBlock, (2, 2, 2, 2)), - 34: (BasicBlock, (3, 4, 6, 3)), - 50: (Bottleneck, (3, 4, 6, 3)), - 101: (Bottleneck, (3, 4, 23, 3)), - 152: (Bottleneck, (3, 8, 36, 3)) - } - - def __init__(self, - depth, - in_channels=3, - stem_channels=None, - base_channels=64, - num_stages=4, - strides=(1, 2, 2, 2), - dilations=(1, 1, 1, 1), - out_indices=(0, 1, 2, 3), - style='pytorch', - deep_stem=False, - avg_down=False, - frozen_stages=-1, - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True), - norm_eval=True, - dcn=None, - stage_with_dcn=(False, False, False, False), - plugins=None, - with_cp=False, - zero_init_residual=True): - super(ResNet, self).__init__() - if depth not in self.arch_settings: - raise KeyError(f'invalid depth {depth} for resnet') - self.depth = depth - if stem_channels is None: - stem_channels = base_channels - self.stem_channels = stem_channels - self.base_channels = base_channels - self.num_stages = num_stages - assert num_stages >= 1 and num_stages <= 4 - self.strides = strides - self.dilations = dilations - assert len(strides) == len(dilations) == num_stages - self.out_indices = out_indices - assert max(out_indices) < num_stages - self.style = style - self.deep_stem = deep_stem - self.avg_down = avg_down - self.frozen_stages = frozen_stages - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.with_cp = with_cp - self.norm_eval = norm_eval - self.dcn = dcn - self.stage_with_dcn = stage_with_dcn - if dcn is not None: - assert len(stage_with_dcn) == num_stages - self.plugins = plugins - self.zero_init_residual = zero_init_residual - self.block, stage_blocks = self.arch_settings[depth] - self.stage_blocks = stage_blocks[:num_stages] - self.inplanes = stem_channels - - self._make_stem_layer(in_channels, stem_channels) - - self.res_layers = [] - for i, num_blocks in enumerate(self.stage_blocks): - stride = strides[i] - dilation = dilations[i] - dcn = self.dcn if self.stage_with_dcn[i] else None - if plugins is not None: - stage_plugins = self.make_stage_plugins(plugins, i) - else: - stage_plugins = None - planes = base_channels * 2**i - res_layer = self.make_res_layer( - block=self.block, - inplanes=self.inplanes, - planes=planes, - num_blocks=num_blocks, - stride=stride, - dilation=dilation, - style=self.style, - avg_down=self.avg_down, - with_cp=with_cp, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - dcn=dcn, - plugins=stage_plugins) - self.inplanes = planes * self.block.expansion - layer_name = f'layer{i + 1}' - self.add_module(layer_name, res_layer) - self.res_layers.append(layer_name) - - self._freeze_stages() - - self.feat_dim = self.block.expansion * base_channels * 2**( - len(self.stage_blocks) - 1) - - def make_stage_plugins(self, plugins, stage_idx): - """Make plugins for ResNet ``stage_idx`` th stage. - - Currently we support to insert ``context_block``, - ``empirical_attention_block``, ``nonlocal_block`` into the backbone - like ResNet/ResNeXt. They could be inserted after conv1/conv2/conv3 of - Bottleneck. - - An example of plugins format could be: - - Examples: - >>> plugins=[ - ... dict(cfg=dict(type='xxx', arg1='xxx'), - ... stages=(False, True, True, True), - ... position='after_conv2'), - ... dict(cfg=dict(type='yyy'), - ... stages=(True, True, True, True), - ... position='after_conv3'), - ... dict(cfg=dict(type='zzz', postfix='1'), - ... stages=(True, True, True, True), - ... position='after_conv3'), - ... dict(cfg=dict(type='zzz', postfix='2'), - ... stages=(True, True, True, True), - ... position='after_conv3') - ... ] - >>> self = ResNet(depth=18) - >>> stage_plugins = self.make_stage_plugins(plugins, 0) - >>> assert len(stage_plugins) == 3 - - Suppose ``stage_idx=0``, the structure of blocks in the stage would be: - - .. code-block:: none - - conv1-> conv2->conv3->yyy->zzz1->zzz2 - - Suppose 'stage_idx=1', the structure of blocks in the stage would be: - - .. code-block:: none - - conv1-> conv2->xxx->conv3->yyy->zzz1->zzz2 - - If stages is missing, the plugin would be applied to all stages. - - Args: - plugins (list[dict]): List of plugins cfg to build. The postfix is - required if multiple same type plugins are inserted. - stage_idx (int): Index of stage to build - - Returns: - list[dict]: Plugins for current stage - """ - stage_plugins = [] - for plugin in plugins: - plugin = plugin.copy() - stages = plugin.pop('stages', None) - assert stages is None or len(stages) == self.num_stages - # whether to insert plugin into current stage - if stages is None or stages[stage_idx]: - stage_plugins.append(plugin) - - return stage_plugins - - def make_res_layer(self, **kwargs): - """Pack all blocks in a stage into a ``ResLayer``.""" - return ResLayer(**kwargs) - - @property - def norm1(self): - """nn.Module: the normalization layer named "norm1" """ - return getattr(self, self.norm1_name) - - def _make_stem_layer(self, in_channels, stem_channels): - if self.deep_stem: - self.stem = nn.Sequential( - build_conv_layer( - self.conv_cfg, - in_channels, - stem_channels // 2, - kernel_size=3, - stride=2, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, stem_channels // 2)[1], - nn.ReLU(inplace=True), - build_conv_layer( - self.conv_cfg, - stem_channels // 2, - stem_channels // 2, - kernel_size=3, - stride=1, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, stem_channels // 2)[1], - nn.ReLU(inplace=True), - build_conv_layer( - self.conv_cfg, - stem_channels // 2, - stem_channels, - kernel_size=3, - stride=1, - padding=1, - bias=False), - build_norm_layer(self.norm_cfg, stem_channels)[1], - nn.ReLU(inplace=True)) - else: - self.conv1 = build_conv_layer( - self.conv_cfg, - in_channels, - stem_channels, - kernel_size=7, - stride=2, - padding=3, - bias=False) - self.norm1_name, norm1 = build_norm_layer( - self.norm_cfg, stem_channels, postfix=1) - self.add_module(self.norm1_name, norm1) - self.relu = nn.ReLU(inplace=True) - self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) - - def _freeze_stages(self): - if self.frozen_stages >= 0: - if self.deep_stem: - self.stem.eval() - for param in self.stem.parameters(): - param.requires_grad = False - else: - self.norm1.eval() - for m in [self.conv1, self.norm1]: - for param in m.parameters(): - param.requires_grad = False - - for i in range(1, self.frozen_stages + 1): - m = getattr(self, f'layer{i}') - m.eval() - for param in m.parameters(): - param.requires_grad = False - - def init_weights(self, pretrained=None): - """Initialize the weights in backbone. - - Args: - pretrained (str, optional): Path to pre-trained weights. - Defaults to None. - """ - if isinstance(pretrained, str): - logger = get_root_logger() - load_checkpoint(self, pretrained, strict=False, logger=logger) - elif pretrained is None: - for m in self.modules(): - if isinstance(m, nn.Conv2d): - kaiming_init(m) - elif isinstance(m, (_BatchNorm, nn.GroupNorm)): - constant_init(m, 1) - - if self.dcn is not None: - for m in self.modules(): - if isinstance(m, Bottleneck) and hasattr( - m.conv2, 'conv_offset'): - constant_init(m.conv2.conv_offset, 0) - - if self.zero_init_residual: - for m in self.modules(): - if isinstance(m, Bottleneck): - constant_init(m.norm3, 0) - elif isinstance(m, BasicBlock): - constant_init(m.norm2, 0) - else: - raise TypeError('pretrained must be a str or None') - - def forward(self, x): - """Forward function.""" - if self.deep_stem: - x = self.stem(x) - else: - x = self.conv1(x) - x = self.norm1(x) - x = self.relu(x) - x = self.maxpool(x) - outs = [] - for i, layer_name in enumerate(self.res_layers): - res_layer = getattr(self, layer_name) - x = res_layer(x) - if i in self.out_indices: - outs.append(x) - return tuple(outs) - - def train(self, mode=True): - """Convert the model into training mode while keep normalization layer - freezed.""" - super(ResNet, self).train(mode) - self._freeze_stages() - if mode and self.norm_eval: - for m in self.modules(): - # trick: eval have effect on BatchNorm only - if isinstance(m, _BatchNorm): - m.eval() - - -@BACKBONES.register_module() -class ResNetV1d(ResNet): - r"""ResNetV1d variant described in `Bag of Tricks - `_. - - Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv in - the input stem with three 3x3 convs. And in the downsampling block, a 2x2 - avg_pool with stride 2 is added before conv, whose stride is changed to 1. - """ - - def __init__(self, **kwargs): - super(ResNetV1d, self).__init__( - deep_stem=True, avg_down=True, **kwargs) diff --git a/spaces/CVPR/regionclip-demo/detectron2/modeling/matcher.py b/spaces/CVPR/regionclip-demo/detectron2/modeling/matcher.py deleted file mode 100644 index 666913f76fb0b9d8a277541716f91872d8246250..0000000000000000000000000000000000000000 --- a/spaces/CVPR/regionclip-demo/detectron2/modeling/matcher.py +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from typing import List -import torch - -from detectron2.layers import nonzero_tuple - - -class Matcher(object): - """ - This class assigns to each predicted "element" (e.g., a box) a ground-truth - element. Each predicted element will have exactly zero or one matches; each - ground-truth element may be matched to zero or more predicted elements. - - The matching is determined by the MxN match_quality_matrix, that characterizes - how well each (ground-truth, prediction)-pair match each other. For example, - if the elements are boxes, this matrix may contain box intersection-over-union - overlap values. - - The matcher returns (a) a vector of length N containing the index of the - ground-truth element m in [0, M) that matches to prediction n in [0, N). - (b) a vector of length N containing the labels for each prediction. - """ - - def __init__( - self, thresholds: List[float], labels: List[int], allow_low_quality_matches: bool = False - ): - """ - Args: - thresholds (list): a list of thresholds used to stratify predictions - into levels. - labels (list): a list of values to label predictions belonging at - each level. A label can be one of {-1, 0, 1} signifying - {ignore, negative class, positive class}, respectively. - allow_low_quality_matches (bool): if True, produce additional matches - for predictions with maximum match quality lower than high_threshold. - See set_low_quality_matches_ for more details. - - For example, - thresholds = [0.3, 0.5] - labels = [0, -1, 1] - All predictions with iou < 0.3 will be marked with 0 and - thus will be considered as false positives while training. - All predictions with 0.3 <= iou < 0.5 will be marked with -1 and - thus will be ignored. - All predictions with 0.5 <= iou will be marked with 1 and - thus will be considered as true positives. - """ - # Add -inf and +inf to first and last position in thresholds - thresholds = thresholds[:] - assert thresholds[0] > 0 - thresholds.insert(0, -float("inf")) - thresholds.append(float("inf")) - # Currently torchscript does not support all + generator - assert all([low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])]) - assert all([l in [-1, 0, 1] for l in labels]) - assert len(labels) == len(thresholds) - 1 - self.thresholds = thresholds - self.labels = labels - self.allow_low_quality_matches = allow_low_quality_matches - - def __call__(self, match_quality_matrix): - """ - Args: - match_quality_matrix (Tensor[float]): an MxN tensor, containing the - pairwise quality between M ground-truth elements and N predicted - elements. All elements must be >= 0 (due to the us of `torch.nonzero` - for selecting indices in :meth:`set_low_quality_matches_`). - - Returns: - matches (Tensor[int64]): a vector of length N, where matches[i] is a matched - ground-truth index in [0, M) - match_labels (Tensor[int8]): a vector of length N, where pred_labels[i] indicates - whether a prediction is a true or false positive or ignored - """ - assert match_quality_matrix.dim() == 2 - if match_quality_matrix.numel() == 0: - default_matches = match_quality_matrix.new_full( - (match_quality_matrix.size(1),), 0, dtype=torch.int64 - ) - # When no gt boxes exist, we define IOU = 0 and therefore set labels - # to `self.labels[0]`, which usually defaults to background class 0 - # To choose to ignore instead, can make labels=[-1,0,-1,1] + set appropriate thresholds - default_match_labels = match_quality_matrix.new_full( - (match_quality_matrix.size(1),), self.labels[0], dtype=torch.int8 - ) - return default_matches, default_match_labels - - assert torch.all(match_quality_matrix >= 0) - - # match_quality_matrix is M (gt) x N (predicted) - # Max over gt elements (dim 0) to find best gt candidate for each prediction - matched_vals, matches = match_quality_matrix.max(dim=0) - - match_labels = matches.new_full(matches.size(), 1, dtype=torch.int8) - - for (l, low, high) in zip(self.labels, self.thresholds[:-1], self.thresholds[1:]): - low_high = (matched_vals >= low) & (matched_vals < high) - match_labels[low_high] = l - - if self.allow_low_quality_matches: - self.set_low_quality_matches_(match_labels, match_quality_matrix) - - return matches, match_labels - - def set_low_quality_matches_(self, match_labels, match_quality_matrix): - """ - Produce additional matches for predictions that have only low-quality matches. - Specifically, for each ground-truth G find the set of predictions that have - maximum overlap with it (including ties); for each prediction in that set, if - it is unmatched, then match it to the ground-truth G. - - This function implements the RPN assignment case (i) in Sec. 3.1.2 of - :paper:`Faster R-CNN`. - """ - # For each gt, find the prediction with which it has highest quality - highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1) - # Find the highest quality match available, even if it is low, including ties. - # Note that the matches qualities must be positive due to the use of - # `torch.nonzero`. - _, pred_inds_with_highest_quality = nonzero_tuple( - match_quality_matrix == highest_quality_foreach_gt[:, None] - ) - # If an anchor was labeled positive only due to a low-quality match - # with gt_A, but it has larger overlap with gt_B, it's matched index will still be gt_B. - # This follows the implementation in Detectron, and is found to have no significant impact. - match_labels[pred_inds_with_highest_quality] = 1 diff --git a/spaces/ChandraMohanNayal/AutoGPT/autogpt/agent/__init__.py b/spaces/ChandraMohanNayal/AutoGPT/autogpt/agent/__init__.py deleted file mode 100644 index e928af2205b1c52d19dc89ec4246e8c1d2c20e3f..0000000000000000000000000000000000000000 --- a/spaces/ChandraMohanNayal/AutoGPT/autogpt/agent/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from autogpt.agent.agent import Agent -from autogpt.agent.agent_manager import AgentManager - -__all__ = ["Agent", "AgentManager"] diff --git a/spaces/Cicooo/vits-uma-genshin-honkai/attentions.py b/spaces/Cicooo/vits-uma-genshin-honkai/attentions.py deleted file mode 100644 index 86bc73b5fe98cc7b443e9078553920346c996707..0000000000000000000000000000000000000000 --- a/spaces/Cicooo/vits-uma-genshin-honkai/attentions.py +++ /dev/null @@ -1,300 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -from modules import LayerNorm - - -class Encoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init)) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels**-0.5 - self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1)) - if self.window_size is not None: - assert t_s == t_t, "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings) - scores_local = self._relative_position_to_absolute_position(rel_logits) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - assert t_s == t_t, "Local attention is only available for self-attention." - block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length) - scores = scores.masked_fill(block_mask == 0, -1e4) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) - output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings) - output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]])) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]])) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]])) - x_flat = x.view([batch, heads, length**2 + length*(length -1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - self.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(x * x_mask)) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/CikeyQI/meme-api/meme_generator/memes/love_you/__init__.py b/spaces/CikeyQI/meme-api/meme_generator/memes/love_you/__init__.py deleted file mode 100644 index 2a579467811e3c8708416f2501c5df26a9fe094e..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/meme-api/meme_generator/memes/love_you/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -from pathlib import Path -from typing import List - -from PIL.Image import Image as IMG -from pil_utils import BuildImage - -from meme_generator import add_meme -from meme_generator.utils import save_gif - -img_dir = Path(__file__).parent / "images" - - -def love_you(images: List[BuildImage], texts, args): - img = images[0].convert("RGBA").square() - frames: List[IMG] = [] - locs = [(68, 65, 70, 70), (63, 59, 80, 80)] - for i in range(2): - heart = BuildImage.open(img_dir / f"{i}.png") - frame = BuildImage.new("RGBA", heart.size, "white") - x, y, w, h = locs[i] - frame.paste(img.resize((w, h)), (x, y), alpha=True).paste(heart, alpha=True) - frames.append(frame.image) - return save_gif(frames, 0.2) - - -add_meme("love_you", love_you, min_images=1, max_images=1, keywords=["永远爱你"]) diff --git a/spaces/Cletrason/dalle2-dreamweddingbooth/README.md b/spaces/Cletrason/dalle2-dreamweddingbooth/README.md deleted file mode 100644 index 97f8b3f009a9c1de1c3481ef75a09340b8732e06..0000000000000000000000000000000000000000 --- a/spaces/Cletrason/dalle2-dreamweddingbooth/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Dalle2 Dreamweddingbooth -emoji: 🔥 -colorFrom: pink -colorTo: indigo -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/CofAI/tv/Dockerfile b/spaces/CofAI/tv/Dockerfile deleted file mode 100644 index 8e670518dbe8c6f90ca81d1aafdda840ebdff7b4..0000000000000000000000000000000000000000 --- a/spaces/CofAI/tv/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -FROM node:18 - - -ARG DEBIAN_FRONTEND=noninteractive - -RUN apt update - -RUN apt --yes install ffmpeg - -# Set up a new user named "user" with user ID 1000 -RUN useradd -o -u 1000 user - -# Switch to the "user" user -USER user - -# Set home to the user's home directory -ENV HOME=/home/user \ - PATH=/home/user/.local/bin:$PATH - -# Set the working directory to the user's home directory -WORKDIR $HOME/app - -# Install app dependencies -# A wildcard is used to ensure both package.json AND package-lock.json are copied -# where available (npm@5+) -COPY --chown=user package*.json $HOME/app - -RUN npm install - -# Copy the current directory contents into the container at $HOME/app setting the owner to the user -COPY --chown=user . $HOME/app - -EXPOSE 7860 1935 8000 - -CMD [ "npm", "run", "start" ] \ No newline at end of file diff --git a/spaces/Cong723/gpt-academic-public/crazy_functions/test_project/python/dqn/policies.py b/spaces/Cong723/gpt-academic-public/crazy_functions/test_project/python/dqn/policies.py deleted file mode 100644 index 4ecf39a5fc04b24ad1b809232b186728366987b6..0000000000000000000000000000000000000000 --- a/spaces/Cong723/gpt-academic-public/crazy_functions/test_project/python/dqn/policies.py +++ /dev/null @@ -1,237 +0,0 @@ -from typing import Any, Dict, List, Optional, Type - -import gym -import torch as th -from torch import nn - -from stable_baselines3.common.policies import BasePolicy, register_policy -from stable_baselines3.common.torch_layers import BaseFeaturesExtractor, FlattenExtractor, NatureCNN, create_mlp -from stable_baselines3.common.type_aliases import Schedule - - -class QNetwork(BasePolicy): - """ - Action-Value (Q-Value) network for DQN - - :param observation_space: Observation space - :param action_space: Action space - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - features_extractor: nn.Module, - features_dim: int, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - normalize_images: bool = True, - ): - super(QNetwork, self).__init__( - observation_space, - action_space, - features_extractor=features_extractor, - normalize_images=normalize_images, - ) - - if net_arch is None: - net_arch = [64, 64] - - self.net_arch = net_arch - self.activation_fn = activation_fn - self.features_extractor = features_extractor - self.features_dim = features_dim - self.normalize_images = normalize_images - action_dim = self.action_space.n # number of actions - q_net = create_mlp(self.features_dim, action_dim, self.net_arch, self.activation_fn) - self.q_net = nn.Sequential(*q_net) - - def forward(self, obs: th.Tensor) -> th.Tensor: - """ - Predict the q-values. - - :param obs: Observation - :return: The estimated Q-Value for each action. - """ - return self.q_net(self.extract_features(obs)) - - def _predict(self, observation: th.Tensor, deterministic: bool = True) -> th.Tensor: - q_values = self.forward(observation) - # Greedy action - action = q_values.argmax(dim=1).reshape(-1) - return action - - def _get_constructor_parameters(self) -> Dict[str, Any]: - data = super()._get_constructor_parameters() - - data.update( - dict( - net_arch=self.net_arch, - features_dim=self.features_dim, - activation_fn=self.activation_fn, - features_extractor=self.features_extractor, - ) - ) - return data - - -class DQNPolicy(BasePolicy): - """ - Policy class with Q-Value Net and target net for DQN - - :param observation_space: Observation space - :param action_space: Action space - :param lr_schedule: Learning rate schedule (could be constant) - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param features_extractor_class: Features extractor to use. - :param features_extractor_kwargs: Keyword arguments - to pass to the features extractor. - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - :param optimizer_class: The optimizer to use, - ``th.optim.Adam`` by default - :param optimizer_kwargs: Additional keyword arguments, - excluding the learning rate, to pass to the optimizer - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - lr_schedule: Schedule, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor, - features_extractor_kwargs: Optional[Dict[str, Any]] = None, - normalize_images: bool = True, - optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam, - optimizer_kwargs: Optional[Dict[str, Any]] = None, - ): - super(DQNPolicy, self).__init__( - observation_space, - action_space, - features_extractor_class, - features_extractor_kwargs, - optimizer_class=optimizer_class, - optimizer_kwargs=optimizer_kwargs, - ) - - if net_arch is None: - if features_extractor_class == FlattenExtractor: - net_arch = [64, 64] - else: - net_arch = [] - - self.net_arch = net_arch - self.activation_fn = activation_fn - self.normalize_images = normalize_images - - self.net_args = { - "observation_space": self.observation_space, - "action_space": self.action_space, - "net_arch": self.net_arch, - "activation_fn": self.activation_fn, - "normalize_images": normalize_images, - } - - self.q_net, self.q_net_target = None, None - self._build(lr_schedule) - - def _build(self, lr_schedule: Schedule) -> None: - """ - Create the network and the optimizer. - - :param lr_schedule: Learning rate schedule - lr_schedule(1) is the initial learning rate - """ - - self.q_net = self.make_q_net() - self.q_net_target = self.make_q_net() - self.q_net_target.load_state_dict(self.q_net.state_dict()) - - # Setup optimizer with initial learning rate - self.optimizer = self.optimizer_class(self.parameters(), lr=lr_schedule(1), **self.optimizer_kwargs) - - def make_q_net(self) -> QNetwork: - # Make sure we always have separate networks for features extractors etc - net_args = self._update_features_extractor(self.net_args, features_extractor=None) - return QNetwork(**net_args).to(self.device) - - def forward(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor: - return self._predict(obs, deterministic=deterministic) - - def _predict(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor: - return self.q_net._predict(obs, deterministic=deterministic) - - def _get_constructor_parameters(self) -> Dict[str, Any]: - data = super()._get_constructor_parameters() - - data.update( - dict( - net_arch=self.net_args["net_arch"], - activation_fn=self.net_args["activation_fn"], - lr_schedule=self._dummy_schedule, # dummy lr schedule, not needed for loading policy alone - optimizer_class=self.optimizer_class, - optimizer_kwargs=self.optimizer_kwargs, - features_extractor_class=self.features_extractor_class, - features_extractor_kwargs=self.features_extractor_kwargs, - ) - ) - return data - - -MlpPolicy = DQNPolicy - - -class CnnPolicy(DQNPolicy): - """ - Policy class for DQN when using images as input. - - :param observation_space: Observation space - :param action_space: Action space - :param lr_schedule: Learning rate schedule (could be constant) - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param features_extractor_class: Features extractor to use. - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - :param optimizer_class: The optimizer to use, - ``th.optim.Adam`` by default - :param optimizer_kwargs: Additional keyword arguments, - excluding the learning rate, to pass to the optimizer - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - lr_schedule: Schedule, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN, - features_extractor_kwargs: Optional[Dict[str, Any]] = None, - normalize_images: bool = True, - optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam, - optimizer_kwargs: Optional[Dict[str, Any]] = None, - ): - super(CnnPolicy, self).__init__( - observation_space, - action_space, - lr_schedule, - net_arch, - activation_fn, - features_extractor_class, - features_extractor_kwargs, - normalize_images, - optimizer_class, - optimizer_kwargs, - ) - - -register_policy("MlpPolicy", MlpPolicy) -register_policy("CnnPolicy", CnnPolicy) diff --git a/spaces/Copy233/copy/app.py b/spaces/Copy233/copy/app.py deleted file mode 100644 index 2439c5cec6b61e8a517f957daf710cbb6b5c3cf6..0000000000000000000000000000000000000000 --- a/spaces/Copy233/copy/app.py +++ /dev/null @@ -1,62 +0,0 @@ -from upcunet_v3 import RealWaifuUpScaler -import gradio as gr -import time -import logging -import os -from PIL import ImageOps -import numpy as np -import math - - -def greet(input_img, input_model_name, input_tile_mode): - # if input_img.size[0] * input_img.size[1] > 256 * 256: - # y = int(math.sqrt(256*256/input_img.size[0]*input_img.size[1])) - # x = int(input_img.size[0]/input_img.size[1]*y) - # input_img = ImageOps.fit(input_img, (x, y)) - input_img = np.array(input_img) - if input_model_name not in model_cache: - t1 = time.time() - upscaler = RealWaifuUpScaler(input_model_name[2], ModelPath + input_model_name, half=False, device="cpu") - t2 = time.time() - logger.info(f'load model time, {t2 - t1}') - model_cache[input_model_name] = upscaler - else: - upscaler = model_cache[input_model_name] - logger.info(f'load model from cache') - - start = time.time() - result = upscaler(input_img, tile_mode=input_tile_mode) - end = time.time() - logger.info(f'input_model_name, {input_model_name}') - logger.info(f'input_tile_mode, {input_tile_mode}') - logger.info(f'input shape, {input_img.shape}') - logger.info(f'output shape, {result.shape}') - logger.info(f'speed time, {end - start}') - return result - - -if __name__ == '__main__': - logging.basicConfig(level=logging.INFO, format="[%(asctime)s] [%(process)d] [%(levelname)s] %(message)s") - logger = logging.getLogger() - - ModelPath = "weights_v3/" - model_cache = {} - - input_model_name = gr.inputs.Dropdown(os.listdir(ModelPath), default="up2x-latest-denoise2x.pth", label='选择model') - input_tile_mode = gr.inputs.Dropdown([0, 1, 2, 3, 4], default=2, label='选择tile_mode') - input_img = gr.inputs.Image(label='image', type='pil') - - inputs = [input_img, input_model_name, input_tile_mode] - outputs = "image" - iface = gr.Interface(fn=greet, - inputs=inputs, - outputs=outputs, - allow_screenshot=False, - allow_flagging='never', - examples=[['test-img.jpg', "up2x-latest-denoise2x.pth", 2]], - article='[https://github.com/bilibili/ailab/tree/main/Real-CUGAN](https://github.com/bilibili/ailab/tree/main/Real-CUGAN)
' - '感谢b站开源的项目,图片过大会导致内存不足,所有我将图片裁剪小,想体验大图片的效果请自行前往上面的链接。
' - '修改bbb' - 'The large image will lead to memory limit exceeded. So I crop and resize image. ' - 'If you want to experience the large image, please go to the link above.') - iface.launch() diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/pens/momentsPen.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/pens/momentsPen.py deleted file mode 100644 index dab0d10e2c63b2552cf44005fdd5d2ecea3dfe12..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/pens/momentsPen.py +++ /dev/null @@ -1,882 +0,0 @@ -from fontTools.pens.basePen import BasePen, OpenContourError - -try: - import cython - - COMPILED = cython.compiled -except (AttributeError, ImportError): - # if cython not installed, use mock module with no-op decorators and types - from fontTools.misc import cython - - COMPILED = False - - -__all__ = ["MomentsPen"] - - -class MomentsPen(BasePen): - def __init__(self, glyphset=None): - BasePen.__init__(self, glyphset) - - self.area = 0 - self.momentX = 0 - self.momentY = 0 - self.momentXX = 0 - self.momentXY = 0 - self.momentYY = 0 - - def _moveTo(self, p0): - self.__startPoint = p0 - - def _closePath(self): - p0 = self._getCurrentPoint() - if p0 != self.__startPoint: - self._lineTo(self.__startPoint) - - def _endPath(self): - p0 = self._getCurrentPoint() - if p0 != self.__startPoint: - # Green theorem is not defined on open contours. - raise OpenContourError("Green theorem is not defined on open contours.") - - @cython.locals(r0=cython.double) - @cython.locals(r1=cython.double) - @cython.locals(r2=cython.double) - @cython.locals(r3=cython.double) - @cython.locals(r4=cython.double) - @cython.locals(r5=cython.double) - @cython.locals(r6=cython.double) - @cython.locals(r7=cython.double) - @cython.locals(r8=cython.double) - @cython.locals(r9=cython.double) - @cython.locals(r10=cython.double) - @cython.locals(r11=cython.double) - @cython.locals(r12=cython.double) - @cython.locals(x0=cython.double, y0=cython.double) - @cython.locals(x1=cython.double, y1=cython.double) - def _lineTo(self, p1): - x0, y0 = self._getCurrentPoint() - x1, y1 = p1 - - r0 = x1 * y0 - r1 = x1 * y1 - r2 = x1**2 - r3 = r2 * y1 - r4 = y0 - y1 - r5 = r4 * x0 - r6 = x0**2 - r7 = 2 * y0 - r8 = y0**2 - r9 = y1**2 - r10 = x1**3 - r11 = y0**3 - r12 = y1**3 - - self.area += -r0 / 2 - r1 / 2 + x0 * (y0 + y1) / 2 - self.momentX += -r2 * y0 / 6 - r3 / 3 - r5 * x1 / 6 + r6 * (r7 + y1) / 6 - self.momentY += ( - -r0 * y1 / 6 - r8 * x1 / 6 - r9 * x1 / 6 + x0 * (r8 + r9 + y0 * y1) / 6 - ) - self.momentXX += ( - -r10 * y0 / 12 - - r10 * y1 / 4 - - r2 * r5 / 12 - - r4 * r6 * x1 / 12 - + x0**3 * (3 * y0 + y1) / 12 - ) - self.momentXY += ( - -r2 * r8 / 24 - - r2 * r9 / 8 - - r3 * r7 / 24 - + r6 * (r7 * y1 + 3 * r8 + r9) / 24 - - x0 * x1 * (r8 - r9) / 12 - ) - self.momentYY += ( - -r0 * r9 / 12 - - r1 * r8 / 12 - - r11 * x1 / 12 - - r12 * x1 / 12 - + x0 * (r11 + r12 + r8 * y1 + r9 * y0) / 12 - ) - - @cython.locals(r0=cython.double) - @cython.locals(r1=cython.double) - @cython.locals(r2=cython.double) - @cython.locals(r3=cython.double) - @cython.locals(r4=cython.double) - @cython.locals(r5=cython.double) - @cython.locals(r6=cython.double) - @cython.locals(r7=cython.double) - @cython.locals(r8=cython.double) - @cython.locals(r9=cython.double) - @cython.locals(r10=cython.double) - @cython.locals(r11=cython.double) - @cython.locals(r12=cython.double) - @cython.locals(r13=cython.double) - @cython.locals(r14=cython.double) - @cython.locals(r15=cython.double) - @cython.locals(r16=cython.double) - @cython.locals(r17=cython.double) - @cython.locals(r18=cython.double) - @cython.locals(r19=cython.double) - @cython.locals(r20=cython.double) - @cython.locals(r21=cython.double) - @cython.locals(r22=cython.double) - @cython.locals(r23=cython.double) - @cython.locals(r24=cython.double) - @cython.locals(r25=cython.double) - @cython.locals(r26=cython.double) - @cython.locals(r27=cython.double) - @cython.locals(r28=cython.double) - @cython.locals(r29=cython.double) - @cython.locals(r30=cython.double) - @cython.locals(r31=cython.double) - @cython.locals(r32=cython.double) - @cython.locals(r33=cython.double) - @cython.locals(r34=cython.double) - @cython.locals(r35=cython.double) - @cython.locals(r36=cython.double) - @cython.locals(r37=cython.double) - @cython.locals(r38=cython.double) - @cython.locals(r39=cython.double) - @cython.locals(r40=cython.double) - @cython.locals(r41=cython.double) - @cython.locals(r42=cython.double) - @cython.locals(r43=cython.double) - @cython.locals(r44=cython.double) - @cython.locals(r45=cython.double) - @cython.locals(r46=cython.double) - @cython.locals(r47=cython.double) - @cython.locals(r48=cython.double) - @cython.locals(r49=cython.double) - @cython.locals(r50=cython.double) - @cython.locals(r51=cython.double) - @cython.locals(r52=cython.double) - @cython.locals(r53=cython.double) - @cython.locals(x0=cython.double, y0=cython.double) - @cython.locals(x1=cython.double, y1=cython.double) - @cython.locals(x2=cython.double, y2=cython.double) - def _qCurveToOne(self, p1, p2): - x0, y0 = self._getCurrentPoint() - x1, y1 = p1 - x2, y2 = p2 - - r0 = 2 * y1 - r1 = r0 * x2 - r2 = x2 * y2 - r3 = 3 * r2 - r4 = 2 * x1 - r5 = 3 * y0 - r6 = x1**2 - r7 = x2**2 - r8 = 4 * y1 - r9 = 10 * y2 - r10 = 2 * y2 - r11 = r4 * x2 - r12 = x0**2 - r13 = 10 * y0 - r14 = r4 * y2 - r15 = x2 * y0 - r16 = 4 * x1 - r17 = r0 * x1 + r2 - r18 = r2 * r8 - r19 = y1**2 - r20 = 2 * r19 - r21 = y2**2 - r22 = r21 * x2 - r23 = 5 * r22 - r24 = y0**2 - r25 = y0 * y2 - r26 = 5 * r24 - r27 = x1**3 - r28 = x2**3 - r29 = 30 * y1 - r30 = 6 * y1 - r31 = 10 * r7 * x1 - r32 = 5 * y2 - r33 = 12 * r6 - r34 = 30 * x1 - r35 = x1 * y1 - r36 = r3 + 20 * r35 - r37 = 12 * x1 - r38 = 20 * r6 - r39 = 8 * r6 * y1 - r40 = r32 * r7 - r41 = 60 * y1 - r42 = 20 * r19 - r43 = 4 * r19 - r44 = 15 * r21 - r45 = 12 * x2 - r46 = 12 * y2 - r47 = 6 * x1 - r48 = 8 * r19 * x1 + r23 - r49 = 8 * y1**3 - r50 = y2**3 - r51 = y0**3 - r52 = 10 * y1 - r53 = 12 * y1 - - self.area += ( - -r1 / 6 - - r3 / 6 - + x0 * (r0 + r5 + y2) / 6 - + x1 * y2 / 3 - - y0 * (r4 + x2) / 6 - ) - self.momentX += ( - -r11 * (-r10 + y1) / 30 - + r12 * (r13 + r8 + y2) / 30 - + r6 * y2 / 15 - - r7 * r8 / 30 - - r7 * r9 / 30 - + x0 * (r14 - r15 - r16 * y0 + r17) / 30 - - y0 * (r11 + 2 * r6 + r7) / 30 - ) - self.momentY += ( - -r18 / 30 - - r20 * x2 / 30 - - r23 / 30 - - r24 * (r16 + x2) / 30 - + x0 * (r0 * y2 + r20 + r21 + r25 + r26 + r8 * y0) / 30 - + x1 * y2 * (r10 + y1) / 15 - - y0 * (r1 + r17) / 30 - ) - self.momentXX += ( - r12 * (r1 - 5 * r15 - r34 * y0 + r36 + r9 * x1) / 420 - + 2 * r27 * y2 / 105 - - r28 * r29 / 420 - - r28 * y2 / 4 - - r31 * (r0 - 3 * y2) / 420 - - r6 * x2 * (r0 - r32) / 105 - + x0**3 * (r30 + 21 * y0 + y2) / 84 - - x0 - * ( - r0 * r7 - + r15 * r37 - - r2 * r37 - - r33 * y2 - + r38 * y0 - - r39 - - r40 - + r5 * r7 - ) - / 420 - - y0 * (8 * r27 + 5 * r28 + r31 + r33 * x2) / 420 - ) - self.momentXY += ( - r12 * (r13 * y2 + 3 * r21 + 105 * r24 + r41 * y0 + r42 + r46 * y1) / 840 - - r16 * x2 * (r43 - r44) / 840 - - r21 * r7 / 8 - - r24 * (r38 + r45 * x1 + 3 * r7) / 840 - - r41 * r7 * y2 / 840 - - r42 * r7 / 840 - + r6 * y2 * (r32 + r8) / 210 - + x0 - * ( - -r15 * r8 - + r16 * r25 - + r18 - + r21 * r47 - - r24 * r34 - - r26 * x2 - + r35 * r46 - + r48 - ) - / 420 - - y0 * (r16 * r2 + r30 * r7 + r35 * r45 + r39 + r40) / 420 - ) - self.momentYY += ( - -r2 * r42 / 420 - - r22 * r29 / 420 - - r24 * (r14 + r36 + r52 * x2) / 420 - - r49 * x2 / 420 - - r50 * x2 / 12 - - r51 * (r47 + x2) / 84 - + x0 - * ( - r19 * r46 - + r21 * r5 - + r21 * r52 - + r24 * r29 - + r25 * r53 - + r26 * y2 - + r42 * y0 - + r49 - + 5 * r50 - + 35 * r51 - ) - / 420 - + x1 * y2 * (r43 + r44 + r9 * y1) / 210 - - y0 * (r19 * r45 + r2 * r53 - r21 * r4 + r48) / 420 - ) - - @cython.locals(r0=cython.double) - @cython.locals(r1=cython.double) - @cython.locals(r2=cython.double) - @cython.locals(r3=cython.double) - @cython.locals(r4=cython.double) - @cython.locals(r5=cython.double) - @cython.locals(r6=cython.double) - @cython.locals(r7=cython.double) - @cython.locals(r8=cython.double) - @cython.locals(r9=cython.double) - @cython.locals(r10=cython.double) - @cython.locals(r11=cython.double) - @cython.locals(r12=cython.double) - @cython.locals(r13=cython.double) - @cython.locals(r14=cython.double) - @cython.locals(r15=cython.double) - @cython.locals(r16=cython.double) - @cython.locals(r17=cython.double) - @cython.locals(r18=cython.double) - @cython.locals(r19=cython.double) - @cython.locals(r20=cython.double) - @cython.locals(r21=cython.double) - @cython.locals(r22=cython.double) - @cython.locals(r23=cython.double) - @cython.locals(r24=cython.double) - @cython.locals(r25=cython.double) - @cython.locals(r26=cython.double) - @cython.locals(r27=cython.double) - @cython.locals(r28=cython.double) - @cython.locals(r29=cython.double) - @cython.locals(r30=cython.double) - @cython.locals(r31=cython.double) - @cython.locals(r32=cython.double) - @cython.locals(r33=cython.double) - @cython.locals(r34=cython.double) - @cython.locals(r35=cython.double) - @cython.locals(r36=cython.double) - @cython.locals(r37=cython.double) - @cython.locals(r38=cython.double) - @cython.locals(r39=cython.double) - @cython.locals(r40=cython.double) - @cython.locals(r41=cython.double) - @cython.locals(r42=cython.double) - @cython.locals(r43=cython.double) - @cython.locals(r44=cython.double) - @cython.locals(r45=cython.double) - @cython.locals(r46=cython.double) - @cython.locals(r47=cython.double) - @cython.locals(r48=cython.double) - @cython.locals(r49=cython.double) - @cython.locals(r50=cython.double) - @cython.locals(r51=cython.double) - @cython.locals(r52=cython.double) - @cython.locals(r53=cython.double) - @cython.locals(r54=cython.double) - @cython.locals(r55=cython.double) - @cython.locals(r56=cython.double) - @cython.locals(r57=cython.double) - @cython.locals(r58=cython.double) - @cython.locals(r59=cython.double) - @cython.locals(r60=cython.double) - @cython.locals(r61=cython.double) - @cython.locals(r62=cython.double) - @cython.locals(r63=cython.double) - @cython.locals(r64=cython.double) - @cython.locals(r65=cython.double) - @cython.locals(r66=cython.double) - @cython.locals(r67=cython.double) - @cython.locals(r68=cython.double) - @cython.locals(r69=cython.double) - @cython.locals(r70=cython.double) - @cython.locals(r71=cython.double) - @cython.locals(r72=cython.double) - @cython.locals(r73=cython.double) - @cython.locals(r74=cython.double) - @cython.locals(r75=cython.double) - @cython.locals(r76=cython.double) - @cython.locals(r77=cython.double) - @cython.locals(r78=cython.double) - @cython.locals(r79=cython.double) - @cython.locals(r80=cython.double) - @cython.locals(r81=cython.double) - @cython.locals(r82=cython.double) - @cython.locals(r83=cython.double) - @cython.locals(r84=cython.double) - @cython.locals(r85=cython.double) - @cython.locals(r86=cython.double) - @cython.locals(r87=cython.double) - @cython.locals(r88=cython.double) - @cython.locals(r89=cython.double) - @cython.locals(r90=cython.double) - @cython.locals(r91=cython.double) - @cython.locals(r92=cython.double) - @cython.locals(r93=cython.double) - @cython.locals(r94=cython.double) - @cython.locals(r95=cython.double) - @cython.locals(r96=cython.double) - @cython.locals(r97=cython.double) - @cython.locals(r98=cython.double) - @cython.locals(r99=cython.double) - @cython.locals(r100=cython.double) - @cython.locals(r101=cython.double) - @cython.locals(r102=cython.double) - @cython.locals(r103=cython.double) - @cython.locals(r104=cython.double) - @cython.locals(r105=cython.double) - @cython.locals(r106=cython.double) - @cython.locals(r107=cython.double) - @cython.locals(r108=cython.double) - @cython.locals(r109=cython.double) - @cython.locals(r110=cython.double) - @cython.locals(r111=cython.double) - @cython.locals(r112=cython.double) - @cython.locals(r113=cython.double) - @cython.locals(r114=cython.double) - @cython.locals(r115=cython.double) - @cython.locals(r116=cython.double) - @cython.locals(r117=cython.double) - @cython.locals(r118=cython.double) - @cython.locals(r119=cython.double) - @cython.locals(r120=cython.double) - @cython.locals(r121=cython.double) - @cython.locals(r122=cython.double) - @cython.locals(r123=cython.double) - @cython.locals(r124=cython.double) - @cython.locals(r125=cython.double) - @cython.locals(r126=cython.double) - @cython.locals(r127=cython.double) - @cython.locals(r128=cython.double) - @cython.locals(r129=cython.double) - @cython.locals(r130=cython.double) - @cython.locals(r131=cython.double) - @cython.locals(r132=cython.double) - @cython.locals(x0=cython.double, y0=cython.double) - @cython.locals(x1=cython.double, y1=cython.double) - @cython.locals(x2=cython.double, y2=cython.double) - @cython.locals(x3=cython.double, y3=cython.double) - def _curveToOne(self, p1, p2, p3): - x0, y0 = self._getCurrentPoint() - x1, y1 = p1 - x2, y2 = p2 - x3, y3 = p3 - - r0 = 6 * y2 - r1 = r0 * x3 - r2 = 10 * y3 - r3 = r2 * x3 - r4 = 3 * y1 - r5 = 6 * x1 - r6 = 3 * x2 - r7 = 6 * y1 - r8 = 3 * y2 - r9 = x2**2 - r10 = 45 * r9 - r11 = r10 * y3 - r12 = x3**2 - r13 = r12 * y2 - r14 = r12 * y3 - r15 = 7 * y3 - r16 = 15 * x3 - r17 = r16 * x2 - r18 = x1**2 - r19 = 9 * r18 - r20 = x0**2 - r21 = 21 * y1 - r22 = 9 * r9 - r23 = r7 * x3 - r24 = 9 * y2 - r25 = r24 * x2 + r3 - r26 = 9 * x2 - r27 = x2 * y3 - r28 = -r26 * y1 + 15 * r27 - r29 = 3 * x1 - r30 = 45 * x1 - r31 = 12 * x3 - r32 = 45 * r18 - r33 = 5 * r12 - r34 = r8 * x3 - r35 = 105 * y0 - r36 = 30 * y0 - r37 = r36 * x2 - r38 = 5 * x3 - r39 = 15 * y3 - r40 = 5 * y3 - r41 = r40 * x3 - r42 = x2 * y2 - r43 = 18 * r42 - r44 = 45 * y1 - r45 = r41 + r43 + r44 * x1 - r46 = y2 * y3 - r47 = r46 * x3 - r48 = y2**2 - r49 = 45 * r48 - r50 = r49 * x3 - r51 = y3**2 - r52 = r51 * x3 - r53 = y1**2 - r54 = 9 * r53 - r55 = y0**2 - r56 = 21 * x1 - r57 = 6 * x2 - r58 = r16 * y2 - r59 = r39 * y2 - r60 = 9 * r48 - r61 = r6 * y3 - r62 = 3 * y3 - r63 = r36 * y2 - r64 = y1 * y3 - r65 = 45 * r53 - r66 = 5 * r51 - r67 = x2**3 - r68 = x3**3 - r69 = 630 * y2 - r70 = 126 * x3 - r71 = x1**3 - r72 = 126 * x2 - r73 = 63 * r9 - r74 = r73 * x3 - r75 = r15 * x3 + 15 * r42 - r76 = 630 * x1 - r77 = 14 * x3 - r78 = 21 * r27 - r79 = 42 * x1 - r80 = 42 * x2 - r81 = x1 * y2 - r82 = 63 * r42 - r83 = x1 * y1 - r84 = r41 + r82 + 378 * r83 - r85 = x2 * x3 - r86 = r85 * y1 - r87 = r27 * x3 - r88 = 27 * r9 - r89 = r88 * y2 - r90 = 42 * r14 - r91 = 90 * x1 - r92 = 189 * r18 - r93 = 378 * r18 - r94 = r12 * y1 - r95 = 252 * x1 * x2 - r96 = r79 * x3 - r97 = 30 * r85 - r98 = r83 * x3 - r99 = 30 * x3 - r100 = 42 * x3 - r101 = r42 * x1 - r102 = r10 * y2 + 14 * r14 + 126 * r18 * y1 + r81 * r99 - r103 = 378 * r48 - r104 = 18 * y1 - r105 = r104 * y2 - r106 = y0 * y1 - r107 = 252 * y2 - r108 = r107 * y0 - r109 = y0 * y3 - r110 = 42 * r64 - r111 = 378 * r53 - r112 = 63 * r48 - r113 = 27 * x2 - r114 = r27 * y2 - r115 = r113 * r48 + 42 * r52 - r116 = x3 * y3 - r117 = 54 * r42 - r118 = r51 * x1 - r119 = r51 * x2 - r120 = r48 * x1 - r121 = 21 * x3 - r122 = r64 * x1 - r123 = r81 * y3 - r124 = 30 * r27 * y1 + r49 * x2 + 14 * r52 + 126 * r53 * x1 - r125 = y2**3 - r126 = y3**3 - r127 = y1**3 - r128 = y0**3 - r129 = r51 * y2 - r130 = r112 * y3 + r21 * r51 - r131 = 189 * r53 - r132 = 90 * y2 - - self.area += ( - -r1 / 20 - - r3 / 20 - - r4 * (x2 + x3) / 20 - + x0 * (r7 + r8 + 10 * y0 + y3) / 20 - + 3 * x1 * (y2 + y3) / 20 - + 3 * x2 * y3 / 10 - - y0 * (r5 + r6 + x3) / 20 - ) - self.momentX += ( - r11 / 840 - - r13 / 8 - - r14 / 3 - - r17 * (-r15 + r8) / 840 - + r19 * (r8 + 2 * y3) / 840 - + r20 * (r0 + r21 + 56 * y0 + y3) / 168 - + r29 * (-r23 + r25 + r28) / 840 - - r4 * (10 * r12 + r17 + r22) / 840 - + x0 - * ( - 12 * r27 - + r30 * y2 - + r34 - - r35 * x1 - - r37 - - r38 * y0 - + r39 * x1 - - r4 * x3 - + r45 - ) - / 840 - - y0 * (r17 + r30 * x2 + r31 * x1 + r32 + r33 + 18 * r9) / 840 - ) - self.momentY += ( - -r4 * (r25 + r58) / 840 - - r47 / 8 - - r50 / 840 - - r52 / 6 - - r54 * (r6 + 2 * x3) / 840 - - r55 * (r56 + r57 + x3) / 168 - + x0 - * ( - r35 * y1 - + r40 * y0 - + r44 * y2 - + 18 * r48 - + 140 * r55 - + r59 - + r63 - + 12 * r64 - + r65 - + r66 - ) - / 840 - + x1 * (r24 * y1 + 10 * r51 + r59 + r60 + r7 * y3) / 280 - + x2 * y3 * (r15 + r8) / 56 - - y0 * (r16 * y1 + r31 * y2 + r44 * x2 + r45 + r61 - r62 * x1) / 840 - ) - self.momentXX += ( - -r12 * r72 * (-r40 + r8) / 9240 - + 3 * r18 * (r28 + r34 - r38 * y1 + r75) / 3080 - + r20 - * ( - r24 * x3 - - r72 * y0 - - r76 * y0 - - r77 * y0 - + r78 - + r79 * y3 - + r80 * y1 - + 210 * r81 - + r84 - ) - / 9240 - - r29 - * ( - r12 * r21 - + 14 * r13 - + r44 * r9 - - r73 * y3 - + 54 * r86 - - 84 * r87 - - r89 - - r90 - ) - / 9240 - - r4 * (70 * r12 * x2 + 27 * r67 + 42 * r68 + r74) / 9240 - + 3 * r67 * y3 / 220 - - r68 * r69 / 9240 - - r68 * y3 / 4 - - r70 * r9 * (-r62 + y2) / 9240 - + 3 * r71 * (r24 + r40) / 3080 - + x0**3 * (r24 + r44 + 165 * y0 + y3) / 660 - + x0 - * ( - r100 * r27 - + 162 * r101 - + r102 - + r11 - + 63 * r18 * y3 - + r27 * r91 - - r33 * y0 - - r37 * x3 - + r43 * x3 - - r73 * y0 - - r88 * y1 - + r92 * y2 - - r93 * y0 - - 9 * r94 - - r95 * y0 - - r96 * y0 - - r97 * y1 - - 18 * r98 - + r99 * x1 * y3 - ) - / 9240 - - y0 - * ( - r12 * r56 - + r12 * r80 - + r32 * x3 - + 45 * r67 - + 14 * r68 - + 126 * r71 - + r74 - + r85 * r91 - + 135 * r9 * x1 - + r92 * x2 - ) - / 9240 - ) - self.momentXY += ( - -r103 * r12 / 18480 - - r12 * r51 / 8 - - 3 * r14 * y2 / 44 - + 3 * r18 * (r105 + r2 * y1 + 18 * r46 + 15 * r48 + 7 * r51) / 6160 - + r20 - * ( - 1260 * r106 - + r107 * y1 - + r108 - + 28 * r109 - + r110 - + r111 - + r112 - + 30 * r46 - + 2310 * r55 - + r66 - ) - / 18480 - - r54 * (7 * r12 + 18 * r85 + 15 * r9) / 18480 - - r55 * (r33 + r73 + r93 + r95 + r96 + r97) / 18480 - - r7 * (42 * r13 + r82 * x3 + 28 * r87 + r89 + r90) / 18480 - - 3 * r85 * (r48 - r66) / 220 - + 3 * r9 * y3 * (r62 + 2 * y2) / 440 - + x0 - * ( - -r1 * y0 - - 84 * r106 * x2 - + r109 * r56 - + 54 * r114 - + r117 * y1 - + 15 * r118 - + 21 * r119 - + 81 * r120 - + r121 * r46 - + 54 * r122 - + 60 * r123 - + r124 - - r21 * x3 * y0 - + r23 * y3 - - r54 * x3 - - r55 * r72 - - r55 * r76 - - r55 * r77 - + r57 * y0 * y3 - + r60 * x3 - + 84 * r81 * y0 - + 189 * r81 * y1 - ) - / 9240 - + x1 - * ( - r104 * r27 - - r105 * x3 - - r113 * r53 - + 63 * r114 - + r115 - - r16 * r53 - + 28 * r47 - + r51 * r80 - ) - / 3080 - - y0 - * ( - 54 * r101 - + r102 - + r116 * r5 - + r117 * x3 - + 21 * r13 - - r19 * y3 - + r22 * y3 - + r78 * x3 - + 189 * r83 * x2 - + 60 * r86 - + 81 * r9 * y1 - + 15 * r94 - + 54 * r98 - ) - / 9240 - ) - self.momentYY += ( - -r103 * r116 / 9240 - - r125 * r70 / 9240 - - r126 * x3 / 12 - - 3 * r127 * (r26 + r38) / 3080 - - r128 * (r26 + r30 + x3) / 660 - - r4 * (r112 * x3 + r115 - 14 * r119 + 84 * r47) / 9240 - - r52 * r69 / 9240 - - r54 * (r58 + r61 + r75) / 9240 - - r55 - * (r100 * y1 + r121 * y2 + r26 * y3 + r79 * y2 + r84 + 210 * x2 * y1) - / 9240 - + x0 - * ( - r108 * y1 - + r110 * y0 - + r111 * y0 - + r112 * y0 - + 45 * r125 - + 14 * r126 - + 126 * r127 - + 770 * r128 - + 42 * r129 - + r130 - + r131 * y2 - + r132 * r64 - + 135 * r48 * y1 - + 630 * r55 * y1 - + 126 * r55 * y2 - + 14 * r55 * y3 - + r63 * y3 - + r65 * y3 - + r66 * y0 - ) - / 9240 - + x1 - * ( - 27 * r125 - + 42 * r126 - + 70 * r129 - + r130 - + r39 * r53 - + r44 * r48 - + 27 * r53 * y2 - + 54 * r64 * y2 - ) - / 3080 - + 3 * x2 * y3 * (r48 + r66 + r8 * y3) / 220 - - y0 - * ( - r100 * r46 - + 18 * r114 - - 9 * r118 - - 27 * r120 - - 18 * r122 - - 30 * r123 - + r124 - + r131 * x2 - + r132 * x3 * y1 - + 162 * r42 * y1 - + r50 - + 63 * r53 * x3 - + r64 * r99 - ) - / 9240 - ) - - -if __name__ == "__main__": - from fontTools.misc.symfont import x, y, printGreenPen - - printGreenPen( - "MomentsPen", - [ - ("area", 1), - ("momentX", x), - ("momentY", y), - ("momentXX", x**2), - ("momentXY", x * y), - ("momentYY", y**2), - ], - ) diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_l_c_a_r.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_l_c_a_r.py deleted file mode 100644 index 1323b670d0c2e7a51e553ee8aa341af789898b1d..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_l_c_a_r.py +++ /dev/null @@ -1,5 +0,0 @@ -from .otBase import BaseTTXConverter - - -class table__l_c_a_r(BaseTTXConverter): - pass diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_m_e_t_a.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_m_e_t_a.py deleted file mode 100644 index 3af9e543049f89f0da3ceb15bb58135854fef002..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_m_e_t_a.py +++ /dev/null @@ -1,104 +0,0 @@ -from fontTools.misc import sstruct -from fontTools.misc.textTools import bytesjoin, strjoin, readHex -from fontTools.ttLib import TTLibError -from . import DefaultTable - -# Apple's documentation of 'meta': -# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html - -META_HEADER_FORMAT = """ - > # big endian - version: L - flags: L - dataOffset: L - numDataMaps: L -""" - - -DATA_MAP_FORMAT = """ - > # big endian - tag: 4s - dataOffset: L - dataLength: L -""" - - -class table__m_e_t_a(DefaultTable.DefaultTable): - def __init__(self, tag=None): - DefaultTable.DefaultTable.__init__(self, tag) - self.data = {} - - def decompile(self, data, ttFont): - headerSize = sstruct.calcsize(META_HEADER_FORMAT) - header = sstruct.unpack(META_HEADER_FORMAT, data[0:headerSize]) - if header["version"] != 1: - raise TTLibError("unsupported 'meta' version %d" % header["version"]) - dataMapSize = sstruct.calcsize(DATA_MAP_FORMAT) - for i in range(header["numDataMaps"]): - dataMapOffset = headerSize + i * dataMapSize - dataMap = sstruct.unpack( - DATA_MAP_FORMAT, data[dataMapOffset : dataMapOffset + dataMapSize] - ) - tag = dataMap["tag"] - offset = dataMap["dataOffset"] - self.data[tag] = data[offset : offset + dataMap["dataLength"]] - if tag in ["dlng", "slng"]: - self.data[tag] = self.data[tag].decode("utf-8") - - def compile(self, ttFont): - keys = sorted(self.data.keys()) - headerSize = sstruct.calcsize(META_HEADER_FORMAT) - dataOffset = headerSize + len(keys) * sstruct.calcsize(DATA_MAP_FORMAT) - header = sstruct.pack( - META_HEADER_FORMAT, - { - "version": 1, - "flags": 0, - "dataOffset": dataOffset, - "numDataMaps": len(keys), - }, - ) - dataMaps = [] - dataBlocks = [] - for tag in keys: - if tag in ["dlng", "slng"]: - data = self.data[tag].encode("utf-8") - else: - data = self.data[tag] - dataMaps.append( - sstruct.pack( - DATA_MAP_FORMAT, - {"tag": tag, "dataOffset": dataOffset, "dataLength": len(data)}, - ) - ) - dataBlocks.append(data) - dataOffset += len(data) - return bytesjoin([header] + dataMaps + dataBlocks) - - def toXML(self, writer, ttFont): - for tag in sorted(self.data.keys()): - if tag in ["dlng", "slng"]: - writer.begintag("text", tag=tag) - writer.newline() - writer.write(self.data[tag]) - writer.newline() - writer.endtag("text") - writer.newline() - else: - writer.begintag("hexdata", tag=tag) - writer.newline() - data = self.data[tag] - if min(data) >= 0x20 and max(data) <= 0x7E: - writer.comment("ascii: " + data.decode("ascii")) - writer.newline() - writer.dumphex(data) - writer.endtag("hexdata") - writer.newline() - - def fromXML(self, name, attrs, content, ttFont): - if name == "hexdata": - self.data[attrs["tag"]] = readHex(content) - elif name == "text" and attrs["tag"] in ["dlng", "slng"]: - self.data[attrs["tag"]] = strjoin(content).strip() - else: - raise TTLibError("can't handle '%s' element" % name) diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/index-c20bfa80.js b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/index-c20bfa80.js deleted file mode 100644 index cc0072be478ee5e6b446cf64023a14fadd41c35f..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/index-c20bfa80.js +++ /dev/null @@ -1,2 +0,0 @@ -import{S as h,e as p,s as v,h as T,j as k,k as C,o as S,t as j,z as m,v as d,x as q,B as w,a9 as z,ab as B,ac as D,ad as E,F as u}from"./index-1d65707a.js";import{T as F}from"./TabItem.svelte_svelte_type_style_lang-1276453b.js";/* empty css */function A(s){let e;const i=s[4].default,t=z(i,s,s[8],null);return{c(){t&&t.c()},m(n,o){t&&t.m(n,o),e=!0},p(n,o){t&&t.p&&(!e||o&256)&&B(t,i,n,n[8],e?E(i,n[8],o,null):D(n[8]),null)},i(n){e||(m(t,n),e=!0)},o(n){d(t,n),e=!1},d(n){t&&t.d(n)}}}function G(s){let e,i,t;function n(l){s[5](l)}let o={visible:s[1],elem_id:s[2],elem_classes:s[3],$$slots:{default:[A]},$$scope:{ctx:s}};return s[0]!==void 0&&(o.selected=s[0]),e=new F({props:o}),T.push(()=>k(e,"selected",n)),e.$on("change",s[6]),e.$on("select",s[7]),{c(){C(e.$$.fragment)},m(l,c){S(e,l,c),t=!0},p(l,[c]){const _={};c&2&&(_.visible=l[1]),c&4&&(_.elem_id=l[2]),c&8&&(_.elem_classes=l[3]),c&256&&(_.$$scope={dirty:c,ctx:l}),!i&&c&1&&(i=!0,_.selected=l[0],j(()=>i=!1)),e.$set(_)},i(l){t||(m(e.$$.fragment,l),t=!0)},o(l){d(e.$$.fragment,l),t=!1},d(l){q(e,l)}}}function H(s,e,i){let{$$slots:t={},$$scope:n}=e;const o=w();let{visible:l=!0}=e,{elem_id:c=""}=e,{elem_classes:_=[]}=e,{selected:f}=e;function r(a){f=a,i(0,f)}function b(a){u.call(this,s,a)}function g(a){u.call(this,s,a)}return s.$$set=a=>{"visible"in a&&i(1,l=a.visible),"elem_id"in a&&i(2,c=a.elem_id),"elem_classes"in a&&i(3,_=a.elem_classes),"selected"in a&&i(0,f=a.selected),"$$scope"in a&&i(8,n=a.$$scope)},s.$$.update=()=>{s.$$.dirty&1&&o("prop_change",{selected:f})},[f,l,c,_,t,r,b,g,n]}class I extends h{constructor(e){super(),p(this,e,H,G,v,{visible:1,elem_id:2,elem_classes:3,selected:0})}}const M=I,N=["static"];export{M as Component,N as modes}; -//# sourceMappingURL=index-c20bfa80.js.map diff --git a/spaces/Detomo/Aisatsu-robot/app.py b/spaces/Detomo/Aisatsu-robot/app.py deleted file mode 100644 index 626fc910e0858b5ba102cff9f988bf85936484b5..0000000000000000000000000000000000000000 --- a/spaces/Detomo/Aisatsu-robot/app.py +++ /dev/null @@ -1,112 +0,0 @@ -import gradio as gr -import torch -from ultralyticsplus import YOLO -import numpy as np - -from PIL import Image -from base64 import b64encode -from io import BytesIO -from gtts import gTTS -from mtranslate import translate -from speech_recognition import AudioFile, Recognizer -import time - -from sahi.prediction import ObjectPrediction, PredictionScore -from sahi.utils.cv import ( - get_bool_mask_from_coco_segmentation, - read_image_as_pil, - visualize_object_predictions, -) - -model = YOLO('ultralyticsplus/yolov8s') -CLASS = model.model.names - -def tts(text: str, language="ja") -> object: - """Converts text into autoplay html. - Args: - text (str): generated answer of bot - Returns: - html: autoplay object - """ - tts_object = gTTS(text=text, lang=language, slow=False) - bytes_object = BytesIO() - tts_object.write_to_fp(bytes_object) - bytes_object.seek(0) - b64 = b64encode(bytes_object.getvalue()).decode() - html = f""" - - """ - return html - - -def yolov8_inference( - image, - area_thres=0.35, - defaul_bot_voice="おはいようございます" -): - """ - YOLOv8 inference function - Args: - image: Input image - Returns: - Rendered image - """ - # time.sleep(1) - # set model parameters - model.overrides['conf'] = 0.25 # NMS confidence threshold - model.overrides['iou'] = 0.45 # NMS IoU threshold - model.overrides['agnostic_nms'] = False # NMS class-agnostic - model.overrides['max_det'] = 1000 # maximum number of detections per image - results = model.predict(image, show=False)[0] - image = read_image_as_pil(image) - np_image = np.ascontiguousarray(image) - masks, boxes = results.masks, results.boxes - area_image = image.width*image.height - object_predictions = [] - html_bot_voice = "" - most_close = 0 - if boxes is not None: - det_ind = 0 - for xyxy, conf, cls in zip(boxes.xyxy, boxes.conf, boxes.cls): - if int(cls) != 0: - continue - box = xyxy.tolist() - area_rate = (box[2] - box[0]) * (box[3] - box[1]) / area_image - object_prediction = ObjectPrediction( - bbox=box, - category_name=CLASS[int(cls)], - category_id=int(cls), - score=area_rate, - ) - object_predictions.append(object_prediction) - det_ind += 1 - if area_rate >= most_close: - out_img = image.crop(tuple(box)).resize((image.width, image.height)) - most_close = area_rate - if area_rate >= area_thres: - html_bot_voice = tts(defaul_bot_voice, language="ja") - - # result = visualize_object_predictions( - # image=np_image, - # object_prediction_list=object_predictions, - # rect_th=2, - # text_th=2, - # ) - # return Image.fromarray(result["image"]), html_bot_voice - return out_img, html_bot_voice - - -outputs = [gr.Image(type="filepath", label="Robot View"), - gr.HTML()] -title = "Detomo Aisatsu Robot" - -demo_app = gr.Interface( - fn=yolov8_inference, - inputs=gr.Image(source="webcam", streaming=True, label="Input Image"), - outputs=outputs, - title=title, - live=True, -) -demo_app.launch(debug=True) \ No newline at end of file diff --git a/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/lpips/base_model.py b/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/lpips/base_model.py deleted file mode 100644 index 8de1d16f0c7fa52d8067139abc6e769e96d0a6a1..0000000000000000000000000000000000000000 --- a/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/lpips/base_model.py +++ /dev/null @@ -1,58 +0,0 @@ -import os -import numpy as np -import torch -from torch.autograd import Variable -from pdb import set_trace as st -from IPython import embed - -class BaseModel(): - def __init__(self): - pass; - - def name(self): - return 'BaseModel' - - def initialize(self, use_gpu=True, gpu_ids=[0]): - self.use_gpu = use_gpu - self.gpu_ids = gpu_ids - - def forward(self): - pass - - def get_image_paths(self): - pass - - def optimize_parameters(self): - pass - - def get_current_visuals(self): - return self.input - - def get_current_errors(self): - return {} - - def save(self, label): - pass - - # helper saving function that can be used by subclasses - def save_network(self, network, path, network_label, epoch_label): - save_filename = '%s_net_%s.pth' % (epoch_label, network_label) - save_path = os.path.join(path, save_filename) - torch.save(network.state_dict(), save_path) - - # helper loading function that can be used by subclasses - def load_network(self, network, network_label, epoch_label): - save_filename = '%s_net_%s.pth' % (epoch_label, network_label) - save_path = os.path.join(self.save_dir, save_filename) - print('Loading network from %s'%save_path) - network.load_state_dict(torch.load(save_path)) - - def update_learning_rate(): - pass - - def get_image_paths(self): - return self.image_paths - - def save_done(self, flag=False): - np.save(os.path.join(self.save_dir, 'done_flag'),flag) - np.savetxt(os.path.join(self.save_dir, 'done_flag'),[flag,],fmt='%i') diff --git a/spaces/Dinoking/Guccio-AI-Designer/netdissect/__main__.py b/spaces/Dinoking/Guccio-AI-Designer/netdissect/__main__.py deleted file mode 100644 index e2bd9f630eaa0f45a6a201adcf356a1e092050cb..0000000000000000000000000000000000000000 --- a/spaces/Dinoking/Guccio-AI-Designer/netdissect/__main__.py +++ /dev/null @@ -1,408 +0,0 @@ -import torch, sys, os, argparse, textwrap, numbers, numpy, json, PIL -from torchvision import transforms -from torch.utils.data import TensorDataset -from netdissect.progress import verbose_progress, print_progress -from netdissect import InstrumentedModel, BrodenDataset, dissect -from netdissect import MultiSegmentDataset, GeneratorSegRunner -from netdissect import ImageOnlySegRunner -from netdissect.parallelfolder import ParallelImageFolders -from netdissect.zdataset import z_dataset_for_model -from netdissect.autoeval import autoimport_eval -from netdissect.modelconfig import create_instrumented_model -from netdissect.pidfile import exit_if_job_done, mark_job_done - -help_epilog = '''\ -Example: to dissect three layers of the pretrained alexnet in torchvision: - -python -m netdissect \\ - --model "torchvision.models.alexnet(pretrained=True)" \\ - --layers features.6:conv3 features.8:conv4 features.10:conv5 \\ - --imgsize 227 \\ - --outdir dissect/alexnet-imagenet - -To dissect a progressive GAN model: - -python -m netdissect \\ - --model "proggan.from_pth_file('model/churchoutdoor.pth')" \\ - --gan -''' - -def main(): - # Training settings - def strpair(arg): - p = tuple(arg.split(':')) - if len(p) == 1: - p = p + p - return p - def intpair(arg): - p = arg.split(',') - if len(p) == 1: - p = p + p - return tuple(int(v) for v in p) - - parser = argparse.ArgumentParser(description='Net dissect utility', - prog='python -m netdissect', - epilog=textwrap.dedent(help_epilog), - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('--model', type=str, default=None, - help='constructor for the model to test') - parser.add_argument('--pthfile', type=str, default=None, - help='filename of .pth file for the model') - parser.add_argument('--unstrict', action='store_true', default=False, - help='ignore unexpected pth parameters') - parser.add_argument('--submodule', type=str, default=None, - help='submodule to load from pthfile') - parser.add_argument('--outdir', type=str, default='dissect', - help='directory for dissection output') - parser.add_argument('--layers', type=strpair, nargs='+', - help='space-separated list of layer names to dissect' + - ', in the form layername[:reportedname]') - parser.add_argument('--segments', type=str, default='dataset/broden', - help='directory containing segmentation dataset') - parser.add_argument('--segmenter', type=str, default=None, - help='constructor for asegmenter class') - parser.add_argument('--download', action='store_true', default=False, - help='downloads Broden dataset if needed') - parser.add_argument('--imagedir', type=str, default=None, - help='directory containing image-only dataset') - parser.add_argument('--imgsize', type=intpair, default=(227, 227), - help='input image size to use') - parser.add_argument('--netname', type=str, default=None, - help='name for network in generated reports') - parser.add_argument('--meta', type=str, nargs='+', - help='json files of metadata to add to report') - parser.add_argument('--merge', type=str, - help='json file of unit data to merge in report') - parser.add_argument('--examples', type=int, default=20, - help='number of image examples per unit') - parser.add_argument('--size', type=int, default=10000, - help='dataset subset size to use') - parser.add_argument('--batch_size', type=int, default=100, - help='batch size for forward pass') - parser.add_argument('--num_workers', type=int, default=24, - help='number of DataLoader workers') - parser.add_argument('--quantile_threshold', type=strfloat, default=None, - choices=[FloatRange(0.0, 1.0), 'iqr'], - help='quantile to use for masks') - parser.add_argument('--no-labels', action='store_true', default=False, - help='disables labeling of units') - parser.add_argument('--maxiou', action='store_true', default=False, - help='enables maxiou calculation') - parser.add_argument('--covariance', action='store_true', default=False, - help='enables covariance calculation') - parser.add_argument('--rank_all_labels', action='store_true', default=False, - help='include low-information labels in rankings') - parser.add_argument('--no-images', action='store_true', default=False, - help='disables generation of unit images') - parser.add_argument('--no-report', action='store_true', default=False, - help='disables generation report summary') - parser.add_argument('--no-cuda', action='store_true', default=False, - help='disables CUDA usage') - parser.add_argument('--gen', action='store_true', default=False, - help='test a generator model (e.g., a GAN)') - parser.add_argument('--gan', action='store_true', default=False, - help='synonym for --gen') - parser.add_argument('--perturbation', default=None, - help='filename of perturbation attack to apply') - parser.add_argument('--add_scale_offset', action='store_true', default=None, - help='offsets masks according to stride and padding') - parser.add_argument('--quiet', action='store_true', default=False, - help='silences console output') - if len(sys.argv) == 1: - parser.print_usage(sys.stderr) - sys.exit(1) - args = parser.parse_args() - args.images = not args.no_images - args.report = not args.no_report - args.labels = not args.no_labels - if args.gan: - args.gen = args.gan - - # Set up console output - verbose_progress(not args.quiet) - - # Exit right away if job is already done or being done. - if args.outdir is not None: - exit_if_job_done(args.outdir) - - # Speed up pytorch - torch.backends.cudnn.benchmark = True - - # Special case: download flag without model to test. - if args.model is None and args.download: - from netdissect.broden import ensure_broden_downloaded - for resolution in [224, 227, 384]: - ensure_broden_downloaded(args.segments, resolution, 1) - from netdissect.segmenter import ensure_upp_segmenter_downloaded - ensure_upp_segmenter_downloaded('dataset/segmodel') - sys.exit(0) - - # Help if broden is not present - if not args.gen and not args.imagedir and not os.path.isdir(args.segments): - print_progress('Segmentation dataset not found at %s.' % args.segments) - print_progress('Specify dataset directory using --segments [DIR]') - print_progress('To download Broden, run: netdissect --download') - sys.exit(1) - - # Default segmenter class - if args.gen and args.segmenter is None: - args.segmenter = ("netdissect.segmenter.UnifiedParsingSegmenter(" + - "segsizes=[256], segdiv='quad')") - - # Default threshold - if args.quantile_threshold is None: - if args.gen: - args.quantile_threshold = 'iqr' - else: - args.quantile_threshold = 0.005 - - # Set up CUDA - args.cuda = not args.no_cuda and torch.cuda.is_available() - if args.cuda: - torch.backends.cudnn.benchmark = True - - # Construct the network with specified layers instrumented - if args.model is None: - print_progress('No model specified') - sys.exit(1) - model = create_instrumented_model(args) - - # Update any metadata from files, if any - meta = getattr(model, 'meta', {}) - if args.meta: - for mfilename in args.meta: - with open(mfilename) as f: - meta.update(json.load(f)) - - # Load any merge data from files - mergedata = None - if args.merge: - with open(args.merge) as f: - mergedata = json.load(f) - - # Set up the output directory, verify write access - if args.outdir is None: - args.outdir = os.path.join('dissect', type(model).__name__) - exit_if_job_done(args.outdir) - print_progress('Writing output into %s.' % args.outdir) - os.makedirs(args.outdir, exist_ok=True) - train_dataset = None - - if not args.gen: - # Load dataset for classifier case. - # Load perturbation - perturbation = numpy.load(args.perturbation - ) if args.perturbation else None - segrunner = None - - # Load broden dataset - if args.imagedir is not None: - dataset = try_to_load_images(args.imagedir, args.imgsize, - perturbation, args.size) - segrunner = ImageOnlySegRunner(dataset) - else: - dataset = try_to_load_broden(args.segments, args.imgsize, 1, - perturbation, args.download, args.size) - if dataset is None: - dataset = try_to_load_multiseg(args.segments, args.imgsize, - perturbation, args.size) - if dataset is None: - print_progress('No segmentation dataset found in %s', - args.segments) - print_progress('use --download to download Broden.') - sys.exit(1) - else: - # For segmenter case the dataset is just a random z - dataset = z_dataset_for_model(model, args.size) - train_dataset = z_dataset_for_model(model, args.size, seed=2) - segrunner = GeneratorSegRunner(autoimport_eval(args.segmenter)) - - # Run dissect - dissect(args.outdir, model, dataset, - train_dataset=train_dataset, - segrunner=segrunner, - examples_per_unit=args.examples, - netname=args.netname, - quantile_threshold=args.quantile_threshold, - meta=meta, - merge=mergedata, - make_images=args.images, - make_labels=args.labels, - make_maxiou=args.maxiou, - make_covariance=args.covariance, - make_report=args.report, - make_row_images=args.images, - make_single_images=True, - rank_all_labels=args.rank_all_labels, - batch_size=args.batch_size, - num_workers=args.num_workers, - settings=vars(args)) - - # Mark the directory so that it's not done again. - mark_job_done(args.outdir) - -class AddPerturbation(object): - def __init__(self, perturbation): - self.perturbation = perturbation - - def __call__(self, pic): - if self.perturbation is None: - return pic - # Convert to a numpy float32 array - npyimg = numpy.array(pic, numpy.uint8, copy=False - ).astype(numpy.float32) - # Center the perturbation - oy, ox = ((self.perturbation.shape[d] - npyimg.shape[d]) // 2 - for d in [0, 1]) - npyimg += self.perturbation[ - oy:oy+npyimg.shape[0], ox:ox+npyimg.shape[1]] - # Pytorch conventions: as a float it should be [0..1] - npyimg.clip(0, 255, npyimg) - return npyimg / 255.0 - -def test_dissection(): - verbose_progress(True) - from torchvision.models import alexnet - from torchvision import transforms - model = InstrumentedModel(alexnet(pretrained=True)) - model.eval() - # Load an alexnet - model.retain_layers([ - ('features.0', 'conv1'), - ('features.3', 'conv2'), - ('features.6', 'conv3'), - ('features.8', 'conv4'), - ('features.10', 'conv5') ]) - # load broden dataset - bds = BrodenDataset('dataset/broden', - transform=transforms.Compose([ - transforms.ToTensor(), - transforms.Normalize(IMAGE_MEAN, IMAGE_STDEV)]), - size=100) - # run dissect - dissect('dissect/test', model, bds, - examples_per_unit=10) - -def try_to_load_images(directory, imgsize, perturbation, size): - # Load plain image dataset - # TODO: allow other normalizations. - return ParallelImageFolders( - [directory], - transform=transforms.Compose([ - transforms.Resize(imgsize), - AddPerturbation(perturbation), - transforms.ToTensor(), - transforms.Normalize(IMAGE_MEAN, IMAGE_STDEV)]), - size=size) - -def try_to_load_broden(directory, imgsize, broden_version, perturbation, - download, size): - # Load broden dataset - ds_resolution = (224 if max(imgsize) <= 224 else - 227 if max(imgsize) <= 227 else 384) - if not os.path.isfile(os.path.join(directory, - 'broden%d_%d' % (broden_version, ds_resolution), 'index.csv')): - return None - return BrodenDataset(directory, - resolution=ds_resolution, - download=download, - broden_version=broden_version, - transform=transforms.Compose([ - transforms.Resize(imgsize), - AddPerturbation(perturbation), - transforms.ToTensor(), - transforms.Normalize(IMAGE_MEAN, IMAGE_STDEV)]), - size=size) - -def try_to_load_multiseg(directory, imgsize, perturbation, size): - if not os.path.isfile(os.path.join(directory, 'labelnames.json')): - return None - minsize = min(imgsize) if hasattr(imgsize, '__iter__') else imgsize - return MultiSegmentDataset(directory, - transform=(transforms.Compose([ - transforms.Resize(minsize), - transforms.CenterCrop(imgsize), - AddPerturbation(perturbation), - transforms.ToTensor(), - transforms.Normalize(IMAGE_MEAN, IMAGE_STDEV)]), - transforms.Compose([ - transforms.Resize(minsize, interpolation=PIL.Image.NEAREST), - transforms.CenterCrop(imgsize)])), - size=size) - -def add_scale_offset_info(model, layer_names): - ''' - Creates a 'scale_offset' property on the model which guesses - how to offset the featuremap, in cases where the convolutional - padding does not exacly correspond to keeping featuremap pixels - centered on the downsampled regions of the input. This mainly - shows up in AlexNet: ResNet and VGG pad convolutions to keep - them centered and do not need this. - ''' - model.scale_offset = {} - seen = set() - sequence = [] - aka_map = {} - for name in layer_names: - aka = name - if not isinstance(aka, str): - name, aka = name - aka_map[name] = aka - for name, layer in model.named_modules(): - sequence.append(layer) - if name in aka_map: - seen.add(name) - aka = aka_map[name] - model.scale_offset[aka] = sequence_scale_offset(sequence) - for name in aka_map: - assert name in seen, ('Layer %s not found' % name) - -def dilation_scale_offset(dilations): - '''Composes a list of (k, s, p) into a single total scale and offset.''' - if len(dilations) == 0: - return (1, 0) - scale, offset = dilation_scale_offset(dilations[1:]) - kernel, stride, padding = dilations[0] - scale *= stride - offset *= stride - offset += (kernel - 1) / 2.0 - padding - return scale, offset - -def dilations(modulelist): - '''Converts a list of modules to (kernel_size, stride, padding)''' - result = [] - for module in modulelist: - settings = tuple(getattr(module, n, d) - for n, d in (('kernel_size', 1), ('stride', 1), ('padding', 0))) - settings = (((s, s) if not isinstance(s, tuple) else s) - for s in settings) - if settings != ((1, 1), (1, 1), (0, 0)): - result.append(zip(*settings)) - return zip(*result) - -def sequence_scale_offset(modulelist): - '''Returns (yscale, yoffset), (xscale, xoffset) given a list of modules''' - return tuple(dilation_scale_offset(d) for d in dilations(modulelist)) - - -def strfloat(s): - try: - return float(s) - except: - return s - -class FloatRange(object): - def __init__(self, start, end): - self.start = start - self.end = end - def __eq__(self, other): - return isinstance(other, float) and self.start <= other <= self.end - def __repr__(self): - return '[%g-%g]' % (self.start, self.end) - -# Many models use this normalization. -IMAGE_MEAN = [0.485, 0.456, 0.406] -IMAGE_STDEV = [0.229, 0.224, 0.225] - -if __name__ == '__main__': - main() diff --git a/spaces/Eddycrack864/Applio-Inference/README.md b/spaces/Eddycrack864/Applio-Inference/README.md deleted file mode 100644 index 9d8914cd05791e4f8db6267eb2a5fe2133e22e58..0000000000000000000000000000000000000000 --- a/spaces/Eddycrack864/Applio-Inference/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: RVC Inference HF -emoji: 👀 -colorFrom: green -colorTo: green -sdk: gradio -sdk_version: 3.43.2 -app_file: app.py -pinned: false ---- \ No newline at end of file diff --git a/spaces/Epitech/userbank/app.py b/spaces/Epitech/userbank/app.py deleted file mode 100644 index c65e60849a95f671a9c6bdd8af410ff145efd7dc..0000000000000000000000000000000000000000 --- a/spaces/Epitech/userbank/app.py +++ /dev/null @@ -1,66 +0,0 @@ -import gradio as gr -import numpy as np -import pandas as pd -from sklearn.model_selection import train_test_split -from sklearn.preprocessing import StandardScaler -from sklearn.linear_model import LogisticRegression -from sklearn.pipeline import Pipeline -from sklearn.metrics import accuracy_score -import time -import paho.mqtt.client as mqtt - -df = pd.read_csv("./Churn_Modelling.csv") -df.drop(["RowNumber","CustomerId","Surname"], axis=1, inplace=True) -df.head() - -df.Balance.plot(kind="hist", figsize=(10,6)) -df.Balance = np.where(df.Balance==0, 0, 1) -df.Balance.value_counts() -df.Age.plot(kind="hist", figsize=(10,6)) - -X = df.drop(["Exited","Geography","Gender"], axis=1) -y = df["Exited"] -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) - -pl = Pipeline([ - ("scale", StandardScaler()), - ("logreg", LogisticRegression()) -]) -pl.fit(X_train, y_train) -y_train_pred = pl.predict(X_train) -y_test_pred = pl.predict(X_test) - -def sentence_builder(credit, age, tenure, balance, nb_prods, has_card, active, est_salary): - data = [{ - "CreditScore": credit, - "Age": age, - "Tenure": tenure, - "Balance": balance, - "NumOfProducts": nb_prods, - "HasCrCard": has_card, - "IsActiveMember": active, - "EstimatedSalary": est_salary, - }] - df = pd.json_normalize(data) - res = bool(pl.predict(df)[0]) - return 'User will stay' if res else 'User will exit' - -iface = gr.Interface( - sentence_builder, - [ - gr.inputs.Slider(0, 10000, label='credit'), - gr.inputs.Slider(0, 100, label='age'), - gr.inputs.Slider(0, 10, label='tenure'), - gr.inputs.Slider(0, 10000, label='balance'), - gr.inputs.Slider(0, 10, label='number of products'), - gr.inputs.Checkbox(label="credit card"), - gr.inputs.Checkbox(label="active"), - gr.inputs.Slider(0, 200000, label='estimated salary'), - ], - "text", - examples=[ - [619, 42, 2, 0, 1, 1, 1, 101348], # Returns False 0 - [608, 41, 1, 83807, 1, 0, 1, 112542], # Returns True 1 - ], -) -iface.launch() diff --git a/spaces/EsoCode/text-generation-webui/extensions/sd_api_pictures/script.py b/spaces/EsoCode/text-generation-webui/extensions/sd_api_pictures/script.py deleted file mode 100644 index 75cc205d5c6a3ad0b2c5075c523094ec667b2f69..0000000000000000000000000000000000000000 --- a/spaces/EsoCode/text-generation-webui/extensions/sd_api_pictures/script.py +++ /dev/null @@ -1,383 +0,0 @@ -import base64 -import io -import re -import time -from datetime import date -from pathlib import Path - -import gradio as gr -import requests -import torch -from PIL import Image - -import modules.shared as shared -from modules.models import reload_model, unload_model -from modules.ui import create_refresh_button - -torch._C._jit_set_profiling_mode(False) - -# parameters which can be customized in settings.json of webui -params = { - 'address': 'http://127.0.0.1:7860', - 'mode': 0, # modes of operation: 0 (Manual only), 1 (Immersive/Interactive - looks for words to trigger), 2 (Picturebook Adventure - Always on) - 'manage_VRAM': False, - 'save_img': False, - 'SD_model': 'NeverEndingDream', # not used right now - 'prompt_prefix': '(Masterpiece:1.1), detailed, intricate, colorful', - 'negative_prompt': '(worst quality, low quality:1.3)', - 'width': 512, - 'height': 512, - 'denoising_strength': 0.61, - 'restore_faces': False, - 'enable_hr': False, - 'hr_upscaler': 'ESRGAN_4x', - 'hr_scale': '1.0', - 'seed': -1, - 'sampler_name': 'DPM++ 2M Karras', - 'steps': 32, - 'cfg_scale': 7, - 'textgen_prefix': 'Please provide a detailed and vivid description of [subject]', - 'sd_checkpoint': ' ', - 'checkpoint_list': [" "] -} - - -def give_VRAM_priority(actor): - global shared, params - - if actor == 'SD': - unload_model() - print("Requesting Auto1111 to re-load last checkpoint used...") - response = requests.post(url=f'{params["address"]}/sdapi/v1/reload-checkpoint', json='') - response.raise_for_status() - - elif actor == 'LLM': - print("Requesting Auto1111 to vacate VRAM...") - response = requests.post(url=f'{params["address"]}/sdapi/v1/unload-checkpoint', json='') - response.raise_for_status() - reload_model() - - elif actor == 'set': - print("VRAM mangement activated -- requesting Auto1111 to vacate VRAM...") - response = requests.post(url=f'{params["address"]}/sdapi/v1/unload-checkpoint', json='') - response.raise_for_status() - - elif actor == 'reset': - print("VRAM mangement deactivated -- requesting Auto1111 to reload checkpoint") - response = requests.post(url=f'{params["address"]}/sdapi/v1/reload-checkpoint', json='') - response.raise_for_status() - - else: - raise RuntimeError(f'Managing VRAM: "{actor}" is not a known state!') - - response.raise_for_status() - del response - - -if params['manage_VRAM']: - give_VRAM_priority('set') - -SD_models = ['NeverEndingDream'] # TODO: get with http://{address}}/sdapi/v1/sd-models and allow user to select - -picture_response = False # specifies if the next model response should appear as a picture - - -def remove_surrounded_chars(string): - # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR - # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string' - return re.sub('\*[^\*]*?(\*|$)', '', string) - - -def triggers_are_in(string): - string = remove_surrounded_chars(string) - # regex searches for send|main|message|me (at the end of the word) followed by - # a whole word of image|pic|picture|photo|snap|snapshot|selfie|meme(s), - # (?aims) are regex parser flags - return bool(re.search('(?aims)(send|mail|message|me)\\b.+?\\b(image|pic(ture)?|photo|snap(shot)?|selfie|meme)s?\\b', string)) - - -def state_modifier(state): - if picture_response: - state['stream'] = False - - return state - - -def input_modifier(string): - """ - This function is applied to your text inputs before - they are fed into the model. - """ - - global params - - if not params['mode'] == 1: # if not in immersive/interactive mode, do nothing - return string - - if triggers_are_in(string): # if we're in it, check for trigger words - toggle_generation(True) - string = string.lower() - if "of" in string: - subject = string.split('of', 1)[1] # subdivide the string once by the first 'of' instance and get what's coming after it - string = params['textgen_prefix'].replace("[subject]", subject) - else: - string = params['textgen_prefix'].replace("[subject]", "your appearance, your surroundings and what you are doing right now") - - return string - -# Get and save the Stable Diffusion-generated picture -def get_SD_pictures(description): - - global params - - if params['manage_VRAM']: - give_VRAM_priority('SD') - - payload = { - "prompt": params['prompt_prefix'] + description, - "seed": params['seed'], - "sampler_name": params['sampler_name'], - "enable_hr": params['enable_hr'], - "hr_scale": params['hr_scale'], - "hr_upscaler": params['hr_upscaler'], - "denoising_strength": params['denoising_strength'], - "steps": params['steps'], - "cfg_scale": params['cfg_scale'], - "width": params['width'], - "height": params['height'], - "restore_faces": params['restore_faces'], - "override_settings_restore_afterwards": True, - "negative_prompt": params['negative_prompt'] - } - - print(f'Prompting the image generator via the API on {params["address"]}...') - response = requests.post(url=f'{params["address"]}/sdapi/v1/txt2img', json=payload) - response.raise_for_status() - r = response.json() - - visible_result = "" - for img_str in r['images']: - if params['save_img']: - img_data = base64.b64decode(img_str) - - variadic = f'{date.today().strftime("%Y_%m_%d")}/{shared.character}_{int(time.time())}' - output_file = Path(f'extensions/sd_api_pictures/outputs/{variadic}.png') - output_file.parent.mkdir(parents=True, exist_ok=True) - - with open(output_file.as_posix(), 'wb') as f: - f.write(img_data) - - visible_result = visible_result + f'{description}\n' - else: - image = Image.open(io.BytesIO(base64.b64decode(img_str.split(",", 1)[0]))) - # lower the resolution of received images for the chat, otherwise the log size gets out of control quickly with all the base64 values in visible history - image.thumbnail((300, 300)) - buffered = io.BytesIO() - image.save(buffered, format="JPEG") - buffered.seek(0) - image_bytes = buffered.getvalue() - img_str = "data:image/jpeg;base64," + base64.b64encode(image_bytes).decode() - visible_result = visible_result + f'{description}\n' - - if params['manage_VRAM']: - give_VRAM_priority('LLM') - - return visible_result - -# TODO: how do I make the UI history ignore the resulting pictures (I don't want HTML to appear in history) -# and replace it with 'text' for the purposes of logging? -def output_modifier(string): - """ - This function is applied to the model outputs. - """ - - global picture_response, params - - if not picture_response: - return string - - string = remove_surrounded_chars(string) - string = string.replace('"', '') - string = string.replace('“', '') - string = string.replace('\n', ' ') - string = string.strip() - - if string == '': - string = 'no viable description in reply, try regenerating' - return string - - text = "" - if (params['mode'] < 2): - toggle_generation(False) - text = f'*Sends a picture which portrays: “{string}”*' - else: - text = string - - string = get_SD_pictures(string) + "\n" + text - - return string - - -def bot_prefix_modifier(string): - """ - This function is only applied in chat mode. It modifies - the prefix text for the Bot and can be used to bias its - behavior. - """ - - return string - - -def toggle_generation(*args): - global picture_response, shared - - if not args: - picture_response = not picture_response - else: - picture_response = args[0] - - shared.processing_message = "*Is sending a picture...*" if picture_response else "*Is typing...*" - - -def filter_address(address): - address = address.strip() - # address = re.sub('http(s)?:\/\/|\/$','',address) # remove starting http:// OR https:// OR trailing slash - address = re.sub('\/$', '', address) # remove trailing /s - if not address.startswith('http'): - address = 'http://' + address - return address - - -def SD_api_address_update(address): - global params - - msg = "✔️ SD API is found on:" - address = filter_address(address) - params.update({"address": address}) - try: - response = requests.get(url=f'{params["address"]}/sdapi/v1/sd-models') - response.raise_for_status() - # r = response.json() - except: - msg = "❌ No SD API endpoint on:" - - return gr.Textbox.update(label=msg) - - -def custom_css(): - path_to_css = Path(__file__).parent.resolve() / 'style.css' - return open(path_to_css, 'r').read() - - -def get_checkpoints(): - global params - - try: - models = requests.get(url=f'{params["address"]}/sdapi/v1/sd-models') - options = requests.get(url=f'{params["address"]}/sdapi/v1/options') - options_json = options.json() - params['sd_checkpoint'] = options_json['sd_model_checkpoint'] - params['checkpoint_list'] = [result["title"] for result in models.json()] - except: - params['sd_checkpoint'] = "" - params['checkpoint_list'] = [] - - return gr.update(choices=params['checkpoint_list'], value=params['sd_checkpoint']) - - -def load_checkpoint(checkpoint): - payload = { - "sd_model_checkpoint": checkpoint - } - - try: - requests.post(url=f'{params["address"]}/sdapi/v1/options', json=payload) - except: - pass - - -def get_samplers(): - try: - response = requests.get(url=f'{params["address"]}/sdapi/v1/samplers') - response.raise_for_status() - samplers = [x["name"] for x in response.json()] - except: - samplers = [] - - return samplers - - -def ui(): - - # Gradio elements - # gr.Markdown('### Stable Diffusion API Pictures') # Currently the name of extension is shown as the title - with gr.Accordion("Parameters", open=True, elem_classes="SDAP"): - with gr.Row(): - address = gr.Textbox(placeholder=params['address'], value=params['address'], label='Auto1111\'s WebUI address') - modes_list = ["Manual", "Immersive/Interactive", "Picturebook/Adventure"] - mode = gr.Dropdown(modes_list, value=modes_list[params['mode']], label="Mode of operation", type="index") - with gr.Column(scale=1, min_width=300): - manage_VRAM = gr.Checkbox(value=params['manage_VRAM'], label='Manage VRAM') - save_img = gr.Checkbox(value=params['save_img'], label='Keep original images and use them in chat') - - force_pic = gr.Button("Force the picture response") - suppr_pic = gr.Button("Suppress the picture response") - with gr.Row(): - checkpoint = gr.Dropdown(params['checkpoint_list'], value=params['sd_checkpoint'], label="Checkpoint", type="value") - update_checkpoints = gr.Button("Get list of checkpoints") - - with gr.Accordion("Generation parameters", open=False): - prompt_prefix = gr.Textbox(placeholder=params['prompt_prefix'], value=params['prompt_prefix'], label='Prompt Prefix (best used to describe the look of the character)') - textgen_prefix = gr.Textbox(placeholder=params['textgen_prefix'], value=params['textgen_prefix'], label='textgen prefix (type [subject] where the subject should be placed)') - negative_prompt = gr.Textbox(placeholder=params['negative_prompt'], value=params['negative_prompt'], label='Negative Prompt') - with gr.Row(): - with gr.Column(): - width = gr.Slider(256, 768, value=params['width'], step=64, label='Width') - height = gr.Slider(256, 768, value=params['height'], step=64, label='Height') - with gr.Column(variant="compact", elem_id="sampler_col"): - with gr.Row(elem_id="sampler_row"): - sampler_name = gr.Dropdown(value=params['sampler_name'], label='Sampling method', elem_id="sampler_box") - create_refresh_button(sampler_name, lambda: None, lambda: {'choices': get_samplers()}, 'refresh-button') - steps = gr.Slider(1, 150, value=params['steps'], step=1, label="Sampling steps", elem_id="steps_box") - with gr.Row(): - seed = gr.Number(label="Seed", value=params['seed'], elem_id="seed_box") - cfg_scale = gr.Number(label="CFG Scale", value=params['cfg_scale'], elem_id="cfg_box") - with gr.Column() as hr_options: - restore_faces = gr.Checkbox(value=params['restore_faces'], label='Restore faces') - enable_hr = gr.Checkbox(value=params['enable_hr'], label='Hires. fix') - with gr.Row(visible=params['enable_hr'], elem_classes="hires_opts") as hr_options: - hr_scale = gr.Slider(1, 4, value=params['hr_scale'], step=0.1, label='Upscale by') - denoising_strength = gr.Slider(0, 1, value=params['denoising_strength'], step=0.01, label='Denoising strength') - hr_upscaler = gr.Textbox(placeholder=params['hr_upscaler'], value=params['hr_upscaler'], label='Upscaler') - - # Event functions to update the parameters in the backend - address.change(lambda x: params.update({"address": filter_address(x)}), address, None) - mode.select(lambda x: params.update({"mode": x}), mode, None) - mode.select(lambda x: toggle_generation(x > 1), inputs=mode, outputs=None) - manage_VRAM.change(lambda x: params.update({"manage_VRAM": x}), manage_VRAM, None) - manage_VRAM.change(lambda x: give_VRAM_priority('set' if x else 'reset'), inputs=manage_VRAM, outputs=None) - save_img.change(lambda x: params.update({"save_img": x}), save_img, None) - - address.submit(fn=SD_api_address_update, inputs=address, outputs=address) - prompt_prefix.change(lambda x: params.update({"prompt_prefix": x}), prompt_prefix, None) - textgen_prefix.change(lambda x: params.update({"textgen_prefix": x}), textgen_prefix, None) - negative_prompt.change(lambda x: params.update({"negative_prompt": x}), negative_prompt, None) - width.change(lambda x: params.update({"width": x}), width, None) - height.change(lambda x: params.update({"height": x}), height, None) - hr_scale.change(lambda x: params.update({"hr_scale": x}), hr_scale, None) - denoising_strength.change(lambda x: params.update({"denoising_strength": x}), denoising_strength, None) - restore_faces.change(lambda x: params.update({"restore_faces": x}), restore_faces, None) - hr_upscaler.change(lambda x: params.update({"hr_upscaler": x}), hr_upscaler, None) - enable_hr.change(lambda x: params.update({"enable_hr": x}), enable_hr, None) - enable_hr.change(lambda x: hr_options.update(visible=params["enable_hr"]), enable_hr, hr_options) - update_checkpoints.click(get_checkpoints, None, checkpoint) - checkpoint.change(lambda x: params.update({"sd_checkpoint": x}), checkpoint, None) - checkpoint.change(load_checkpoint, checkpoint, None) - - sampler_name.change(lambda x: params.update({"sampler_name": x}), sampler_name, None) - steps.change(lambda x: params.update({"steps": x}), steps, None) - seed.change(lambda x: params.update({"seed": x}), seed, None) - cfg_scale.change(lambda x: params.update({"cfg_scale": x}), cfg_scale, None) - - force_pic.click(lambda x: toggle_generation(True), inputs=force_pic, outputs=None) - suppr_pic.click(lambda x: toggle_generation(False), inputs=suppr_pic, outputs=None) diff --git a/spaces/EuroPython2022/Write-Stories-Using-Bloom/README.md b/spaces/EuroPython2022/Write-Stories-Using-Bloom/README.md deleted file mode 100644 index 8dc4605af35389e4dce8006aa828efbcc0fd7fdd..0000000000000000000000000000000000000000 --- a/spaces/EuroPython2022/Write-Stories-Using-Bloom/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Write Stories Using Bloom -emoji: 🌸 -colorFrom: gray -colorTo: gray -sdk: gradio -sdk_version: 3.0.25 -app_file: app.py -pinned: false -license: gpl ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Fengbinbin/gpt-academic/crazy_functions/test_project/cpp/libJPG/jpgd.h b/spaces/Fengbinbin/gpt-academic/crazy_functions/test_project/cpp/libJPG/jpgd.h deleted file mode 100644 index a1c0cac61839a6f66a42c341f50d5e36faad9a93..0000000000000000000000000000000000000000 --- a/spaces/Fengbinbin/gpt-academic/crazy_functions/test_project/cpp/libJPG/jpgd.h +++ /dev/null @@ -1,316 +0,0 @@ -// jpgd.h - C++ class for JPEG decompression. -// Public domain, Rich Geldreich -#ifndef JPEG_DECODER_H -#define JPEG_DECODER_H - -#include -#include -#include - -namespace jpgd -{ - typedef unsigned char uint8; - typedef signed short int16; - typedef unsigned short uint16; - typedef unsigned int uint; - typedef signed int int32; - - // Loads a JPEG image from a memory buffer or a file. - // req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA). - // On return, width/height will be set to the image's dimensions, and actual_comps will be set to the either 1 (grayscale) or 3 (RGB). - // Notes: For more control over where and how the source data is read, see the decompress_jpeg_image_from_stream() function below, or call the jpeg_decoder class directly. - // Requesting a 8 or 32bpp image is currently a little faster than 24bpp because the jpeg_decoder class itself currently always unpacks to either 8 or 32bpp. -// BEGIN EPIC MOD -//unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps); - unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps, int format); -// END EPIC MOD - unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps); - - // Success/failure error codes. - enum jpgd_status - { - JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1, - JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE, - JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS, - JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH, - JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER, - JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS, - JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE, - JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER, JPGD_ASSERTION_ERROR, - JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM - }; - - // Input stream interface. - // Derive from this class to read input data from sources other than files or memory. Set m_eof_flag to true when no more data is available. - // The decoder is rather greedy: it will keep on calling this method until its internal input buffer is full, or until the EOF flag is set. - // It the input stream contains data after the JPEG stream's EOI (end of image) marker it will probably be pulled into the internal buffer. - // Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding. - class jpeg_decoder_stream - { - public: - jpeg_decoder_stream() { } - virtual ~jpeg_decoder_stream() { } - - // The read() method is called when the internal input buffer is empty. - // Parameters: - // pBuf - input buffer - // max_bytes_to_read - maximum bytes that can be written to pBuf - // pEOF_flag - set this to true if at end of stream (no more bytes remaining) - // Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0). - // Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full. - virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) = 0; - }; - - // stdio FILE stream class. - class jpeg_decoder_file_stream : public jpeg_decoder_stream - { - jpeg_decoder_file_stream(const jpeg_decoder_file_stream &); - jpeg_decoder_file_stream &operator =(const jpeg_decoder_file_stream &); - - FILE *m_pFile; - bool m_eof_flag, m_error_flag; - - public: - jpeg_decoder_file_stream(); - virtual ~jpeg_decoder_file_stream(); - - bool open(const char *Pfilename); - void close(); - - virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag); - }; - - // Memory stream class. - class jpeg_decoder_mem_stream : public jpeg_decoder_stream - { - const uint8 *m_pSrc_data; - uint m_ofs, m_size; - - public: - jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { } - jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { } - - virtual ~jpeg_decoder_mem_stream() { } - - bool open(const uint8 *pSrc_data, uint size); - void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; } - - virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag); - }; - - // Loads JPEG file from a jpeg_decoder_stream. - unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps); - - enum - { - JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4, - JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 8192, JPGD_MAX_HEIGHT = 16384, JPGD_MAX_WIDTH = 16384 - }; - - typedef int16 jpgd_quant_t; - typedef int16 jpgd_block_t; - - class jpeg_decoder - { - public: - // Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc. - // methods after the constructor is called. You may then either destruct the object, or begin decoding the image by calling begin_decoding(), then decode() on each scanline. - jpeg_decoder(jpeg_decoder_stream *pStream); - - ~jpeg_decoder(); - - // Call this method after constructing the object to begin decompression. - // If JPGD_SUCCESS is returned you may then call decode() on each scanline. - int begin_decoding(); - - // Returns the next scan line. - // For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1). - // Otherwise, it will always point to a buffer containing 32-bit RGBA pixels (A will always be 255, and get_bytes_per_pixel() will return 4). - // Returns JPGD_SUCCESS if a scan line has been returned. - // Returns JPGD_DONE if all scan lines have been returned. - // Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info. - int decode(const void** pScan_line, uint* pScan_line_len); - - inline jpgd_status get_error_code() const { return m_error_code; } - - inline int get_width() const { return m_image_x_size; } - inline int get_height() const { return m_image_y_size; } - - inline int get_num_components() const { return m_comps_in_frame; } - - inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; } - inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); } - - // Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file). - inline int get_total_bytes_read() const { return m_total_bytes_read; } - - private: - jpeg_decoder(const jpeg_decoder &); - jpeg_decoder &operator =(const jpeg_decoder &); - - typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int); - - struct huff_tables - { - bool ac_table; - uint look_up[256]; - uint look_up2[256]; - uint8 code_size[256]; - uint tree[512]; - }; - - struct coeff_buf - { - uint8 *pData; - int block_num_x, block_num_y; - int block_len_x, block_len_y; - int block_size; - }; - - struct mem_block - { - mem_block *m_pNext; - size_t m_used_count; - size_t m_size; - char m_data[1]; - }; - - jmp_buf m_jmp_state; - mem_block *m_pMem_blocks; - int m_image_x_size; - int m_image_y_size; - jpeg_decoder_stream *m_pStream; - int m_progressive_flag; - uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES]; - uint8* m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size - uint8* m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size - jpgd_quant_t* m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables - int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported) - int m_comps_in_frame; // # of components in frame - int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor - int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor - int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector - int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID - int m_comp_h_blocks[JPGD_MAX_COMPONENTS]; - int m_comp_v_blocks[JPGD_MAX_COMPONENTS]; - int m_comps_in_scan; // # of components in scan - int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan - int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector - int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector - int m_spectral_start; // spectral selection start - int m_spectral_end; // spectral selection end - int m_successive_low; // successive approximation low - int m_successive_high; // successive approximation high - int m_max_mcu_x_size; // MCU's max. X size in pixels - int m_max_mcu_y_size; // MCU's max. Y size in pixels - int m_blocks_per_mcu; - int m_max_blocks_per_row; - int m_mcus_per_row, m_mcus_per_col; - int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU]; - int m_total_lines_left; // total # lines left in image - int m_mcu_lines_left; // total # lines left in this MCU - int m_real_dest_bytes_per_scan_line; - int m_dest_bytes_per_scan_line; // rounded up - int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y) - huff_tables* m_pHuff_tabs[JPGD_MAX_HUFF_TABLES]; - coeff_buf* m_dc_coeffs[JPGD_MAX_COMPONENTS]; - coeff_buf* m_ac_coeffs[JPGD_MAX_COMPONENTS]; - int m_eob_run; - int m_block_y_mcu[JPGD_MAX_COMPONENTS]; - uint8* m_pIn_buf_ofs; - int m_in_buf_left; - int m_tem_flag; - bool m_eof_flag; - uint8 m_in_buf_pad_start[128]; - uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128]; - uint8 m_in_buf_pad_end[128]; - int m_bits_left; - uint m_bit_buf; - int m_restart_interval; - int m_restarts_left; - int m_next_restart_num; - int m_max_mcus_per_row; - int m_max_blocks_per_mcu; - int m_expanded_blocks_per_mcu; - int m_expanded_blocks_per_row; - int m_expanded_blocks_per_component; - bool m_freq_domain_chroma_upsample; - int m_max_mcus_per_col; - uint m_last_dc_val[JPGD_MAX_COMPONENTS]; - jpgd_block_t* m_pMCU_coefficients; - int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU]; - uint8* m_pSample_buf; - int m_crr[256]; - int m_cbb[256]; - int m_crg[256]; - int m_cbg[256]; - uint8* m_pScan_line_0; - uint8* m_pScan_line_1; - jpgd_status m_error_code; - bool m_ready_flag; - int m_total_bytes_read; - - void free_all_blocks(); - // BEGIN EPIC MOD - UE_NORETURN void stop_decoding(jpgd_status status); - // END EPIC MOD - void *alloc(size_t n, bool zero = false); - void word_clear(void *p, uint16 c, uint n); - void prep_in_buffer(); - void read_dht_marker(); - void read_dqt_marker(); - void read_sof_marker(); - void skip_variable_marker(); - void read_dri_marker(); - void read_sos_marker(); - int next_marker(); - int process_markers(); - void locate_soi_marker(); - void locate_sof_marker(); - int locate_sos_marker(); - void init(jpeg_decoder_stream * pStream); - void create_look_ups(); - void fix_in_buffer(); - void transform_mcu(int mcu_row); - void transform_mcu_expand(int mcu_row); - coeff_buf* coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y); - inline jpgd_block_t *coeff_buf_getp(coeff_buf *cb, int block_x, int block_y); - void load_next_row(); - void decode_next_row(); - void make_huff_table(int index, huff_tables *pH); - void check_quant_tables(); - void check_huff_tables(); - void calc_mcu_block_order(); - int init_scan(); - void init_frame(); - void process_restart(); - void decode_scan(pDecode_block_func decode_block_func); - void init_progressive(); - void init_sequential(); - void decode_start(); - void decode_init(jpeg_decoder_stream * pStream); - void H2V2Convert(); - void H2V1Convert(); - void H1V2Convert(); - void H1V1Convert(); - void gray_convert(); - void expanded_convert(); - void find_eoi(); - inline uint get_char(); - inline uint get_char(bool *pPadding_flag); - inline void stuff_char(uint8 q); - inline uint8 get_octet(); - inline uint get_bits(int num_bits); - inline uint get_bits_no_markers(int numbits); - inline int huff_decode(huff_tables *pH); - inline int huff_decode(huff_tables *pH, int& extrabits); - static inline uint8 clamp(int i); - static void decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y); - static void decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y); - static void decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y); - static void decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y); - }; - -} // namespace jpgd - -#endif // JPEG_DECODER_H diff --git a/spaces/Fengbinbin/gpt-academic/main.py b/spaces/Fengbinbin/gpt-academic/main.py deleted file mode 100644 index 5932b83ed9b3bffcfbcf613ec3175d253c674bd6..0000000000000000000000000000000000000000 --- a/spaces/Fengbinbin/gpt-academic/main.py +++ /dev/null @@ -1,209 +0,0 @@ -import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染 - -def main(): - import gradio as gr - from request_llm.bridge_all import predict - from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, DummyWith - # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到 - proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY, AVAIL_LLM_MODELS = \ - get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY', 'AVAIL_LLM_MODELS') - - # 如果WEB_PORT是-1, 则随机选取WEB端口 - PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT - if not AUTHENTICATION: AUTHENTICATION = None - - from check_proxy import get_current_version - initial_prompt = "Serve me as a writing and programming assistant." - title_html = f"

ChatGPT 学术优化 {get_current_version()}

" - description = """代码开源和更新[地址🚀](https://github.com/binary-husky/chatgpt_academic),感谢热情的[开发者们❤️](https://github.com/binary-husky/chatgpt_academic/graphs/contributors)""" - - # 问询记录, python 版本建议3.9+(越新越好) - import logging - os.makedirs("gpt_log", exist_ok=True) - try:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO, encoding="utf-8") - except:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO) - print("所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!") - - # 一些普通功能模块 - from core_functional import get_core_functions - functional = get_core_functions() - - # 高级函数插件 - from crazy_functional import get_crazy_functions - crazy_fns = get_crazy_functions() - - # 处理markdown文本格式的转变 - gr.Chatbot.postprocess = format_io - - # 做一些外观色彩上的调整 - from theme import adjust_theme, advanced_css - set_theme = adjust_theme() - - # 代理与自动更新 - from check_proxy import check_proxy, auto_update, warm_up_modules - proxy_info = check_proxy(proxies) - - gr_L1 = lambda: gr.Row().style() - gr_L2 = lambda scale: gr.Column(scale=scale) - if LAYOUT == "TOP-DOWN": - gr_L1 = lambda: DummyWith() - gr_L2 = lambda scale: gr.Row() - CHATBOT_HEIGHT /= 2 - - cancel_handles = [] - with gr.Blocks(title="ChatGPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo: - gr.HTML(title_html) - gr.HTML('''
Duplicate Space请您打开此页面后务必点击上方的“复制空间”(Duplicate Space)按钮!使用时,先在输入框填入API-KEY然后回车。
切忌在“复制空间”(Duplicate Space)之前填入API_KEY或进行提问,否则您的API_KEY将极可能被空间所有者攫取!
支持任意数量的OpenAI的密钥和API2D的密钥共存,例如输入"OpenAI密钥1,API2D密钥2",然后提交,即可同时使用两种模型接口。
''') - cookies = gr.State({'api_key': API_KEY, 'llm_model': LLM_MODEL}) - with gr_L1(): - with gr_L2(scale=2): - chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}") - chatbot.style(height=CHATBOT_HEIGHT) - history = gr.State([]) - with gr_L2(scale=1): - with gr.Accordion("输入区", open=True) as area_input_primary: - with gr.Row(): - txt = gr.Textbox(show_label=False, lines=2, placeholder="输入问题或API密钥,输入多个密钥时,用英文逗号间隔。支持OpenAI密钥和API2D密钥共存。").style(container=False) - with gr.Row(): - submitBtn = gr.Button("提交", variant="primary") - with gr.Row(): - resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm") - stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm") - clearBtn = gr.Button("清除", variant="secondary", visible=False); clearBtn.style(size="sm") - with gr.Row(): - status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}") - with gr.Accordion("基础功能区", open=True) as area_basic_fn: - with gr.Row(): - for k in functional: - variant = functional[k]["Color"] if "Color" in functional[k] else "secondary" - functional[k]["Button"] = gr.Button(k, variant=variant) - with gr.Accordion("函数插件区", open=True) as area_crazy_fn: - with gr.Row(): - gr.Markdown("注意:以下“红颜色”标识的函数插件需从输入区读取路径作为参数.") - with gr.Row(): - for k in crazy_fns: - if not crazy_fns[k].get("AsButton", True): continue - variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary" - crazy_fns[k]["Button"] = gr.Button(k, variant=variant) - crazy_fns[k]["Button"].style(size="sm") - with gr.Row(): - with gr.Accordion("更多函数插件", open=True): - dropdown_fn_list = [k for k in crazy_fns.keys() if not crazy_fns[k].get("AsButton", True)] - with gr.Row(): - dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(container=False) - with gr.Row(): - plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False, - placeholder="这里是特殊函数插件的高级参数输入区").style(container=False) - with gr.Row(): - switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary") - with gr.Row(): - with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up: - file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple") - with gr.Accordion("更换模型 & SysPrompt & 交互界面布局", open=(LAYOUT == "TOP-DOWN")): - system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt) - top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",) - temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",) - max_length_sl = gr.Slider(minimum=256, maximum=4096, value=512, step=1, interactive=True, label="Local LLM MaxLength",) - checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "底部输入区", "输入清除键", "插件参数区"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区") - md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False) - - gr.Markdown(description) - with gr.Accordion("备选输入区", open=True, visible=False) as area_input_secondary: - with gr.Row(): - txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False) - with gr.Row(): - submitBtn2 = gr.Button("提交", variant="primary") - with gr.Row(): - resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn2.style(size="sm") - stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn2.style(size="sm") - clearBtn2 = gr.Button("清除", variant="secondary", visible=False); clearBtn2.style(size="sm") - # 功能区显示开关与功能区的互动 - def fn_area_visibility(a): - ret = {} - ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))}) - ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))}) - ret.update({area_input_primary: gr.update(visible=("底部输入区" not in a))}) - ret.update({area_input_secondary: gr.update(visible=("底部输入区" in a))}) - ret.update({clearBtn: gr.update(visible=("输入清除键" in a))}) - ret.update({clearBtn2: gr.update(visible=("输入清除键" in a))}) - ret.update({plugin_advanced_arg: gr.update(visible=("插件参数区" in a))}) - if "底部输入区" in a: ret.update({txt: gr.update(value="")}) - return ret - checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2, plugin_advanced_arg] ) - # 整理反复出现的控件句柄组合 - input_combo = [cookies, max_length_sl, md_dropdown, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg] - output_combo = [cookies, chatbot, history, status] - predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=input_combo, outputs=output_combo) - # 提交按钮、重置按钮 - cancel_handles.append(txt.submit(**predict_args)) - cancel_handles.append(txt2.submit(**predict_args)) - cancel_handles.append(submitBtn.click(**predict_args)) - cancel_handles.append(submitBtn2.click(**predict_args)) - resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status]) - resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status]) - clearBtn.click(lambda: ("",""), None, [txt, txt2]) - clearBtn2.click(lambda: ("",""), None, [txt, txt2]) - # 基础功能区的回调函数注册 - for k in functional: - click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo) - cancel_handles.append(click_handle) - # 文件上传区,接收文件后与chatbot的互动 - file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes], [chatbot, txt, txt2]) - # 函数插件-固定按钮区 - for k in crazy_fns: - if not crazy_fns[k].get("AsButton", True): continue - click_handle = crazy_fns[k]["Button"].click(ArgsGeneralWrapper(crazy_fns[k]["Function"]), [*input_combo, gr.State(PORT)], output_combo) - click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot]) - cancel_handles.append(click_handle) - # 函数插件-下拉菜单与随变按钮的互动 - def on_dropdown_changed(k): - variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary" - ret = {switchy_bt: gr.update(value=k, variant=variant)} - if crazy_fns[k].get("AdvancedArgs", False): # 是否唤起高级插件参数区 - ret.update({plugin_advanced_arg: gr.update(visible=True, label=f"插件[{k}]的高级参数说明:" + crazy_fns[k].get("ArgsReminder", [f"没有提供高级参数功能说明"]))}) - else: - ret.update({plugin_advanced_arg: gr.update(visible=False, label=f"插件[{k}]不需要高级参数。")}) - return ret - dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt, plugin_advanced_arg] ) - def on_md_dropdown_changed(k): - return {chatbot: gr.update(label="当前模型:"+k)} - md_dropdown.select(on_md_dropdown_changed, [md_dropdown], [chatbot] ) - # 随变按钮的回调函数注册 - def route(k, *args, **kwargs): - if k in [r"打开插件列表", r"请先从插件列表中选择"]: return - yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs) - click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo) - click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot]) - cancel_handles.append(click_handle) - # 终止按钮的回调函数注册 - stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles) - stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles) - - # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数 - def auto_opentab_delay(): - import threading, webbrowser, time - print(f"如果浏览器没有自动打开,请复制并转到以下URL:") - print(f"\t(亮色主题): http://localhost:{PORT}") - print(f"\t(暗色主题): http://localhost:{PORT}/?__dark-theme=true") - def open(): - time.sleep(2) # 打开浏览器 - DARK_MODE, = get_conf('DARK_MODE') - if DARK_MODE: webbrowser.open_new_tab(f"http://localhost:{PORT}/?__dark-theme=true") - else: webbrowser.open_new_tab(f"http://localhost:{PORT}") - threading.Thread(target=open, name="open-browser", daemon=True).start() - threading.Thread(target=auto_update, name="self-upgrade", daemon=True).start() - threading.Thread(target=warm_up_modules, name="warm-up", daemon=True).start() - - auto_opentab_delay() - demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=False, favicon_path="docs/logo.png") - - # 如果需要在二级路径下运行 - # CUSTOM_PATH, = get_conf('CUSTOM_PATH') - # if CUSTOM_PATH != "/": - # from toolbox import run_gradio_in_subpath - # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH) - # else: - # demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png") - -if __name__ == "__main__": - main() diff --git a/spaces/FourthBrainGenAI/DeepLearningAIDemoChatBot/README.md b/spaces/FourthBrainGenAI/DeepLearningAIDemoChatBot/README.md deleted file mode 100644 index 5d1e1684536a6ac258dcf2744da17a7565a67d3e..0000000000000000000000000000000000000000 --- a/spaces/FourthBrainGenAI/DeepLearningAIDemoChatBot/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: DeepLearningAIDemoChatBot -emoji: 👁 -colorFrom: blue -colorTo: purple -sdk: gradio -sdk_version: 3.32.0 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/FrankZxShen/vits-fast-finetuning-pcr/text/symbols.py b/spaces/FrankZxShen/vits-fast-finetuning-pcr/text/symbols.py deleted file mode 100644 index 789e9df25d3d93d1976ef22d15d77f51d170ed00..0000000000000000000000000000000000000000 --- a/spaces/FrankZxShen/vits-fast-finetuning-pcr/text/symbols.py +++ /dev/null @@ -1,76 +0,0 @@ -''' -Defines the set of symbols used in text input to the model. -''' - -# japanese_cleaners -# _pad = '_' -# _punctuation = ',.!?-' -# _letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧ↓↑ ' - - -'''# japanese_cleaners2 -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'AEINOQUabdefghijkmnoprstuvwyzʃʧʦ↓↑ ' -''' - - -'''# korean_cleaners -_pad = '_' -_punctuation = ',.!?…~' -_letters = 'ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㄲㄸㅃㅆㅉㅏㅓㅗㅜㅡㅣㅐㅔ ' -''' - -'''# chinese_cleaners -_pad = '_' -_punctuation = ',。!?—…' -_letters = 'ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩˉˊˇˋ˙ ' -''' - -# # zh_ja_mixture_cleaners -# _pad = '_' -# _punctuation = ',.!?-~…' -# _letters = 'AEINOQUabdefghijklmnoprstuvwyzʃʧʦɯɹəɥ⁼ʰ`→↓↑ ' - - -'''# sanskrit_cleaners -_pad = '_' -_punctuation = '।' -_letters = 'ँंःअआइईउऊऋएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलळवशषसहऽािीुूृॄेैोौ्ॠॢ ' -''' - -'''# cjks_cleaners -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'NQabdefghijklmnopstuvwxyzʃʧʥʦɯɹəɥçɸɾβŋɦː⁼ʰ`^#*=→↓↑ ' -''' - -'''# thai_cleaners -_pad = '_' -_punctuation = '.!? ' -_letters = 'กขฃคฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลวศษสหฬอฮฯะัาำิีึืุูเแโใไๅๆ็่้๊๋์' -''' - -# # cjke_cleaners2 -_pad = '_' -_punctuation = ',.!?-~…' -_letters = 'NQabdefghijklmnopstuvwxyzɑæʃʑçɯɪɔɛɹðəɫɥɸʊɾʒθβŋɦ⁼ʰ`^#*=ˈˌ→↓↑ ' - - -'''# shanghainese_cleaners -_pad = '_' -_punctuation = ',.!?…' -_letters = 'abdfghiklmnopstuvyzøŋȵɑɔɕəɤɦɪɿʑʔʰ̩̃ᴀᴇ15678 ' -''' - -'''# chinese_dialect_cleaners -_pad = '_' -_punctuation = ',.!?~…─' -_letters = '#Nabdefghijklmnoprstuvwxyzæçøŋœȵɐɑɒɓɔɕɗɘəɚɛɜɣɤɦɪɭɯɵɷɸɻɾɿʂʅʊʋʌʏʑʔʦʮʰʷˀː˥˦˧˨˩̥̩̃̚ᴀᴇ↑↓∅ⱼ ' -''' - -# Export all symbols: -symbols = [_pad] + list(_punctuation) + list(_letters) - -# Special symbol ids -SPACE_ID = symbols.index(" ") diff --git a/spaces/FridaZuley/RVC_HFKawaii/infer/modules/onnx/export.py b/spaces/FridaZuley/RVC_HFKawaii/infer/modules/onnx/export.py deleted file mode 100644 index ed4a4162ff04b7e12642fcbe96847f8ea9db06aa..0000000000000000000000000000000000000000 --- a/spaces/FridaZuley/RVC_HFKawaii/infer/modules/onnx/export.py +++ /dev/null @@ -1,52 +0,0 @@ -import torch - -from infer.lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM - - -def export_onnx(ModelPath, ExportedPath): - cpt = torch.load(ModelPath, map_location="cpu") - cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] - vec_channels = 256 if cpt.get("version", "v1") == "v1" else 768 - - test_phone = torch.rand(1, 200, vec_channels) # hidden unit - test_phone_lengths = torch.tensor([200]).long() # hidden unit 长度(貌似没啥用) - test_pitch = torch.randint(size=(1, 200), low=5, high=255) # 基频(单位赫兹) - test_pitchf = torch.rand(1, 200) # nsf基频 - test_ds = torch.LongTensor([0]) # 说话人ID - test_rnd = torch.rand(1, 192, 200) # 噪声(加入随机因子) - - device = "cpu" # 导出时设备(不影响使用模型) - - net_g = SynthesizerTrnMsNSFsidM( - *cpt["config"], is_half=False, version=cpt.get("version", "v1") - ) # fp32导出(C++要支持fp16必须手动将内存重新排列所以暂时不用fp16) - net_g.load_state_dict(cpt["weight"], strict=False) - input_names = ["phone", "phone_lengths", "pitch", "pitchf", "ds", "rnd"] - output_names = [ - "audio", - ] - # net_g.construct_spkmixmap(n_speaker) 多角色混合轨道导出 - torch.onnx.export( - net_g, - ( - test_phone.to(device), - test_phone_lengths.to(device), - test_pitch.to(device), - test_pitchf.to(device), - test_ds.to(device), - test_rnd.to(device), - ), - ExportedPath, - dynamic_axes={ - "phone": [1], - "pitch": [1], - "pitchf": [1], - "rnd": [2], - }, - do_constant_folding=False, - opset_version=13, - verbose=False, - input_names=input_names, - output_names=output_names, - ) - return "Finished" diff --git a/spaces/GAIR/Factool/factool/utils/base/__init__.py b/spaces/GAIR/Factool/factool/utils/base/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Gazoche/text-to-gundam/app.py b/spaces/Gazoche/text-to-gundam/app.py deleted file mode 100644 index 52493337984fc4a0fdbd25083fcdb630eb1daeba..0000000000000000000000000000000000000000 --- a/spaces/Gazoche/text-to-gundam/app.py +++ /dev/null @@ -1,218 +0,0 @@ -from contextlib import nullcontext -import torch -from torch import autocast -from diffusers import StableDiffusionPipeline -import gradio as gr - - -CHECKPOINTS = [ - "epoch-000025", - "epoch-000081" -] - -device = "cuda" if torch.cuda.is_available() else "cpu" -context = autocast if device == "cuda" else nullcontext -dtype = torch.float16 if device == "cuda" else torch.float32 - -def load_pipe(checkpoint): - - pipe = StableDiffusionPipeline.from_pretrained("Gazoche/sd-gundam-diffusers", revision=checkpoint, torch_dtype=dtype) - pipe = pipe.to(device) - - # Disabling the NSFW filter as it's getting confused by the generated images - def null_safety(images, **kwargs): - return images, False - pipe.safety_checker = null_safety - - return pipe - -pipes = { - checkpoint: load_pipe(checkpoint) - for checkpoint in CHECKPOINTS -} - -def infer(prompt, n_samples, steps, scale, model): - - checkpoint = "epoch-000025" if model == "normal" else "epoch-000081" - - in_prompt = "" - guidance_scale = 0.0 - if prompt is not None: - in_prompt = prompt - guidance_scale = scale - - with context("cuda"): - images = pipes[checkpoint]( - n_samples * [in_prompt], - guidance_scale=guidance_scale, - num_inference_steps=steps - ).images - - return images - - -def infer_random(n_samples, steps, scale, model): - return infer(None, n_samples, steps, scale, model) - -css = """ - a { - color: inherit; - text-decoration: underline; - } - .gradio-container { - font-family: 'IBM Plex Sans', sans-serif; - } - .gr-button { - color: white; - border-color: #9d66e5; - background: #9d66e5; - } - input[type='range'] { - accent-color: #9d66e5; - } - .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-options { - 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 .logo{ filter: invert(1); } - .dark .footer { - border-color: #303030; - } - .dark .footer>p { - background: #0b0f19; - } - .acknowledgments h4{ - margin: 1.25em 0 .25em 0; - font-weight: bold; - font-size: 115%; - } -""" - -block = gr.Blocks(css=css) - -with block: - gr.HTML( - """ -
-
-

- Gundam text to image -

-
-

- From a text description, generate a mecha from the anime franchise Mobile Suit Gundam -

-

- Github: https://github.com/Askannz/gundam-stable-diffusion -

-
    -
  • More steps generally means less visual noise but fewer details
  • -
  • Text guidance controls how much the prompt influences the generation
  • -
  • The overfitted model gives cleaner but less original results
  • -
-
- """ - ) - with gr.Group(): - - with gr.Box(): - with gr.Row().style(mobile_collapse=False, equal_height=True): - text = gr.Textbox( - label="Enter your prompt", - show_label=False, - max_lines=1, - placeholder="Enter your prompt", - ).style( - border=(True, False, True, True), - rounded=(True, False, False, True), - container=False, - ) - btn = gr.Button("Generate from prompt").style( - margin=False, - rounded=(False, True, True, False), - ) - - with gr.Box(): - with gr.Row().style(mobile_collapse=False, equal_height=True): - btn_rand = gr.Button("Random").style( - margin=False, - rounded=(False, True, True, False), - ) - - gallery = gr.Gallery( - label="Generated images", show_label=False, elem_id="gallery" - ).style(grid=[2], height="auto") - - - with gr.Row(elem_id="advanced-options"): - samples = gr.Slider(label="Images", minimum=1, maximum=2, value=1, step=1) - steps = gr.Slider(label="Steps", minimum=5, maximum=50, value=25, step=5) - scale = gr.Slider( - label="Text Guidance Scale", minimum=0, maximum=50, value=7.5, step=0.1 - ) - - with gr.Row(elem_id="checkpoint"): - model = gr.Radio(label="Model", choices=["normal", "overfitted"], value="normal") - #model = gr.Radio(label="Model", choices=["normal"], value="normal") - - - text.submit(infer, inputs=[text, samples, steps, scale, model], outputs=gallery) - btn.click(infer, inputs=[text, samples, steps, scale, model], outputs=gallery) - btn_rand.click(infer_random, inputs=[samples, steps, scale, model], outputs=gallery) - gr.HTML( - """ - - """ - ) - -block.launch() diff --git a/spaces/Gen-Sim/Gen-Sim/cliport/generated_tasks/ball_sorting_with_blocks_barrier.py b/spaces/Gen-Sim/Gen-Sim/cliport/generated_tasks/ball_sorting_with_blocks_barrier.py deleted file mode 100644 index b1e7ea17e2252bbebe87f49b1ba1327f8b698406..0000000000000000000000000000000000000000 --- a/spaces/Gen-Sim/Gen-Sim/cliport/generated_tasks/ball_sorting_with_blocks_barrier.py +++ /dev/null @@ -1,62 +0,0 @@ -import numpy as np -import os -import pybullet as p -import random -from cliport.tasks import primitives -from cliport.tasks.grippers import Spatula -from cliport.tasks.task import Task -from cliport.utils import utils -import numpy as np -from cliport.tasks.task import Task -from cliport.utils import utils -import pybullet as p - -class BallSortingWithBlocksBarrier(Task): - """Pick up each ball and place it into the zone of the same color, but without knocking over the blocks.""" - - def __init__(self): - super().__init__() - self.max_steps = 20 - self.lang_template = "place the {color} ball in the {color} zone without knocking over the blocks" - self.task_completed_desc = "done sorting balls." - self.additional_reset() - - def reset(self, env): - super().reset(env) - - # Define colors for the balls and zones - colors = ['red', 'blue', 'green', 'yellow'] - - # Add zones and blocks. - zone_size = (0.12, 0.12, 0) - block_size = (0.04, 0.04, 0.04) - block_urdf = 'block/small.urdf' - zone_urdf = 'zone/zone.urdf' - zones = [] - blocks = [] - for color in colors: - # Add zone of specific color - zone_pose = self.get_random_pose(env, zone_size) - env.add_object(zone_urdf, zone_pose, 'fixed', color=utils.COLORS[color]) - zones.append(zone_pose) - - # Add line of blocks of the same color - for _ in range(5): - block_pose = self.get_random_pose(env, block_size) - block_id = env.add_object(block_urdf, block_pose, color=utils.COLORS[color]) - blocks.append(block_id) - - # Add balls. - ball_size = (0.04, 0.04, 0.04) - ball_urdf = 'ball/ball-template.urdf' - balls = [] - for color in colors: - ball_pose = self.get_random_pose(env, ball_size) - ball_id = env.add_object(ball_urdf, ball_pose, color=utils.COLORS[color]) - balls.append(ball_id) - - # Goal: each ball is in a zone of the same color. - for i in range(len(balls)): - self.add_goal(objs=[balls[i]], matches=np.ones((1, 1)), targ_poses=[zones[i]], replace=False, - rotations=True, metric='pose', params=None, step_max_reward=1/len(balls), - language_goal=self.lang_template.format(color=colors[i])) \ No newline at end of file diff --git a/spaces/Gen-Sim/Gen-Sim/cliport/utils/dataaug.py b/spaces/Gen-Sim/Gen-Sim/cliport/utils/dataaug.py deleted file mode 100644 index 3dcd1890583b6e6d228f434126f7f4e513595d5a..0000000000000000000000000000000000000000 --- a/spaces/Gen-Sim/Gen-Sim/cliport/utils/dataaug.py +++ /dev/null @@ -1,80 +0,0 @@ -# -------------------------------------------------------- -# Fast R-CNN -# Copyright (c) 2015 Microsoft -# Licensed under The MIT License [see LICENSE for details] -# Written by Ross Girshick -# -------------------------------------------------------- - -"""Blob helper functions.""" - -import numpy as np -import cv2 -import torch -import torch.nn as nn -import random - -def chromatic_transform(im, label=None, d_h=None, d_s=None, d_l=None): - """ - Given an image array, add the hue, saturation and luminosity to the image - """ - # Set random hue, luminosity and saturation which ranges from -0.1 to 0.1 - if d_h is None: - d_h = (np.random.rand(1) - 0.5) * 0.02 * 180 - if d_l is None: - d_l = (np.random.rand(1) - 0.5) * 0.2 * 256 - if d_s is None: - d_s = (np.random.rand(1) - 0.5) * 0.2 * 256 - # Convert the BGR to HLS - hls = cv2.cvtColor(im, cv2.COLOR_BGR2HLS) - h, l, s = cv2.split(hls) - # Add the values to the image H, L, S - new_h = (h + d_h) % 180 - new_l = np.clip(l + d_l, 0, 255) - new_s = np.clip(s + d_s, 0, 255) - # Convert the HLS to BGR - new_hls = cv2.merge((new_h, new_l, new_s)).astype('uint8') - new_im = cv2.cvtColor(new_hls, cv2.COLOR_HLS2BGR) - - if label is not None: - I = np.where(label > 0) - new_im[I[0], I[1], :] = im[I[0], I[1], :] - return new_im - - -def add_noise(image): - - # random number - r = np.random.rand(1) - - # gaussian noise - if r < 0.9: - row,col,ch= image.shape - mean = 0 - var = np.random.rand(1) * 0.3 * 256 - sigma = var**0.5 - gauss = sigma * np.random.randn(row,col) + mean - gauss = np.repeat(gauss[:, :, np.newaxis], ch, axis=2) - noisy = image + gauss - noisy = np.clip(noisy, 0, 255) - else: - # motion blur - sizes = [3, 5, 7, 9, 11, 15] - size = sizes[int(np.random.randint(len(sizes), size=1))] - kernel_motion_blur = np.zeros((size, size)) - if np.random.rand(1) < 0.5: - kernel_motion_blur[int((size-1)/2), :] = np.ones(size) - else: - kernel_motion_blur[:, int((size-1)/2)] = np.ones(size) - kernel_motion_blur = kernel_motion_blur / size - noisy = cv2.filter2D(image, -1, kernel_motion_blur) - - return noisy - - -def add_noise_depth(image, level = 0.01): - row,col,ch= image.shape - noise_level = random.uniform(0, level) - gauss = noise_level * np.random.randn(row,col) - gauss = np.repeat(gauss[:, :, np.newaxis], ch, axis=2) - noisy = image + gauss - return noisy diff --git a/spaces/Gradio-Blocks/protGPT2_gradioFold/alphafold/alphafold/model/config.py b/spaces/Gradio-Blocks/protGPT2_gradioFold/alphafold/alphafold/model/config.py deleted file mode 100644 index 03d494f719237339854467c527c2a2e8f188b1e2..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/protGPT2_gradioFold/alphafold/alphafold/model/config.py +++ /dev/null @@ -1,402 +0,0 @@ -# Copyright 2021 DeepMind Technologies Limited -# -# 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. -"""Model config.""" - -import copy -from alphafold.model.tf import shape_placeholders -import ml_collections - - -NUM_RES = shape_placeholders.NUM_RES -NUM_MSA_SEQ = shape_placeholders.NUM_MSA_SEQ -NUM_EXTRA_SEQ = shape_placeholders.NUM_EXTRA_SEQ -NUM_TEMPLATES = shape_placeholders.NUM_TEMPLATES - - -def model_config(name: str) -> ml_collections.ConfigDict: - """Get the ConfigDict of a CASP14 model.""" - - if name not in CONFIG_DIFFS: - raise ValueError(f'Invalid model name {name}.') - cfg = copy.deepcopy(CONFIG) - cfg.update_from_flattened_dict(CONFIG_DIFFS[name]) - return cfg - - -CONFIG_DIFFS = { - 'model_1': { - # Jumper et al. (2021) Suppl. Table 5, Model 1.1.1 - 'data.common.max_extra_msa': 5120, - 'data.common.reduce_msa_clusters_by_max_templates': True, - 'data.common.use_templates': True, - 'model.embeddings_and_evoformer.template.embed_torsion_angles': True, - 'model.embeddings_and_evoformer.template.enabled': True - }, - 'model_2': { - # Jumper et al. (2021) Suppl. Table 5, Model 1.1.2 - 'data.common.reduce_msa_clusters_by_max_templates': True, - 'data.common.use_templates': True, - 'model.embeddings_and_evoformer.template.embed_torsion_angles': True, - 'model.embeddings_and_evoformer.template.enabled': True - }, - 'model_3': { - # Jumper et al. (2021) Suppl. Table 5, Model 1.2.1 - 'data.common.max_extra_msa': 5120, - }, - 'model_4': { - # Jumper et al. (2021) Suppl. Table 5, Model 1.2.2 - 'data.common.max_extra_msa': 5120, - }, - 'model_5': { - # Jumper et al. (2021) Suppl. Table 5, Model 1.2.3 - }, - - # The following models are fine-tuned from the corresponding models above - # with an additional predicted_aligned_error head that can produce - # predicted TM-score (pTM) and predicted aligned errors. - 'model_1_ptm': { - 'data.common.max_extra_msa': 5120, - 'data.common.reduce_msa_clusters_by_max_templates': True, - 'data.common.use_templates': True, - 'model.embeddings_and_evoformer.template.embed_torsion_angles': True, - 'model.embeddings_and_evoformer.template.enabled': True, - 'model.heads.predicted_aligned_error.weight': 0.1 - }, - 'model_2_ptm': { - 'data.common.reduce_msa_clusters_by_max_templates': True, - 'data.common.use_templates': True, - 'model.embeddings_and_evoformer.template.embed_torsion_angles': True, - 'model.embeddings_and_evoformer.template.enabled': True, - 'model.heads.predicted_aligned_error.weight': 0.1 - }, - 'model_3_ptm': { - 'data.common.max_extra_msa': 5120, - 'model.heads.predicted_aligned_error.weight': 0.1 - }, - 'model_4_ptm': { - 'data.common.max_extra_msa': 5120, - 'model.heads.predicted_aligned_error.weight': 0.1 - }, - 'model_5_ptm': { - 'model.heads.predicted_aligned_error.weight': 0.1 - } -} - -CONFIG = ml_collections.ConfigDict({ - 'data': { - 'common': { - 'masked_msa': { - 'profile_prob': 0.1, - 'same_prob': 0.1, - 'uniform_prob': 0.1 - }, - 'max_extra_msa': 1024, - 'msa_cluster_features': True, - 'num_recycle': 3, - 'reduce_msa_clusters_by_max_templates': False, - 'resample_msa_in_recycling': True, - 'template_features': [ - 'template_all_atom_positions', 'template_sum_probs', - 'template_aatype', 'template_all_atom_masks', - 'template_domain_names' - ], - 'unsupervised_features': [ - 'aatype', 'residue_index', 'sequence', 'msa', 'domain_name', - 'num_alignments', 'seq_length', 'between_segment_residues', - 'deletion_matrix' - ], - 'use_templates': False, - }, - 'eval': { - 'feat': { - 'aatype': [NUM_RES], - 'all_atom_mask': [NUM_RES, None], - 'all_atom_positions': [NUM_RES, None, None], - 'alt_chi_angles': [NUM_RES, None], - 'atom14_alt_gt_exists': [NUM_RES, None], - 'atom14_alt_gt_positions': [NUM_RES, None, None], - 'atom14_atom_exists': [NUM_RES, None], - 'atom14_atom_is_ambiguous': [NUM_RES, None], - 'atom14_gt_exists': [NUM_RES, None], - 'atom14_gt_positions': [NUM_RES, None, None], - 'atom37_atom_exists': [NUM_RES, None], - 'backbone_affine_mask': [NUM_RES], - 'backbone_affine_tensor': [NUM_RES, None], - 'bert_mask': [NUM_MSA_SEQ, NUM_RES], - 'chi_angles': [NUM_RES, None], - 'chi_mask': [NUM_RES, None], - 'extra_deletion_value': [NUM_EXTRA_SEQ, NUM_RES], - 'extra_has_deletion': [NUM_EXTRA_SEQ, NUM_RES], - 'extra_msa': [NUM_EXTRA_SEQ, NUM_RES], - 'extra_msa_mask': [NUM_EXTRA_SEQ, NUM_RES], - 'extra_msa_row_mask': [NUM_EXTRA_SEQ], - 'is_distillation': [], - 'msa_feat': [NUM_MSA_SEQ, NUM_RES, None], - 'msa_mask': [NUM_MSA_SEQ, NUM_RES], - 'msa_row_mask': [NUM_MSA_SEQ], - 'pseudo_beta': [NUM_RES, None], - 'pseudo_beta_mask': [NUM_RES], - 'random_crop_to_size_seed': [None], - 'residue_index': [NUM_RES], - 'residx_atom14_to_atom37': [NUM_RES, None], - 'residx_atom37_to_atom14': [NUM_RES, None], - 'resolution': [], - 'rigidgroups_alt_gt_frames': [NUM_RES, None, None], - 'rigidgroups_group_exists': [NUM_RES, None], - 'rigidgroups_group_is_ambiguous': [NUM_RES, None], - 'rigidgroups_gt_exists': [NUM_RES, None], - 'rigidgroups_gt_frames': [NUM_RES, None, None], - 'seq_length': [], - 'seq_mask': [NUM_RES], - 'target_feat': [NUM_RES, None], - 'template_aatype': [NUM_TEMPLATES, NUM_RES], - 'template_all_atom_masks': [NUM_TEMPLATES, NUM_RES, None], - 'template_all_atom_positions': [ - NUM_TEMPLATES, NUM_RES, None, None], - 'template_backbone_affine_mask': [NUM_TEMPLATES, NUM_RES], - 'template_backbone_affine_tensor': [ - NUM_TEMPLATES, NUM_RES, None], - 'template_mask': [NUM_TEMPLATES], - 'template_pseudo_beta': [NUM_TEMPLATES, NUM_RES, None], - 'template_pseudo_beta_mask': [NUM_TEMPLATES, NUM_RES], - 'template_sum_probs': [NUM_TEMPLATES, None], - 'true_msa': [NUM_MSA_SEQ, NUM_RES] - }, - 'fixed_size': True, - 'subsample_templates': False, # We want top templates. - 'masked_msa_replace_fraction': 0.15, - 'max_msa_clusters': 512, - 'max_templates': 4, - 'num_ensemble': 1, - }, - }, - 'model': { - 'embeddings_and_evoformer': { - 'evoformer_num_block': 48, - 'evoformer': { - 'msa_row_attention_with_pair_bias': { - 'dropout_rate': 0.15, - 'gating': True, - 'num_head': 8, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'msa_column_attention': { - 'dropout_rate': 0.0, - 'gating': True, - 'num_head': 8, - 'orientation': 'per_column', - 'shared_dropout': True - }, - 'msa_transition': { - 'dropout_rate': 0.0, - 'num_intermediate_factor': 4, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'outer_product_mean': { - 'chunk_size': 128, - 'dropout_rate': 0.0, - 'num_outer_channel': 32, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'triangle_attention_starting_node': { - 'dropout_rate': 0.25, - 'gating': True, - 'num_head': 4, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'triangle_attention_ending_node': { - 'dropout_rate': 0.25, - 'gating': True, - 'num_head': 4, - 'orientation': 'per_column', - 'shared_dropout': True - }, - 'triangle_multiplication_outgoing': { - 'dropout_rate': 0.25, - 'equation': 'ikc,jkc->ijc', - 'num_intermediate_channel': 128, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'triangle_multiplication_incoming': { - 'dropout_rate': 0.25, - 'equation': 'kjc,kic->ijc', - 'num_intermediate_channel': 128, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'pair_transition': { - 'dropout_rate': 0.0, - 'num_intermediate_factor': 4, - 'orientation': 'per_row', - 'shared_dropout': True - } - }, - 'extra_msa_channel': 64, - 'extra_msa_stack_num_block': 4, - 'max_relative_feature': 32, - 'msa_channel': 256, - 'pair_channel': 128, - 'prev_pos': { - 'min_bin': 3.25, - 'max_bin': 20.75, - 'num_bins': 15 - }, - 'recycle_features': True, - 'recycle_pos': True, - 'seq_channel': 384, - 'template': { - 'attention': { - 'gating': False, - 'key_dim': 64, - 'num_head': 4, - 'value_dim': 64 - }, - 'dgram_features': { - 'min_bin': 3.25, - 'max_bin': 50.75, - 'num_bins': 39 - }, - 'embed_torsion_angles': False, - 'enabled': False, - 'template_pair_stack': { - 'num_block': 2, - 'triangle_attention_starting_node': { - 'dropout_rate': 0.25, - 'gating': True, - 'key_dim': 64, - 'num_head': 4, - 'orientation': 'per_row', - 'shared_dropout': True, - 'value_dim': 64 - }, - 'triangle_attention_ending_node': { - 'dropout_rate': 0.25, - 'gating': True, - 'key_dim': 64, - 'num_head': 4, - 'orientation': 'per_column', - 'shared_dropout': True, - 'value_dim': 64 - }, - 'triangle_multiplication_outgoing': { - 'dropout_rate': 0.25, - 'equation': 'ikc,jkc->ijc', - 'num_intermediate_channel': 64, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'triangle_multiplication_incoming': { - 'dropout_rate': 0.25, - 'equation': 'kjc,kic->ijc', - 'num_intermediate_channel': 64, - 'orientation': 'per_row', - 'shared_dropout': True - }, - 'pair_transition': { - 'dropout_rate': 0.0, - 'num_intermediate_factor': 2, - 'orientation': 'per_row', - 'shared_dropout': True - } - }, - 'max_templates': 4, - 'subbatch_size': 128, - 'use_template_unit_vector': False, - } - }, - 'global_config': { - 'deterministic': False, - 'subbatch_size': 4, - 'use_remat': False, - 'zero_init': True - }, - 'heads': { - 'distogram': { - 'first_break': 2.3125, - 'last_break': 21.6875, - 'num_bins': 64, - 'weight': 0.3 - }, - 'predicted_aligned_error': { - # `num_bins - 1` bins uniformly space the - # [0, max_error_bin A] range. - # The final bin covers [max_error_bin A, +infty] - # 31A gives bins with 0.5A width. - 'max_error_bin': 31., - 'num_bins': 64, - 'num_channels': 128, - 'filter_by_resolution': True, - 'min_resolution': 0.1, - 'max_resolution': 3.0, - 'weight': 0.0, - }, - 'experimentally_resolved': { - 'filter_by_resolution': True, - 'max_resolution': 3.0, - 'min_resolution': 0.1, - 'weight': 0.01 - }, - 'structure_module': { - 'num_layer': 8, - 'fape': { - 'clamp_distance': 10.0, - 'clamp_type': 'relu', - 'loss_unit_distance': 10.0 - }, - 'angle_norm_weight': 0.01, - 'chi_weight': 0.5, - 'clash_overlap_tolerance': 1.5, - 'compute_in_graph_metrics': True, - 'dropout': 0.1, - 'num_channel': 384, - 'num_head': 12, - 'num_layer_in_transition': 3, - 'num_point_qk': 4, - 'num_point_v': 8, - 'num_scalar_qk': 16, - 'num_scalar_v': 16, - 'position_scale': 10.0, - 'sidechain': { - 'atom_clamp_distance': 10.0, - 'num_channel': 128, - 'num_residual_block': 2, - 'weight_frac': 0.5, - 'length_scale': 10., - }, - 'structural_violation_loss_weight': 1.0, - 'violation_tolerance_factor': 12.0, - 'weight': 1.0 - }, - 'predicted_lddt': { - 'filter_by_resolution': True, - 'max_resolution': 3.0, - 'min_resolution': 0.1, - 'num_bins': 50, - 'num_channels': 128, - 'weight': 0.01 - }, - 'masked_msa': { - 'num_output': 23, - 'weight': 2.0 - }, - }, - 'num_recycle': 3, - 'resample_msa_in_recycling': True - }, -}) diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/mmdet/models/dense_heads/rpn_test_mixin.py b/spaces/Gradio-Blocks/uniformer_image_detection/mmdet/models/dense_heads/rpn_test_mixin.py deleted file mode 100644 index 4ce5c66f82595f496e6e55719c1caee75150d568..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/mmdet/models/dense_heads/rpn_test_mixin.py +++ /dev/null @@ -1,59 +0,0 @@ -import sys - -from mmdet.core import merge_aug_proposals - -if sys.version_info >= (3, 7): - from mmdet.utils.contextmanagers import completed - - -class RPNTestMixin(object): - """Test methods of RPN.""" - - if sys.version_info >= (3, 7): - - async def async_simple_test_rpn(self, x, img_metas): - sleep_interval = self.test_cfg.pop('async_sleep_interval', 0.025) - async with completed( - __name__, 'rpn_head_forward', - sleep_interval=sleep_interval): - rpn_outs = self(x) - - proposal_list = self.get_bboxes(*rpn_outs, img_metas) - return proposal_list - - def simple_test_rpn(self, x, img_metas): - """Test without augmentation. - - Args: - x (tuple[Tensor]): Features from the upstream network, each is - a 4D-tensor. - img_metas (list[dict]): Meta info of each image. - - Returns: - list[Tensor]: Proposals of each image. - """ - rpn_outs = self(x) - proposal_list = self.get_bboxes(*rpn_outs, img_metas) - return proposal_list - - def aug_test_rpn(self, feats, img_metas): - samples_per_gpu = len(img_metas[0]) - aug_proposals = [[] for _ in range(samples_per_gpu)] - for x, img_meta in zip(feats, img_metas): - proposal_list = self.simple_test_rpn(x, img_meta) - for i, proposals in enumerate(proposal_list): - aug_proposals[i].append(proposals) - # reorganize the order of 'img_metas' to match the dimensions - # of 'aug_proposals' - aug_img_metas = [] - for i in range(samples_per_gpu): - aug_img_meta = [] - for j in range(len(img_metas)): - aug_img_meta.append(img_metas[j][i]) - aug_img_metas.append(aug_img_meta) - # after merging, proposals will be rescaled to the original image size - merged_proposals = [ - merge_aug_proposals(proposals, aug_img_meta, self.test_cfg) - for proposals, aug_img_meta in zip(aug_proposals, aug_img_metas) - ] - return merged_proposals diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/hrnet/fcn_hr48_480x480_40k_pascal_context_59.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/hrnet/fcn_hr48_480x480_40k_pascal_context_59.py deleted file mode 100644 index 655b4604677b3d4c5eb155e8b2f1cdacbd4194d5..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/hrnet/fcn_hr48_480x480_40k_pascal_context_59.py +++ /dev/null @@ -1,10 +0,0 @@ -_base_ = './fcn_hr18_480x480_40k_pascal_context_59.py' -model = dict( - pretrained='open-mmlab://msra/hrnetv2_w48', - backbone=dict( - extra=dict( - stage2=dict(num_channels=(48, 96)), - stage3=dict(num_channels=(48, 96, 192)), - stage4=dict(num_channels=(48, 96, 192, 384)))), - decode_head=dict( - in_channels=[48, 96, 192, 384], channels=sum([48, 96, 192, 384]))) diff --git a/spaces/HIT-TMG/dialogue-bart-large-chinese/README.md b/spaces/HIT-TMG/dialogue-bart-large-chinese/README.md deleted file mode 100644 index 5d5398d06147f416c3d1c06b37369a7af0295442..0000000000000000000000000000000000000000 --- a/spaces/HIT-TMG/dialogue-bart-large-chinese/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Dialogue Bart Large Chinese -emoji: 📊 -colorFrom: pink -colorTo: purple -sdk: gradio -sdk_version: 3.13.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/HaHaBill/LandShapes-Antarctica/models/stylegan2/stylegan2-pytorch/prepare_data.py b/spaces/HaHaBill/LandShapes-Antarctica/models/stylegan2/stylegan2-pytorch/prepare_data.py deleted file mode 100644 index db49cbda14aca3b2bc0268a4f40cd97f2dd603cc..0000000000000000000000000000000000000000 --- a/spaces/HaHaBill/LandShapes-Antarctica/models/stylegan2/stylegan2-pytorch/prepare_data.py +++ /dev/null @@ -1,82 +0,0 @@ -import argparse -from io import BytesIO -import multiprocessing -from functools import partial - -from PIL import Image -import lmdb -from tqdm import tqdm -from torchvision import datasets -from torchvision.transforms import functional as trans_fn - - -def resize_and_convert(img, size, resample, quality=100): - img = trans_fn.resize(img, size, resample) - img = trans_fn.center_crop(img, size) - buffer = BytesIO() - img.save(buffer, format='jpeg', quality=quality) - val = buffer.getvalue() - - return val - - -def resize_multiple(img, sizes=(128, 256, 512, 1024), resample=Image.LANCZOS, quality=100): - imgs = [] - - for size in sizes: - imgs.append(resize_and_convert(img, size, resample, quality)) - - return imgs - - -def resize_worker(img_file, sizes, resample): - i, file = img_file - img = Image.open(file) - img = img.convert('RGB') - out = resize_multiple(img, sizes=sizes, resample=resample) - - return i, out - - -def prepare(env, dataset, n_worker, sizes=(128, 256, 512, 1024), resample=Image.LANCZOS): - resize_fn = partial(resize_worker, sizes=sizes, resample=resample) - - files = sorted(dataset.imgs, key=lambda x: x[0]) - files = [(i, file) for i, (file, label) in enumerate(files)] - total = 0 - - with multiprocessing.Pool(n_worker) as pool: - for i, imgs in tqdm(pool.imap_unordered(resize_fn, files)): - for size, img in zip(sizes, imgs): - key = f'{size}-{str(i).zfill(5)}'.encode('utf-8') - - with env.begin(write=True) as txn: - txn.put(key, img) - - total += 1 - - with env.begin(write=True) as txn: - txn.put('length'.encode('utf-8'), str(total).encode('utf-8')) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--out', type=str) - parser.add_argument('--size', type=str, default='128,256,512,1024') - parser.add_argument('--n_worker', type=int, default=8) - parser.add_argument('--resample', type=str, default='lanczos') - parser.add_argument('path', type=str) - - args = parser.parse_args() - - resample_map = {'lanczos': Image.LANCZOS, 'bilinear': Image.BILINEAR} - resample = resample_map[args.resample] - - sizes = [int(s.strip()) for s in args.size.split(',')] - - print(f'Make dataset of image sizes:', ', '.join(str(s) for s in sizes)) - - imgset = datasets.ImageFolder(args.path) - - with lmdb.open(args.out, map_size=1024 ** 4, readahead=False) as env: - prepare(env, imgset, args.n_worker, sizes=sizes, resample=resample) diff --git a/spaces/HaloMaster/chinesesummary/fengshen/examples/longformer/README.md b/spaces/HaloMaster/chinesesummary/fengshen/examples/longformer/README.md deleted file mode 100644 index ef4706898b87d2f10eff5df2db24ae3a182ce673..0000000000000000000000000000000000000000 --- a/spaces/HaloMaster/chinesesummary/fengshen/examples/longformer/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# longformer model (Chinese),one model of [Fengshenbang-LM](https://github.com/IDEA-CCNL/Fengshenbang-LM). -We modify the original position code of longformer to rotational position coding,and on the basis of [chinese_roformer_L-12_H-768_A-12.zip](https://github.com/ZhuiyiTechnology/roformer), use 180G of data to continue training - -## Usage -There is no structure of Longformer-base in [Transformers](https://github.com/huggingface/transformers), you can run follow code to get structure of longformer from [Fengshenbang-LM](https://github.com/IDEA-CCNL/Fengshenbang-LM) - - ```shell - git clone https://github.com/IDEA-CCNL/Fengshenbang-LM.git - ``` - -### Load Model -```python -from fengshen import LongformerModel -from fengshen import LongformerConfig -from transformers import BertTokenizer - -tokenizer = BertTokenizer.from_pretrained("IDEA-CCNL/Erlangshen-Longformer-110M") -config = LongformerConfig.from_pretrained("IDEA-CCNL/Erlangshen-Longformer-110M") -model = LongformerModel.from_pretrained("IDEA-CCNL/Erlangshen-Longformer-110M") -``` - - - -## Citation -If you find the resource is useful, please cite the following website in your paper. - -``` -@misc{Fengshenbang-LM, - title={Fengshenbang-LM}, - author={IDEA-CCNL}, - year={2021}, - howpublished={\url{https://github.com/IDEA-CCNL/Fengshenbang-LM}}, -} -``` diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/tasks/frm_text_to_speech.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/tasks/frm_text_to_speech.py deleted file mode 100644 index 1fa9b0f83e742aefce764e2858a81f99db911afd..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/tasks/frm_text_to_speech.py +++ /dev/null @@ -1,56 +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 logging - -from fairseq.data.audio.frm_text_to_speech_dataset import FrmTextToSpeechDatasetCreator -from fairseq.tasks import register_task -from fairseq.tasks.text_to_speech import TextToSpeechTask - - -logging.basicConfig( - format='%(asctime)s | %(levelname)s | %(name)s | %(message)s', - datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO -) -logger = logging.getLogger(__name__) - - -@register_task('frm_text_to_speech') -class FrmTextToSpeechTask(TextToSpeechTask): - @staticmethod - def add_args(parser): - TextToSpeechTask.add_args(parser) - parser.add_argument( - "--do_chunk", action="store_true", help="train on chunks" - ) - parser.add_argument("--chunk_bound", default=-1, type=int) - parser.add_argument("--chunk_init", default=50, type=int) - parser.add_argument("--chunk_incr", default=5, type=int) - parser.add_argument("--add_eos", action="store_true") - parser.add_argument("--dedup", action="store_true") - parser.add_argument("--ref_fpu", default=-1, type=float) - - def load_dataset(self, split, **unused_kwargs): - is_train_split = split.startswith("train") - pre_tokenizer = self.build_tokenizer(self.args) - bpe_tokenizer = self.build_bpe(self.args) - self.datasets[split] = FrmTextToSpeechDatasetCreator.from_tsv( - self.args.data, - self.data_cfg, - split, - self.src_dict, - pre_tokenizer, - bpe_tokenizer, - is_train_split=is_train_split, - n_frames_per_step=self.args.n_frames_per_step, - speaker_to_id=self.speaker_to_id, - do_chunk=self.args.do_chunk, - chunk_bound=self.args.chunk_bound, - chunk_init=self.args.chunk_init, - chunk_incr=self.args.chunk_incr, - add_eos=self.args.add_eos, - dedup=self.args.dedup, - ref_fpu=self.args.ref_fpu - ) diff --git a/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.a8c8aa0f.js b/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.a8c8aa0f.js deleted file mode 100644 index 0a7b65170f0c0d9e324b0e7887362f89fb1a26ed..0000000000000000000000000000000000000000 --- a/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.a8c8aa0f.js +++ /dev/null @@ -1,13264 +0,0 @@ -import{S as al,i as sl,s as cl,c as Mi,a as qr,B as ll,m as Ii,f as bn,D as ul,k as wn,E as hl,j as Fn,o as Di,n as yn,ad as Cf,a5 as Rf,I as dl,e as hr,b as Lo,g as ol,x as Do,F as Cv,aa as Pf,O as Rv,L as Ov,t as Io,h as rl,P as Mv,Q as Iv,X as Dv,R as Lv,T as Nv,U as wv,V as Fv,K as xf}from"./index.396f4a72.js";import{n as Bv}from"./utils.27234e1d.js";import{B as Of}from"./BlockLabel.37da86a3.js";import{F as fl}from"./File.60a988f4.js";import{c as Qr}from"./_commonjsHelpers.88e99c8f.js";import{U as Uv}from"./Upload.5d0148e8.js";import{M as Vv}from"./ModifyUpload.2cfe71e4.js";import{E as _b}from"./Model3D.b44fd6f2.js";var zn={exports:{}};(function(ft,Ze){(function(Ie,y){ft.exports=y()})(typeof self<"u"?self:typeof Qr<"u"?Qr:Qr,function(){return function(Ie){var y={};function f(U){if(y[U])return y[U].exports;var _=y[U]={i:U,l:!1,exports:{}};return Ie[U].call(_.exports,_,_.exports,f),_.l=!0,_.exports}return f.m=Ie,f.c=y,f.d=function(U,_,R){f.o(U,_)||Object.defineProperty(U,_,{enumerable:!0,get:R})},f.r=function(U){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(U,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(U,"__esModule",{value:!0})},f.t=function(U,_){if(1&_&&(U=f(U)),8&_||4&_&&typeof U=="object"&&U&&U.__esModule)return U;var R=Object.create(null);if(f.r(R),Object.defineProperty(R,"default",{enumerable:!0,value:U}),2&_&&typeof U!="string")for(var u in U)f.d(R,u,function(M){return U[M]}.bind(null,u));return R},f.n=function(U){var _=U&&U.__esModule?function(){return U.default}:function(){return U};return f.d(_,"a",_),_},f.o=function(U,_){return Object.prototype.hasOwnProperty.call(U,_)},f.p="",f(f.s=169)}([function(Ie,y,f){f.d(y,"d",function(){return C}),f.d(y,"e",function(){return P}),f.d(y,"f",function(){return m}),f.d(y,"b",function(){return c}),f.d(y,"a",function(){return T}),f.d(y,"c",function(){return S});var U=f(14),_=f(28),R=f(44),u=f(11),M=f(74),C=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&&U.a.WithinEpsilon(this.x,l.x,h)&&U.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,v){v.x=l[h],v.y=l[h+1]},g.CatmullRom=function(l,h,v,E,D){var w=D*D,N=D*w;return new g(.5*(2*h.x+(-l.x+v.x)*D+(2*l.x-5*h.x+4*v.x-E.x)*w+(-l.x+3*h.x-3*v.x+E.x)*N),.5*(2*h.y+(-l.y+v.y)*D+(2*l.y-5*h.y+4*v.y-E.y)*w+(-l.y+3*h.y-3*v.y+E.y)*N))},g.Clamp=function(l,h,v){var E=l.x;E=(E=E>v.x?v.x:E)v.y?v.y:D)h.x?l.x:h.x,l.y>h.y?l.y:h.y)},g.Transform=function(l,h){var v=g.Zero();return g.TransformToRef(l,h,v),v},g.TransformToRef=function(l,h,v){var E=h.m,D=l.x*E[0]+l.y*E[4]+E[12],w=l.x*E[1]+l.y*E[5]+E[13];v.x=D,v.y=w},g.PointInTriangle=function(l,h,v,E){var D=.5*(-v.y*E.x+h.y*(-v.x+E.x)+h.x*(v.y-E.y)+v.x*E.y),w=D<0?-1:1,N=(h.y*E.x-h.x*E.y+(E.y-h.y)*l.x+(h.x-E.x)*l.y)*w,I=(h.x*v.y-h.y*v.x+(h.y-v.y)*l.x+(v.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 v=l.x-h.x,E=l.y-h.y;return v*v+E*E},g.Center=function(l,h){var v=l.add(h);return v.scaleInPlace(.5),v},g.DistanceOfPointFromSegment=function(l,h,v){var E=g.DistanceSquared(h,v);if(E===0)return g.Distance(l,h);var D=v.subtract(h),w=Math.max(0,Math.min(1,g.Dot(l.subtract(h),D)/E)),N=h.add(D.multiplyByFloats(w,w));return g.Distance(l,N)},g}(),P=function(){function g(l,h,v){l===void 0&&(l=0),h===void 0&&(h=0),v===void 0&&(v=0),this._isDirty=!0,this._x=l,this._y=h,this._z=v}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,v){return this.x+=l,this.y+=h,this.z+=v,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,v){return new g(this._x-l,this._y-h,this._z-v)},g.prototype.subtractFromFloatsToRef=function(l,h,v,E){return E.copyFromFloats(this._x-l,this._y-h,this._z-v)},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 v=g.Zero();return this.projectOnPlaneToRef(l,h,v),v},g.prototype.projectOnPlaneToRef=function(l,h,v){var E=l.normal,D=l.d,w=A.Vector3[0];this.subtractToRef(h,w),w.normalize();var N=g.Dot(w,E),I=-(g.Dot(h,E)+D)/N,V=w.scaleInPlace(I);h.addToRef(V,v)},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&&U.a.WithinEpsilon(this._x,l._x,h)&&U.a.WithinEpsilon(this._y,l._y,h)&&U.a.WithinEpsilon(this._z,l._z,h)},g.prototype.equalsToFloats=function(l,h,v){return this._x===l&&this._y===h&&this._z===v},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,v){return new g(this._x*l,this._y*h,this._z*v)},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,v){return lthis._x&&(this.x=l),h>this._y&&(this.y=h),v>this._z&&(this.z=v),this},g.prototype.isNonUniformWithinEpsilon=function(l){var h=Math.abs(this._x),v=Math.abs(this._y);if(!U.a.WithinEpsilon(h,v,l))return!0;var E=Math.abs(this._z);return!U.a.WithinEpsilon(h,E,l)||!U.a.WithinEpsilon(v,E,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(v,E){h[v]=A.Vector3[0][l[E]]})),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,v){return this.subtractToRef(h,A.Vector3[0]),A.Vector3[0].rotateByQuaternionToRef(l,A.Vector3[0]),h.addToRef(A.Vector3[0],v),v},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,v){return this.x=l,this.y=h,this.z=v,this},g.prototype.set=function(l,h,v){return this.copyFromFloats(l,h,v)},g.prototype.setAll=function(l){return this.x=this.y=this.z=l,this},g.GetClipFactor=function(l,h,v,E){var D=g.Dot(l,v)-E;return D/(D-(g.Dot(h,v)-E))},g.GetAngleBetweenVectors=function(l,h,v){var E=l.normalizeToRef(A.Vector3[1]),D=h.normalizeToRef(A.Vector3[2]),w=g.Dot(E,D),N=A.Vector3[3];return g.CrossToRef(E,D,N),g.Dot(N,v)>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,v){v.x=l[h],v.y=l[h+1],v.z=l[h+2]},g.FromFloatArrayToRef=function(l,h,v){return g.FromArrayToRef(l,h,v)},g.FromFloatsToRef=function(l,h,v,E){E.copyFromFloats(l,h,v)},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 v=g.Zero();return g.TransformCoordinatesToRef(l,h,v),v},g.TransformCoordinatesToRef=function(l,h,v){g.TransformCoordinatesFromFloatsToRef(l._x,l._y,l._z,h,v)},g.TransformCoordinatesFromFloatsToRef=function(l,h,v,E,D){var w=E.m,N=l*w[0]+h*w[4]+v*w[8]+w[12],I=l*w[1]+h*w[5]+v*w[9]+w[13],V=l*w[2]+h*w[6]+v*w[10]+w[14],X=1/(l*w[3]+h*w[7]+v*w[11]+w[15]);D.x=N*X,D.y=I*X,D.z=V*X},g.TransformNormal=function(l,h){var v=g.Zero();return g.TransformNormalToRef(l,h,v),v},g.TransformNormalToRef=function(l,h,v){this.TransformNormalFromFloatsToRef(l._x,l._y,l._z,h,v)},g.TransformNormalFromFloatsToRef=function(l,h,v,E,D){var w=E.m;D.x=l*w[0]+h*w[4]+v*w[8],D.y=l*w[1]+h*w[5]+v*w[9],D.z=l*w[2]+h*w[6]+v*w[10]},g.CatmullRom=function(l,h,v,E,D){var w=D*D,N=D*w;return new g(.5*(2*h._x+(-l._x+v._x)*D+(2*l._x-5*h._x+4*v._x-E._x)*w+(-l._x+3*h._x-3*v._x+E._x)*N),.5*(2*h._y+(-l._y+v._y)*D+(2*l._y-5*h._y+4*v._y-E._y)*w+(-l._y+3*h._y-3*v._y+E._y)*N),.5*(2*h._z+(-l._z+v._z)*D+(2*l._z-5*h._z+4*v._z-E._z)*w+(-l._z+3*h._z-3*v._z+E._z)*N))},g.Clamp=function(l,h,v){var E=new g;return g.ClampToRef(l,h,v,E),E},g.ClampToRef=function(l,h,v,E){var D=l._x;D=(D=D>v._x?v._x:D)v._y?v._y:w)v._z?v._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 P(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,v,E){return this.x=l,this.y=h,this.z=v,this.w=E,this},g.prototype.set=function(l,h,v,E){return this.copyFromFloats(l,h,v,E)},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,v){v.x=l[h],v.y=l[h+1],v.z=l[h+2],v.w=l[h+3]},g.FromFloatArrayToRef=function(l,h,v){g.FromArrayToRef(l,h,v)},g.FromFloatsToRef=function(l,h,v,E,D){D.x=l,D.y=h,D.z=v,D.w=E},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 v=l.clone();return v.minimizeInPlace(h),v},g.Maximize=function(l,h){var v=l.clone();return v.maximizeInPlace(h),v},g.Distance=function(l,h){return Math.sqrt(g.DistanceSquared(l,h))},g.DistanceSquared=function(l,h){var v=l.x-h.x,E=l.y-h.y,D=l.z-h.z,w=l.w-h.w;return v*v+E*E+D*D+w*w},g.Center=function(l,h){var v=l.add(h);return v.scaleInPlace(.5),v},g.TransformNormal=function(l,h){var v=g.Zero();return g.TransformNormalToRef(l,h,v),v},g.TransformNormalToRef=function(l,h,v){var E=h.m,D=l.x*E[0]+l.y*E[4]+l.z*E[8],w=l.x*E[1]+l.y*E[5]+l.z*E[9],N=l.x*E[2]+l.y*E[6]+l.z*E[10];v.x=D,v.y=w,v.z=N,v.w=l.w},g.TransformNormalFromFloatsToRef=function(l,h,v,E,D,w){var N=D.m;w.x=l*N[0]+h*N[4]+v*N[8],w.y=l*N[1]+h*N[5]+v*N[9],w.z=l*N[2]+h*N[6]+v*N[10],w.w=E},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,v,E){l===void 0&&(l=0),h===void 0&&(h=0),v===void 0&&(v=0),E===void 0&&(E=1),this._isDirty=!0,this._x=l,this._y=h,this._z=v,this._w=E}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&&U.a.WithinEpsilon(this._x,l._x,h)&&U.a.WithinEpsilon(this._y,l._y,h)&&U.a.WithinEpsilon(this._z,l._z,h)&&U.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,v,E){return this.x=l,this.y=h,this.z=v,this.w=E,this},g.prototype.set=function(l,h,v,E){return this.copyFromFloats(l,h,v,E)},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 v=this._x*l._w+this._y*l._z-this._z*l._y+this._w*l._x,E=-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(v,E,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=P.Zero();return this.toEulerAnglesToRef(h),h},g.prototype.toEulerAnglesToRef=function(l){var h=this._z,v=this._x,E=this._y,D=this._w,w=D*D,N=h*h,I=v*v,V=E*E,X=E*h-v*D;return X<-.4999999?(l.y=2*Math.atan2(E,D),l.x=Math.PI/2,l.z=0):X>.4999999?(l.y=2*Math.atan2(E,D),l.x=-Math.PI/2,l.z=0):(l.z=Math.atan2(2*(v*E+h*D),-N-I+V+w),l.x=Math.asin(-2*(h*E-v*D)),l.y=Math.atan2(2*(h*v+E*D),N-I-V+w)),this},g.prototype.toRotationMatrix=function(l){return T.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 v,E=l.m,D=E[0],w=E[4],N=E[8],I=E[1],V=E[5],X=E[9],j=E[2],ne=E[6],te=E[10],de=D+V+te;de>0?(v=.5/Math.sqrt(de+1),h.w=.25/v,h.x=(ne-X)*v,h.y=(N-j)*v,h.z=(I-w)*v):D>V&&D>te?(v=2*Math.sqrt(1+D-V-te),h.w=(ne-X)/v,h.x=.25*v,h.y=(w+I)/v,h.z=(N+j)/v):V>te?(v=2*Math.sqrt(1+V-D-te),h.w=(N-j)/v,h.x=(w+I)/v,h.y=.25*v,h.z=(X+ne)/v):(v=2*Math.sqrt(1+te-D-V),h.w=(I-w)/v,h.x=(N+j)/v,h.y=(X+ne)/v,h.z=.25*v)},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,v){var E=Math.sin(h/2);return l.normalize(),v.w=Math.cos(h/2),v.x=l._x*E,v.y=l._y*E,v.z=l._z*E,v},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,v){v.x=l[h],v.y=l[h+1],v.z=l[h+2],v.w=l[h+3]},g.FromEulerAngles=function(l,h,v){var E=new g;return g.RotationYawPitchRollToRef(h,l,v,E),E},g.FromEulerAnglesToRef=function(l,h,v,E){return g.RotationYawPitchRollToRef(h,l,v,E),E},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,v){var E=new g;return g.RotationYawPitchRollToRef(l,h,v,E),E},g.RotationYawPitchRollToRef=function(l,h,v,E){var D=.5*v,w=.5*h,N=.5*l,I=Math.sin(D),V=Math.cos(D),X=Math.sin(w),j=Math.cos(w),ne=Math.sin(N),te=Math.cos(N);E.x=te*X*V+ne*j*I,E.y=ne*j*V-te*X*I,E.z=te*j*I-ne*X*V,E.w=te*j*V+ne*X*I},g.RotationAlphaBetaGamma=function(l,h,v){var E=new g;return g.RotationAlphaBetaGammaToRef(l,h,v,E),E},g.RotationAlphaBetaGammaToRef=function(l,h,v,E){var D=.5*(v+l),w=.5*(v-l),N=.5*h;E.x=Math.cos(w)*Math.sin(N),E.y=Math.sin(w)*Math.sin(N),E.z=Math.sin(D)*Math.cos(N),E.w=Math.cos(D)*Math.cos(N)},g.RotationQuaternionFromAxis=function(l,h,v){var E=new g(0,0,0,0);return g.RotationQuaternionFromAxisToRef(l,h,v,E),E},g.RotationQuaternionFromAxisToRef=function(l,h,v,E){var D=A.Matrix[0];T.FromXYZAxesToRef(l.normalize(),h.normalize(),v.normalize(),D),g.FromRotationMatrixToRef(D,E)},g.Slerp=function(l,h,v){var E=g.Identity();return g.SlerpToRef(l,h,v,E),E},g.SlerpToRef=function(l,h,v,E){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-v,D=I?-v:v;else{var V=Math.acos(N),X=1/Math.sin(V);w=Math.sin((1-v)*V)*X,D=I?-Math.sin(v*V)*X:Math.sin(v*V)*X}E.x=w*l._x+D*h._x,E.y=w*l._y+D*h._y,E.z=w*l._z+D*h._z,E.w=w*l._w+D*h._w},g.Hermite=function(l,h,v,E,D){var w=D*D,N=D*w,I=2*N-3*w+1,V=-2*N+3*w,X=N-2*w+D,j=N-w;return new g(l._x*I+v._x*V+h._x*X+E._x*j,l._y*I+v._y*V+h._y*X+E._y*j,l._z*I+v._z*V+h._z*X+E._z*j,l._w*I+v._w*V+h._w*X+E._w*j)},g}(),T=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,v,E){h===void 0&&(h=!1),v===void 0&&(v=!1),E===void 0&&(E=!0),this.updateFlag=g._updateFlagSeed++,this._isIdentity=l,this._isIdentity3x2=l||v,this._isIdentityDirty=!this._isIdentity&&h,this._isIdentity3x2Dirty=!this._isIdentity3x2&&E},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],v=l[1],E=l[2],D=l[3],w=l[4],N=l[5],I=l[6],V=l[7],X=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=X*ee-de*te,Q=X*ae-ne*de,oe=X*pe-de*j;return h*+(N*K-I*$+V*L)+v*-(w*K-I*G+V*Q)+E*+(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 v=this._m,E=h._m,D=l.m,w=0;w<16;w++)E[w]=v[w]+D[w];return h._markAsUpdated(),this},g.prototype.addToSelf=function(l){for(var h=this._m,v=l.m,E=0;E<16;E++)h[E]+=v[E];return this._markAsUpdated(),this},g.prototype.invertToRef=function(l){if(this._isIdentity===!0)return g.IdentityToRef(l),this;var h=this._m,v=h[0],E=h[1],D=h[2],w=h[3],N=h[4],I=h[5],V=h[6],X=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+X*G),k=-(N*$-V*Q+X*oe),H=+(N*L-I*Q+X*re),Z=-(N*G-I*oe+V*re),W=v*Y+E*k+D*H+w*Z;if(W===0)return l.copyFrom(this),this;var q=1/W,he=V*K-ee*X,ge=I*K-ae*X,me=I*ee-ae*V,_e=N*K-pe*X,be=N*ee-pe*V,Pe=N*ae-pe*I,ye=V*de-te*X,Be=I*de-ne*X,ke=I*te-ne*V,We=N*de-j*X,je=N*te-j*V,He=N*ne-j*I,Qe=-(E*$-D*L+w*G),Ge=+(v*$-D*Q+w*oe),nt=-(v*L-E*Q+w*re),$e=+(v*G-E*oe+D*re),ct=+(E*he-D*ge+w*me),st=-(v*he-D*_e+w*be),mt=+(v*ge-E*_e+w*Pe),St=-(v*me-E*be+D*Pe),wt=-(E*ye-D*Be+w*ke),It=+(v*ye-D*We+w*je),Pt=-(v*Be-E*We+w*He),Ot=+(v*ke-E*je+D*He);return g.FromValuesToRef(Y*q,Qe*q,ct*q,wt*q,k*q,Ge*q,st*q,It*q,H*q,nt*q,mt*q,Pt*q,Z*q,$e*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,v){return this._m[12]=l,this._m[13]=h,this._m[14]=v,this._markAsUpdated(),this},g.prototype.addTranslationFromFloats=function(l,h,v){return this._m[12]+=l,this._m[13]+=h,this._m[14]+=v,this._markAsUpdated(),this},g.prototype.setTranslation=function(l){return this.setTranslationFromFloats(l._x,l._y,l._z)},g.prototype.getTranslation=function(){return new P(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 v=this._m;return l[h]=v[0],l[h+1]=v[1],l[h+2]=v[2],l[h+3]=v[3],l[h+4]=v[4],l[h+5]=v[5],l[h+6]=v[6],l[h+7]=v[7],l[h+8]=v[8],l[h+9]=v[9],l[h+10]=v[10],l[h+11]=v[11],l[h+12]=v[12],l[h+13]=v[13],l[h+14]=v[14],l[h+15]=v[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,v){var E=this._m,D=l.m,w=E[0],N=E[1],I=E[2],V=E[3],X=E[4],j=E[5],ne=E[6],te=E[7],de=E[8],pe=E[9],ae=E[10],ee=E[11],K=E[12],$=E[13],L=E[14],G=E[15],Q=D[0],oe=D[1],re=D[2],Y=D[3],k=D[4],H=D[5],Z=D[6],W=D[7],q=D[8],he=D[9],ge=D[10],me=D[11],_e=D[12],be=D[13],Pe=D[14],ye=D[15];return h[v]=w*Q+N*k+I*q+V*_e,h[v+1]=w*oe+N*H+I*he+V*be,h[v+2]=w*re+N*Z+I*ge+V*Pe,h[v+3]=w*Y+N*W+I*me+V*ye,h[v+4]=X*Q+j*k+ne*q+te*_e,h[v+5]=X*oe+j*H+ne*he+te*be,h[v+6]=X*re+j*Z+ne*ge+te*Pe,h[v+7]=X*Y+j*W+ne*me+te*ye,h[v+8]=de*Q+pe*k+ae*q+ee*_e,h[v+9]=de*oe+pe*H+ae*he+ee*be,h[v+10]=de*re+pe*Z+ae*ge+ee*Pe,h[v+11]=de*Y+pe*W+ae*me+ee*ye,h[v+12]=K*Q+$*k+L*q+G*_e,h[v+13]=K*oe+$*H+L*he+G*be,h[v+14]=K*re+$*Z+L*ge+G*Pe,h[v+15]=K*Y+$*W+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 v=this.m,E=h.m;return v[0]===E[0]&&v[1]===E[1]&&v[2]===E[2]&&v[3]===E[3]&&v[4]===E[4]&&v[5]===E[5]&&v[6]===E[6]&&v[7]===E[7]&&v[8]===E[8]&&v[9]===E[9]&&v[10]===E[10]&&v[11]===E[11]&&v[12]===E[12]&&v[13]===E[13]&&v[14]===E[14]&&v[15]===E[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,v){if(this._isIdentity)return v&&v.setAll(0),l&&l.setAll(1),h&&h.copyFromFloats(0,0,0,1),!0;var E=this._m;if(v&&v.copyFromFloats(E[12],E[13],E[14]),(l=l||A.Vector3[0]).x=Math.sqrt(E[0]*E[0]+E[1]*E[1]+E[2]*E[2]),l.y=Math.sqrt(E[4]*E[4]+E[5]*E[5]+E[6]*E[6]),l.z=Math.sqrt(E[8]*E[8]+E[9]*E[9]+E[10]*E[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(E[0]*D,E[1]*D,E[2]*D,0,E[4]*w,E[5]*w,E[6]*w,0,E[8]*N,E[9]*N,E[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,v,E,D){if(l<0||l>3)return this;var w=4*l;return this._m[w+0]=h,this._m[w+1]=v,this._m[w+2]=E,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 v=0;v<16;v++)h._m[v]=this._m[v]*l;return h._markAsUpdated(),this},g.prototype.scaleAndAddToRef=function(l,h){for(var v=0;v<16;v++)h._m[v]+=this._m[v]*l;return h._markAsUpdated(),this},g.prototype.toNormalMatrix=function(l){var h=A.Matrix[0];this.invertToRef(h),h.transposeToRef(l);var v=l._m;g.FromValuesToRef(v[0],v[1],v[2],0,v[4],v[5],v[6],0,v[8],v[9],v[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 v=this._m,E=1/h._x,D=1/h._y,w=1/h._z;return g.FromValuesToRef(v[0]*E,v[1]*E,v[2]*E,0,v[4]*D,v[5]*D,v[6]*D,0,v[8]*w,v[9]*w,v[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 v=new g;return g.FromArrayToRef(l,h,v),v},g.FromArrayToRef=function(l,h,v){for(var E=0;E<16;E++)v._m[E]=l[E+h];v._markAsUpdated()},g.FromFloat32ArrayToRefScaled=function(l,h,v,E){for(var D=0;D<16;D++)E._m[D]=l[D+h]*v;E._markAsUpdated()},Object.defineProperty(g,"IdentityReadOnly",{get:function(){return g._identityReadOnly},enumerable:!1,configurable:!0}),g.FromValuesToRef=function(l,h,v,E,D,w,N,I,V,X,j,ne,te,de,pe,ae,ee){var K=ee._m;K[0]=l,K[1]=h,K[2]=v,K[3]=E,K[4]=D,K[5]=w,K[6]=N,K[7]=I,K[8]=V,K[9]=X,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,v,E,D,w,N,I,V,X,j,ne,te,de,pe,ae){var ee=new g,K=ee._m;return K[0]=l,K[1]=h,K[2]=v,K[3]=E,K[4]=D,K[5]=w,K[6]=N,K[7]=I,K[8]=V,K[9]=X,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,v){var E=new g;return g.ComposeToRef(l,h,v,E),E},g.ComposeToRef=function(l,h,v,E){var D=E._m,w=h._x,N=h._y,I=h._z,V=h._w,X=w+w,j=N+N,ne=I+I,te=w*X,de=w*j,pe=w*ne,ae=N*j,ee=N*ne,K=I*ne,$=V*X,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]=v._x,D[13]=v._y,D[14]=v._z,D[15]=1,E._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 v=Math.sin(l),E=Math.cos(l);g.FromValuesToRef(1,0,0,0,0,E,v,0,0,-v,E,0,0,0,0,1,h),h._updateIdentityStatus(E===1&&v===0)},g.RotationY=function(l){var h=new g;return g.RotationYToRef(l,h),h},g.RotationYToRef=function(l,h){var v=Math.sin(l),E=Math.cos(l);g.FromValuesToRef(E,0,-v,0,0,1,0,0,v,0,E,0,0,0,0,1,h),h._updateIdentityStatus(E===1&&v===0)},g.RotationZ=function(l){var h=new g;return g.RotationZToRef(l,h),h},g.RotationZToRef=function(l,h){var v=Math.sin(l),E=Math.cos(l);g.FromValuesToRef(E,v,0,0,-v,E,0,0,0,0,1,0,0,0,0,1,h),h._updateIdentityStatus(E===1&&v===0)},g.RotationAxis=function(l,h){var v=new g;return g.RotationAxisToRef(l,h,v),v},g.RotationAxisToRef=function(l,h,v){var E=Math.sin(-h),D=Math.cos(-h),w=1-D;l.normalize();var N=v._m;N[0]=l._x*l._x*w+D,N[1]=l._x*l._y*w-l._z*E,N[2]=l._x*l._z*w+l._y*E,N[3]=0,N[4]=l._y*l._x*w+l._z*E,N[5]=l._y*l._y*w+D,N[6]=l._y*l._z*w-l._x*E,N[7]=0,N[8]=l._z*l._x*w-l._y*E,N[9]=l._z*l._y*w+l._x*E,N[10]=l._z*l._z*w+D,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,v._markAsUpdated()},g.RotationAlignToRef=function(l,h,v){var E=P.Cross(h,l),D=P.Dot(h,l),w=1/(1+D),N=v._m;N[0]=E._x*E._x*w+D,N[1]=E._y*E._x*w-E._z,N[2]=E._z*E._x*w+E._y,N[3]=0,N[4]=E._x*E._y*w+E._z,N[5]=E._y*E._y*w+D,N[6]=E._z*E._y*w-E._x,N[7]=0,N[8]=E._x*E._z*w-E._y,N[9]=E._y*E._z*w+E._x,N[10]=E._z*E._z*w+D,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,v._markAsUpdated()},g.RotationYawPitchRoll=function(l,h,v){var E=new g;return g.RotationYawPitchRollToRef(l,h,v,E),E},g.RotationYawPitchRollToRef=function(l,h,v,E){c.RotationYawPitchRollToRef(l,h,v,A.Quaternion[0]),A.Quaternion[0].toRotationMatrix(E)},g.Scaling=function(l,h,v){var E=new g;return g.ScalingToRef(l,h,v,E),E},g.ScalingToRef=function(l,h,v,E){g.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,v,0,0,0,0,1,E),E._updateIdentityStatus(l===1&&h===1&&v===1)},g.Translation=function(l,h,v){var E=new g;return g.TranslationToRef(l,h,v,E),E},g.TranslationToRef=function(l,h,v,E){g.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,l,h,v,1,E),E._updateIdentityStatus(l===0&&h===0&&v===0)},g.Lerp=function(l,h,v){var E=new g;return g.LerpToRef(l,h,v,E),E},g.LerpToRef=function(l,h,v,E){for(var D=E._m,w=l.m,N=h.m,I=0;I<16;I++)D[I]=w[I]*(1-v)+N[I]*v;E._markAsUpdated()},g.DecomposeLerp=function(l,h,v){var E=new g;return g.DecomposeLerpToRef(l,h,v,E),E},g.DecomposeLerpToRef=function(l,h,v,E){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],X=A.Vector3[3];h.decompose(I,V,X);var j=A.Vector3[4];P.LerpToRef(D,I,v,j);var ne=A.Quaternion[2];c.SlerpToRef(w,V,v,ne);var te=A.Vector3[5];P.LerpToRef(N,X,v,te),g.ComposeToRef(j,ne,te,E)},g.LookAtLH=function(l,h,v){var E=new g;return g.LookAtLHToRef(l,h,v,E),E},g.LookAtLHToRef=function(l,h,v,E){var D=A.Vector3[0],w=A.Vector3[1],N=A.Vector3[2];h.subtractToRef(l,N),N.normalize(),P.CrossToRef(v,N,D);var I=D.lengthSquared();I===0?D.x=1:D.normalizeFromLength(Math.sqrt(I)),P.CrossToRef(N,D,w),w.normalize();var V=-P.Dot(D,l),X=-P.Dot(w,l),j=-P.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,X,j,1,E)},g.LookAtRH=function(l,h,v){var E=new g;return g.LookAtRHToRef(l,h,v,E),E},g.LookAtRHToRef=function(l,h,v,E){var D=A.Vector3[0],w=A.Vector3[1],N=A.Vector3[2];l.subtractToRef(h,N),N.normalize(),P.CrossToRef(v,N,D);var I=D.lengthSquared();I===0?D.x=1:D.normalizeFromLength(Math.sqrt(I)),P.CrossToRef(N,D,w),w.normalize();var V=-P.Dot(D,l),X=-P.Dot(w,l),j=-P.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,X,j,1,E)},g.OrthoLH=function(l,h,v,E){var D=new g;return g.OrthoLHToRef(l,h,v,E,D),D},g.OrthoLHToRef=function(l,h,v,E,D){var w=2/l,N=2/h,I=2/(E-v),V=-(E+v)/(E-v);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,v,E,D,w){var N=new g;return g.OrthoOffCenterLHToRef(l,h,v,E,D,w,N),N},g.OrthoOffCenterLHToRef=function(l,h,v,E,D,w,N){var I=2/(h-l),V=2/(E-v),X=2/(w-D),j=-(w+D)/(w-D),ne=(l+h)/(l-h),te=(E+v)/(v-E);g.FromValuesToRef(I,0,0,0,0,V,0,0,0,0,X,0,ne,te,j,1,N),N._markAsUpdated()},g.OrthoOffCenterRH=function(l,h,v,E,D,w){var N=new g;return g.OrthoOffCenterRHToRef(l,h,v,E,D,w,N),N},g.OrthoOffCenterRHToRef=function(l,h,v,E,D,w,N){g.OrthoOffCenterLHToRef(l,h,v,E,D,w,N),N._m[10]*=-1},g.PerspectiveLH=function(l,h,v,E){var D=new g,w=2*v/l,N=2*v/h,I=(E+v)/(E-v),V=-2*E*v/(E-v);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,v,E){var D=new g;return g.PerspectiveFovLHToRef(l,h,v,E,D),D},g.PerspectiveFovLHToRef=function(l,h,v,E,D,w){w===void 0&&(w=!0);var N=v,I=E,V=1/Math.tan(.5*l),X=w?V/h:V,j=w?V:V*h,ne=(I+N)/(I-N),te=-2*I*N/(I-N);g.FromValuesToRef(X,0,0,0,0,j,0,0,0,0,ne,1,0,0,te,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovReverseLHToRef=function(l,h,v,E,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,-v,1,0,0,1,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovRH=function(l,h,v,E){var D=new g;return g.PerspectiveFovRHToRef(l,h,v,E,D),D},g.PerspectiveFovRHToRef=function(l,h,v,E,D,w){w===void 0&&(w=!0);var N=v,I=E,V=1/Math.tan(.5*l),X=w?V/h:V,j=w?V:V*h,ne=-(I+N)/(I-N),te=-2*I*N/(I-N);g.FromValuesToRef(X,0,0,0,0,j,0,0,0,0,ne,-1,0,0,te,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovReverseRHToRef=function(l,h,v,E,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,-v,-1,0,0,-1,0,D),D._updateIdentityStatus(!1)},g.PerspectiveFovWebVRToRef=function(l,h,v,E,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),X=Math.tan(l.rightDegrees*Math.PI/180),j=2/(V+X),ne=2/(N+I),te=E._m;te[0]=j,te[1]=te[2]=te[3]=te[4]=0,te[5]=ne,te[6]=te[7]=0,te[8]=(V-X)*j*.5,te[9]=-(N-I)*ne*.5,te[10]=-v/(h-v),te[11]=1*w,te[12]=te[13]=te[15]=0,te[14]=-2*v*h/(v-h),E._markAsUpdated()},g.GetFinalMatrix=function(l,h,v,E,D,w){var N=l.width,I=l.height,V=l.x,X=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+X,D,1),ne=A.Matrix[0];return h.multiplyToRef(v,ne),ne.multiplyToRef(E,ne),ne.multiply(j)},g.GetAsMatrix2x2=function(l){var h=l.m,v=[h[0],h[1],h[4],h[5]];return M.a.MatrixUse64Bits?v:new Float32Array(v)},g.GetAsMatrix3x3=function(l){var h=l.m,v=[h[0],h[1],h[2],h[4],h[5],h[6],h[8],h[9],h[10]];return M.a.MatrixUse64Bits?v:new Float32Array(v)},g.Transpose=function(l){var h=new g;return g.TransposeToRef(l,h),h},g.TransposeToRef=function(l,h){var v=h._m,E=l.m;v[0]=E[0],v[1]=E[4],v[2]=E[8],v[3]=E[12],v[4]=E[1],v[5]=E[5],v[6]=E[9],v[7]=E[13],v[8]=E[2],v[9]=E[6],v[10]=E[10],v[11]=E[14],v[12]=E[3],v[13]=E[7],v[14]=E[11],v[15]=E[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 v=l.normal.x,E=l.normal.y,D=l.normal.z,w=-2*v,N=-2*E,I=-2*D;g.FromValuesToRef(w*v+1,N*v,I*v,0,w*E,N*E+1,I*E,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,v,E){g.FromValuesToRef(l._x,l._y,l._z,0,h._x,h._y,h._z,0,v._x,v._y,v._z,0,0,0,0,1,E)},g.FromQuaternionToRef=function(l,h){var v=l._x*l._x,E=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,X=l._y*l._z,j=l._x*l._w;h._m[0]=1-2*(E+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+v),h._m[6]=2*(X+j),h._m[7]=0,h._m[8]=2*(I+V),h._m[9]=2*(X-j),h._m[10]=1-2*(E+v),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=R.a.BuildArray(6,P.Zero),g.Matrix=R.a.BuildArray(2,T.Identity),g.Quaternion=R.a.BuildArray(3,c.Zero),g}(),S=function(){function g(){}return g.Vector2=R.a.BuildArray(3,C.Zero),g.Vector3=R.a.BuildArray(13,P.Zero),g.Vector4=R.a.BuildArray(3,m.Zero),g.Quaternion=R.a.BuildArray(2,c.Zero),g.Matrix=R.a.BuildArray(8,T.Identity),g}();u.a.RegisteredTypes["BABYLON.Vector2"]=C,u.a.RegisteredTypes["BABYLON.Vector3"]=P,u.a.RegisteredTypes["BABYLON.Vector4"]=m,u.a.RegisteredTypes["BABYLON.Matrix"]=T},function(Ie,y,f){f.d(y,"d",function(){return _}),f.d(y,"a",function(){return R}),f.d(y,"c",function(){return u}),f.d(y,"b",function(){return M}),f.d(y,"e",function(){return C}),f.d(y,"f",function(){return P});/*! ***************************************************************************** -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 U=function(m,c){return(U=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(T,A){T.__proto__=A}||function(T,A){for(var S in A)Object.prototype.hasOwnProperty.call(A,S)&&(T[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 T(){this.constructor=m}U(m,c),m.prototype=c===null?Object.create(c):(T.prototype=c.prototype,new T)}var R=function(){return(R=Object.assign||function(m){for(var c,T=1,A=arguments.length;T=0;h--)(S=m[h])&&(l=(g<3?S(l):g>3?S(c,T,l):S(c,T))||l);return g>3&&l&&Object.defineProperty(c,T,l),l}function M(m,c,T,A){return new(T||(T=Promise))(function(S,g){function l(E){try{v(A.next(E))}catch(D){g(D)}}function h(E){try{v(A.throw(E))}catch(D){g(D)}}function v(E){var D;E.done?S(E.value):(D=E.value,D instanceof T?D:new T(function(w){w(D)})).then(l,h)}v((A=A.apply(m,c||[])).next())})}function C(m,c){var T,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(v){return function(E){return function(D){if(T)throw new TypeError("Generator is already executing.");for(;l;)try{if(T=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(P.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new U.c),this._onBindObservable},enumerable:!1,configurable:!0}),P.prototype._useFinalCode=function(m,c,T){if(T){var A=T.vertexElement||T.vertex||T.spectorName||T,S=T.fragmentElement||T.fragment||T.spectorName||T;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(P.prototype,"key",{get:function(){return this._key},enumerable:!1,configurable:!0}),P.prototype.isReady=function(){try{return this._isReadyInternal()}catch{return!1}},P.prototype._isReadyInternal=function(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady},P.prototype.getEngine=function(){return this._engine},P.prototype.getPipelineContext=function(){return this._pipelineContext},P.prototype.getAttributesNames=function(){return this._attributesNames},P.prototype.getAttributeLocation=function(m){return this._attributes[m]},P.prototype.getAttributeLocationByName=function(m){return this._attributeLocationByName[m]},P.prototype.getAttributesCount=function(){return this._attributes.length},P.prototype.getUniformIndex=function(m){return this._uniformsNames.indexOf(m)},P.prototype.getUniform=function(m){return this._uniforms[m]},P.prototype.getSamplers=function(){return this._samplerList},P.prototype.getUniformNames=function(){return this._uniformsNames},P.prototype.getUniformBuffersNames=function(){return this._uniformBuffersNamesList},P.prototype.getIndexParameters=function(){return this._indexParameters},P.prototype.getCompilationError=function(){return this._compilationError},P.prototype.allFallbacksProcessed=function(){return this._allFallbacksProcessed},P.prototype.executeWhenCompiled=function(m){var c=this;this.isReady()?m(this):(this.onCompileObservable.add(function(T){m(T)}),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout(function(){c._checkIsReady(null)},16))},P.prototype._checkIsReady=function(m){var c=this;try{if(this._isReadyInternal())return}catch(T){return void this._processCompilationErrors(T,m)}setTimeout(function(){c._checkIsReady(m)},16)},P.prototype._loadShader=function(m,c,T,A){var S;if(typeof HTMLElement<"u"&&m instanceof HTMLElement)return void A(R.a.GetDOMTextContent(m));m.substr(0,7)!=="source:"?m.substr(0,7)!=="base64:"?P.ShadersStore[m+c+"Shader"]?A(P.ShadersStore[m+c+"Shader"]):T&&P.ShadersStore[m+T+"Shader"]?A(P.ShadersStore[m+T+"Shader"]):(S=m[0]==="."||m[0]==="/"||m.indexOf("http")>-1?m:P.ShadersRepository+m,this._engine._loadFile(S+"."+c.toLowerCase()+".fx",A)):A(window.atob(m.substr(7))):A(m.substr(7))},Object.defineProperty(P.prototype,"vertexSourceCode",{get:function(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._vertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"fragmentSourceCode",{get:function(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._fragmentSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"rawVertexSourceCode",{get:function(){return this._rawVertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"rawFragmentSourceCode",{get:function(){return this._rawFragmentSourceCode},enumerable:!1,configurable:!0}),P.prototype._rebuildProgram=function(m,c,T,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 "+(T?"fragment":"vertex")+" code: "+h[l-1])}}return[m,S]},P.prototype._processCompilationErrors=function(m,c){var T,A,S,g,l;c===void 0&&(c=null),this._compilationError=m.message;var h=this._attributesNames,v=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),P.LogShaderCodeOnCompilationError){var E=null,D=null,w=null;!((S=this._pipelineContext)===null||S===void 0)&&S._getVertexShaderCode()&&(w=(T=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1))[0],E=T[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))),E&&u.a.Error(E),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)),v?(this._pipelineContext=null,v.hasMoreFallbacks?(this._allFallbacksProcessed=!1,u.a.Error("Trying next fallback."),this.defines=v.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(P.prototype,"isSupported",{get:function(){return this._compilationError===""},enumerable:!1,configurable:!0}),P.prototype._bindTexture=function(m,c){this._engine._bindTexture(this._samplers[m],c)},P.prototype.setTexture=function(m,c){this._engine.setTexture(this._samplers[m],this._uniforms[m],c)},P.prototype.setDepthStencilTexture=function(m,c){this._engine.setDepthStencilTexture(this._samplers[m],this._uniforms[m],c)},P.prototype.setTextureArray=function(m,c){var T=m+"Ex";if(this._samplerList.indexOf(T+"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 C=new M;return C._observers=this._observers.slice(0),C},M.prototype.hasSpecificMask=function(C){C===void 0&&(C=-1);for(var P=0,m=this._observers;P0},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=(je=_e[me]).getMaterial();if(be){if(be._storeEffectOnSubMeshes){if(!be.isReadyForSubMesh(this,je,he))return!1}else if(!be.isReady(this,he))return!1}}else if(!ge.isReady(this,he))return!1}for(var Pe=0,ye=this.lightSources;Pe0){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 T.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;T.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 T.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(),W=re?H.intermediateDefaultRenderId:H.defaultRenderId;k.visibleInstances[G]=H[Z],!k.visibleInstances[G]&&W&&(k.visibleInstances[G]=H[W])}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,W=H.instancesBuffer,q=16*(k.length+1)*4;H.instancesBufferSizehe&&re++,be!==0&&me++,ge+=be,he=be}if(W[me]++,me>k&&(k=me),ge===0)Y++;else{var Pe=1/ge,ye=0;for(_e=0;_e.001&&H++}}var Be=this.skeleton.bones.length,ke=this.getVerticesData(c.b.MatricesIndicesKind),We=this.getVerticesData(c.b.MatricesIndicesExtraKind),je=0;for(q=0;q=Be||He<0)&&je++}return{skinned:!0,valid:Y===0&&H===0&&je===0,report:"Number of Weights = "+oe/4+` -Maximum influences = `+k+` -Missing Weights = `+Y+` -Not Sorted = `+re+` -Not Normalized = `+H+` -WeightCounts = [`+W+`] -Number of bones = `+Be+` -Bad Bone Indices = `+je}},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 R.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=C.e.Zero(),be=new C.a,Pe=new C.a,ye=0,Be=0;Be0&&(C.a.FromFloat32ArrayToRefScaled(me,Math.floor(16*H[ye+W]),ke,Pe),be.addToSelf(Pe));if(q)for(W=0;W<4;W++)(ke=ge[ye+W])>0&&(C.a.FromFloat32ArrayToRefScaled(me,Math.floor(16*he[ye+W]),ke,Pe),be.addToSelf(Pe));C.e.TransformCoordinatesFromFloatsToRef(oe._sourcePositions[Be],oe._sourcePositions[Be+1],oe._sourcePositions[Be+2],be,_e),_e.toArray(Y,Be),Q&&(C.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:C.e.Zero(),max:C.e.Zero()}},L.Center=function(G){var Q=G instanceof Array?L.MinMax(G):G;return C.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 W,q,he=null;Y=!1}var ge,me=new Array,_e=new Array,be=null,Pe=new Array,ye=null;for(H=0;H
";_._AddLogEntry(M)},_._WarnDisabled=function(R){},_._WarnEnabled=function(R){var u=_._FormatMessage(R);console.warn("BJS - "+u);var M="
"+u+"

";_._AddLogEntry(M)},_._ErrorDisabled=function(R){},_._ErrorEnabled=function(R){_.errorsCount++;var u=_._FormatMessage(R);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(R){(R&_.MessageLogLevel)===_.MessageLogLevel?_.Log=_._LogEnabled:_.Log=_._LogDisabled,(R&_.WarningLogLevel)===_.WarningLogLevel?_.Warn=_._WarnEnabled:_.Warn=_._WarnDisabled,(R&_.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(Ie,y,f){f.d(y,"a",function(){return M}),f.d(y,"b",function(){return C}),f.d(y,"c",function(){return P});var U=f(14),_=f(28),R=f(44),u=f(11),M=function(){function m(c,T,A){c===void 0&&(c=0),T===void 0&&(T=0),A===void 0&&(A=0),this.r=c,this.g=T,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,T){return T===void 0&&(T=0),c[T]=this.r,c[T+1]=this.g,c[T+2]=this.b,this},m.prototype.fromArray=function(c,T){return T===void 0&&(T=0),m.FromArrayToRef(c,T,this),this},m.prototype.toColor4=function(c){return c===void 0&&(c=1),new C(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,T){return T.r=this.r*c.r,T.g=this.g*c.g,T.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,T,A){return this.r===c&&this.g===T&&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,T){return T.r=this.r*c,T.g=this.g*c,T.b=this.b*c,this},m.prototype.scaleAndAddToRef=function(c,T){return T.r+=this.r*c,T.g+=this.g*c,T.b+=this.b*c,this},m.prototype.clampToRef=function(c,T,A){return c===void 0&&(c=0),T===void 0&&(T=1),A.r=U.a.Clamp(this.r,c,T),A.g=U.a.Clamp(this.g,c,T),A.b=U.a.Clamp(this.b,c,T),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,T){return T.r=this.r+c.r,T.g=this.g+c.g,T.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,T){return T.r=this.r-c.r,T.g=this.g-c.g,T.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,T,A){return this.r=c,this.g=T,this.b=A,this},m.prototype.set=function(c,T,A){return this.copyFromFloats(c,T,A)},m.prototype.toHexString=function(){var c=255*this.r|0,T=255*this.g|0,A=255*this.b|0;return"#"+U.a.ToHex(c)+U.a.ToHex(T)+U.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 T=this.r,A=this.g,S=this.b,g=Math.max(T,A,S),l=Math.min(T,A,S),h=0,v=0,E=g,D=g-l;g!==0&&(v=D/g),g!=l&&(g==T?(h=(A-S)/D,A=0&&l<=1?(v=g,E=h):l>=1&&l<=2?(v=h,E=g):l>=2&&l<=3?(E=g,D=h):l>=3&&l<=4?(E=h,D=g):l>=4&&l<=5?(v=h,D=g):l>=5&&l<=6&&(v=g,D=h);var w=A-g;S.set(v+w,E+w,D+w)},m.FromHexString=function(c){if(c.substring(0,1)!=="#"||c.length!==7)return new m(0,0,0);var T=parseInt(c.substring(1,3),16),A=parseInt(c.substring(3,5),16),S=parseInt(c.substring(5,7),16);return m.FromInts(T,A,S)},m.FromArray=function(c,T){return T===void 0&&(T=0),new m(c[T],c[T+1],c[T+2])},m.FromArrayToRef=function(c,T,A){T===void 0&&(T=0),A.r=c[T],A.g=c[T+1],A.b=c[T+2]},m.FromInts=function(c,T,A){return new m(c/255,T/255,A/255)},m.Lerp=function(c,T,A){var S=new m(0,0,0);return m.LerpToRef(c,T,A,S),S},m.LerpToRef=function(c,T,A,S){S.r=c.r+(T.r-c.r)*A,S.g=c.g+(T.g-c.g)*A,S.b=c.b+(T.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}(),C=function(){function m(c,T,A,S){c===void 0&&(c=0),T===void 0&&(T=0),A===void 0&&(A=0),S===void 0&&(S=1),this.r=c,this.g=T,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,T){return T===void 0&&(T=0),c[T]=this.r,c[T+1]=this.g,c[T+2]=this.b,c[T+3]=this.a,this},m.prototype.fromArray=function(c,T){return T===void 0&&(T=0),m.FromArrayToRef(c,T,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,T){return T.r=this.r-c.r,T.g=this.g-c.g,T.b=this.b-c.b,T.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,T){return T.r=this.r*c,T.g=this.g*c,T.b=this.b*c,T.a=this.a*c,this},m.prototype.scaleAndAddToRef=function(c,T){return T.r+=this.r*c,T.g+=this.g*c,T.b+=this.b*c,T.a+=this.a*c,this},m.prototype.clampToRef=function(c,T,A){return c===void 0&&(c=0),T===void 0&&(T=1),A.r=U.a.Clamp(this.r,c,T),A.g=U.a.Clamp(this.g,c,T),A.b=U.a.Clamp(this.b,c,T),A.a=U.a.Clamp(this.a,c,T),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,T){return T.r=this.r*c.r,T.g=this.g*c.g,T.b=this.b*c.b,T.a=this.a*c.a,T},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,T,A,S){return this.r=c,this.g=T,this.b=A,this.a=S,this},m.prototype.set=function(c,T,A,S){return this.copyFromFloats(c,T,A,S)},m.prototype.toHexString=function(c){c===void 0&&(c=!1);var T=255*this.r|0,A=255*this.g|0,S=255*this.b|0;if(c)return"#"+U.a.ToHex(T)+U.a.ToHex(A)+U.a.ToHex(S);var g=255*this.a|0;return"#"+U.a.ToHex(T)+U.a.ToHex(A)+U.a.ToHex(S)+U.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 T=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(T,A,S,g)},m.Lerp=function(c,T,A){var S=new m(0,0,0,0);return m.LerpToRef(c,T,A,S),S},m.LerpToRef=function(c,T,A,S){S.r=c.r+(T.r-c.r)*A,S.g=c.g+(T.g-c.g)*A,S.b=c.b+(T.b-c.b)*A,S.a=c.a+(T.a-c.a)*A},m.FromColor3=function(c,T){return T===void 0&&(T=1),new m(c.r,c.g,c.b,T)},m.FromArray=function(c,T){return T===void 0&&(T=0),new m(c[T],c[T+1],c[T+2],c[T+3])},m.FromArrayToRef=function(c,T,A){T===void 0&&(T=0),A.r=c[T],A.g=c[T+1],A.b=c[T+2],A.a=c[T+3]},m.FromInts=function(c,T,A,S){return new m(c/255,T/255,A/255,S/255)},m.CheckColors4=function(c,T){if(c.length===3*T){for(var A=[],S=0;S0?E.name:w+E.name,(S.a.StartsWith(E.url,"data:")||v.UseSerializedUrlIfAny&&E.url)&&(ae=E.url),X=new v(ae,D,!j,E.invertY,void 0,I)}return X},E,D);return V},v.CreateFromBase64String=function(E,D,w,N,I,V,X,j,ne){return V===void 0&&(V=v.TRILINEAR_SAMPLINGMODE),X===void 0&&(X=null),j===void 0&&(j=null),ne===void 0&&(ne=C.a.TEXTUREFORMAT_RGBA),new v("data:"+D,w,N,I,V,X,j,E,!1,ne)},v.LoadFromDataString=function(E,D,w,N,I,V,X,j,ne,te){return N===void 0&&(N=!1),I===void 0&&(I=!1),V===void 0&&(V=!0),X===void 0&&(X=v.TRILINEAR_SAMPLINGMODE),j===void 0&&(j=null),ne===void 0&&(ne=null),te===void 0&&(te=C.a.TEXTUREFORMAT_RGBA),E.substr(0,5)!=="data:"&&(E="data:"+E),new v(E,w,I,V,X,j,ne,D,N,te)},v.SerializeBuffers=!0,v.ForceSerializeBuffers=!1,v._CubeTextureParser=function(E,D,w){throw m.a.WarnImport("CubeTexture")},v._CreateMirror=function(E,D,w,N){throw m.a.WarnImport("MirrorTexture")},v._CreateRenderTargetTexture=function(E,D,w,N){throw m.a.WarnImport("RenderTargetTexture")},v.NEAREST_SAMPLINGMODE=C.a.TEXTURE_NEAREST_SAMPLINGMODE,v.NEAREST_NEAREST_MIPLINEAR=C.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,v.BILINEAR_SAMPLINGMODE=C.a.TEXTURE_BILINEAR_SAMPLINGMODE,v.LINEAR_LINEAR_MIPNEAREST=C.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,v.TRILINEAR_SAMPLINGMODE=C.a.TEXTURE_TRILINEAR_SAMPLINGMODE,v.LINEAR_LINEAR_MIPLINEAR=C.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,v.NEAREST_NEAREST_MIPNEAREST=C.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,v.NEAREST_LINEAR_MIPNEAREST=C.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,v.NEAREST_LINEAR_MIPLINEAR=C.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,v.NEAREST_LINEAR=C.a.TEXTURE_NEAREST_LINEAR,v.NEAREST_NEAREST=C.a.TEXTURE_NEAREST_NEAREST,v.LINEAR_NEAREST_MIPNEAREST=C.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,v.LINEAR_NEAREST_MIPLINEAR=C.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,v.LINEAR_LINEAR=C.a.TEXTURE_LINEAR_LINEAR,v.LINEAR_NEAREST=C.a.TEXTURE_LINEAR_NEAREST,v.EXPLICIT_MODE=C.a.TEXTURE_EXPLICIT_MODE,v.SPHERICAL_MODE=C.a.TEXTURE_SPHERICAL_MODE,v.PLANAR_MODE=C.a.TEXTURE_PLANAR_MODE,v.CUBIC_MODE=C.a.TEXTURE_CUBIC_MODE,v.PROJECTION_MODE=C.a.TEXTURE_PROJECTION_MODE,v.SKYBOX_MODE=C.a.TEXTURE_SKYBOX_MODE,v.INVCUBIC_MODE=C.a.TEXTURE_INVCUBIC_MODE,v.EQUIRECTANGULAR_MODE=C.a.TEXTURE_EQUIRECTANGULAR_MODE,v.FIXED_EQUIRECTANGULAR_MODE=C.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,v.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=C.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,v.CLAMP_ADDRESSMODE=C.a.TEXTURE_CLAMP_ADDRESSMODE,v.WRAP_ADDRESSMODE=C.a.TEXTURE_WRAP_ADDRESSMODE,v.MIRROR_ADDRESSMODE=C.a.TEXTURE_MIRROR_ADDRESSMODE,v.UseSerializedUrlIfAny=!1,Object(U.c)([Object(_.c)()],v.prototype,"url",void 0),Object(U.c)([Object(_.c)()],v.prototype,"uOffset",void 0),Object(U.c)([Object(_.c)()],v.prototype,"vOffset",void 0),Object(U.c)([Object(_.c)()],v.prototype,"uScale",void 0),Object(U.c)([Object(_.c)()],v.prototype,"vScale",void 0),Object(U.c)([Object(_.c)()],v.prototype,"uAng",void 0),Object(U.c)([Object(_.c)()],v.prototype,"vAng",void 0),Object(U.c)([Object(_.c)()],v.prototype,"wAng",void 0),Object(U.c)([Object(_.c)()],v.prototype,"uRotationCenter",void 0),Object(U.c)([Object(_.c)()],v.prototype,"vRotationCenter",void 0),Object(U.c)([Object(_.c)()],v.prototype,"wRotationCenter",void 0),Object(U.c)([Object(_.c)()],v.prototype,"homogeneousRotationInUVTransform",void 0),Object(U.c)([Object(_.c)()],v.prototype,"isBlocking",null),v}(M.a);P.a.RegisteredTypes["BABYLON.Texture"]=l,_.a._TextureParser=l.Parse},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(){}return _.GetClass=function(R){return this.RegisteredTypes&&this.RegisteredTypes[R]?this.RegisteredTypes[R]:null},_.RegisteredTypes={},_}()},function(Ie,y,f){f.d(y,"b",function(){return l}),f.d(y,"c",function(){return h}),f.d(y,"a",function(){return v});var U=f(6),_=f(38),R=f(8),u=f(41),M=f(57),C=f(21),P=f(49),m=f(22),c=f(56),T=f(145),A=f(104),S=f(122),g=f(120),l=function(){function E(){}return Object.defineProperty(E,"BaseUrl",{get:function(){return c.a.BaseUrl},set:function(D){c.a.BaseUrl=D},enumerable:!1,configurable:!0}),Object.defineProperty(E,"DefaultRetryStrategy",{get:function(){return c.a.DefaultRetryStrategy},set:function(D){c.a.DefaultRetryStrategy=D},enumerable:!1,configurable:!0}),Object.defineProperty(E,"CorsBehavior",{get:function(){return c.a.CorsBehavior},set:function(D){c.a.CorsBehavior=D},enumerable:!1,configurable:!0}),Object.defineProperty(E,"UseFallbackTexture",{get:function(){return m.a.UseFallbackTexture},set:function(D){m.a.UseFallbackTexture=D},enumerable:!1,configurable:!0}),Object.defineProperty(E,"RegisteredExternalClasses",{get:function(){return S.a.RegisteredExternalClasses},set:function(D){S.a.RegisteredExternalClasses=D},enumerable:!1,configurable:!0}),Object.defineProperty(E,"fallbackTexture",{get:function(){return m.a.FallbackTexture},set:function(D){m.a.FallbackTexture=D},enumerable:!1,configurable:!0}),E.FetchToRef=function(D,w,N,I,V,X){var j=4*((Math.abs(D)*N%N|0)+(Math.abs(w)*I%I|0)*N);X.r=V[j]/255,X.g=V[j+1]/255,X.b=V[j+2]/255,X.a=V[j+3]/255},E.Mix=function(D,w,N){return D*(1-N)+w*N},E.Instantiate=function(D){return S.a.Instantiate(D)},E.Slice=function(D,w,N){return D.slice?D.slice(w,N):Array.prototype.slice.call(D,w,N)},E.SliceToArray=function(D,w,N){return Array.isArray(D)?D.slice(w,N):Array.prototype.slice.call(D,w,N)},E.SetImmediate=function(D){A.a.SetImmediate(D)},E.IsExponentOfTwo=function(D){var w=1;do w*=2;while(w=D)break;if(N(te),V&&V()){j.breakLoop();break}}j.executeNext()},X)},I)},E}();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",T.a.Apply()},function(Ie,y,f){f.d(y,"a",function(){return S});var U=f(1),_=f(6),R=f(38),u=f(22),M=f(21),C=f(26),P=f(2),m=f(146),c=f(55),T=f(88),A=f(8),S=(f(123),f(129),f(124),function(g){function l(h,v,E,D){D===void 0&&(D=!1);var w=g.call(this,h,v,E,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(E=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(X){w.onCanvasPointerOutObservable.notifyObservers(X)},N.addEventListener("pointerout",w._onCanvasPointerOut),R.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&&E.audioEngine&&l.AudioEngineFactory&&(l.audioEngine=l.AudioEngineFactory(w.getRenderingCanvas()))}w._connectVREvents(),w.enableOfflineSupport=l.OfflineProviderFactory!==void 0,E.doNotHandleTouchAction||w._disableTouchAction(),w._deterministicLockstep=!!E.deterministicLockstep,w._lockstepMaxSteps=E.lockstepMaxSteps||0,w._timeStep=E.timeStep||1/60}return w._prepareVRComponent(),E.autoEnableWebVR&&w.initWebVR(),w}return Object(U.d)(l,g),Object.defineProperty(l,"NpmPackage",{get:function(){return C.a.NpmPackage},enumerable:!1,configurable:!0}),Object.defineProperty(l,"Version",{get:function(){return C.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,v){for(var E=0;E0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1},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,v){if(!this._renderingCanvas||!g.prototype.setSize.call(this,h,v))return!1;if(this.scenes){for(var E=0;E1&&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=v,h.fragmentShader=E,h.isParallelCompiled||this._finalizePipelineContext(h),N},l.prototype._releaseTexture=function(h){g.prototype._releaseTexture.call(this,h),this.scenes.forEach(function(v){v.postProcesses.forEach(function(E){E._outputTexture==h&&(E._outputTexture=null)}),v.cameras.forEach(function(E){E._postProcesses.forEach(function(D){D&&D._outputTexture==h&&(D._outputTexture=null)})})})},l.prototype._rescaleTexture=function(h,v,E,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:v.width,height:v.height},{generateMipMaps:!1,type:P.a.TEXTURETYPE_UNSIGNED_INT,samplingMode:P.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(X){X._bindTexture("textureSampler",h)};var V=E;V||(V=N.scenes[N.scenes.length-1]),V.postProcessManager.directRender([N._rescalePostProcess],I,!0),N._bindTextureDirectly(N._gl.TEXTURE_2D,v,!0),N._gl.copyTexImage2D(N._gl.TEXTURE_2D,0,D,0,0,v.width,v.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,v,E,D){E===void 0&&(E=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),X=h.isCube?w.TEXTURE_CUBE_MAP:w.TEXTURE_2D;this._bindTextureDirectly(X,h,!0),this._unpackFlipY(h.invertY);var j=w.TEXTURE_2D;h.isCube&&(j=w.TEXTURE_CUBE_MAP_POSITIVE_X+E),w.texImage2D(j,D,V,I,N,v),this._bindTextureDirectly(X,null,!0)},l.prototype.updateRenderTargetTextureSampleCount=function(h,v){if(this.webGLVersion<2||!h)return 1;if(h.samples===v)return v;var E=this._gl;if(v=Math.min(v,this.getCaps().maxMSAASamples),h._depthStencilBuffer&&(E.deleteRenderbuffer(h._depthStencilBuffer),h._depthStencilBuffer=null),h._MSAAFramebuffer&&(E.deleteFramebuffer(h._MSAAFramebuffer),h._MSAAFramebuffer=null),h._MSAARenderBuffer&&(E.deleteRenderbuffer(h._MSAARenderBuffer),h._MSAARenderBuffer=null),v>1&&E.renderbufferStorageMultisample){var D=E.createFramebuffer();if(!D)throw new Error("Unable to create multi sampled framebuffer");h._MSAAFramebuffer=D,this._bindUnboundFramebuffer(h._MSAAFramebuffer);var w=E.createRenderbuffer();if(!w)throw new Error("Unable to create multi sampled framebuffer");E.bindRenderbuffer(E.RENDERBUFFER,w),E.renderbufferStorageMultisample(E.RENDERBUFFER,v,this._getRGBAMultiSampleBufferFormat(h.type),h.width,h.height),E.framebufferRenderbuffer(E.FRAMEBUFFER,E.COLOR_ATTACHMENT0,E.RENDERBUFFER,w),h._MSAARenderBuffer=w}else this._bindUnboundFramebuffer(h._framebuffer);return h.samples=v,h._depthStencilBuffer=this._setupFramebufferDepthAttachments(h._generateStencilBuffer,h._generateDepthBuffer,h.width,h.height,v),this._bindUnboundFramebuffer(null),v},l.prototype.updateTextureComparisonFunction=function(h,v){if(this.webGLVersion!==1){var E=this._gl;h.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),v===0?(E.texParameteri(E.TEXTURE_CUBE_MAP,E.TEXTURE_COMPARE_FUNC,P.a.LEQUAL),E.texParameteri(E.TEXTURE_CUBE_MAP,E.TEXTURE_COMPARE_MODE,E.NONE)):(E.texParameteri(E.TEXTURE_CUBE_MAP,E.TEXTURE_COMPARE_FUNC,v),E.texParameteri(E.TEXTURE_CUBE_MAP,E.TEXTURE_COMPARE_MODE,E.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,h,!0),v===0?(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_COMPARE_FUNC,P.a.LEQUAL),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_COMPARE_MODE,E.NONE)):(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_COMPARE_FUNC,v),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_COMPARE_MODE,E.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),h._comparisonFunction=v}else A.a.Error("WebGL 1 does not support texture comparison.")},l.prototype.createInstancesBuffer=function(h){var v=this._gl.createBuffer();if(!v)throw new Error("Unable to create instance buffer");var E=new T.a(v);return E.capacity=h,this.bindArrayBuffer(E),this._gl.bufferData(this._gl.ARRAY_BUFFER,h,this._gl.DYNAMIC_DRAW),E},l.prototype.deleteInstancesBuffer=function(h){this._gl.deleteBuffer(h)},l.prototype._clientWaitAsync=function(h,v,E){v===void 0&&(v=0),E===void 0&&(E=10);var D=this._gl;return new Promise(function(w,N){var I=function(){var V=D.clientWaitSync(h,v,0);V!=D.WAIT_FAILED?V!=D.TIMEOUT_EXPIRED?w():setTimeout(I,E):N()};I()})},l.prototype._readPixelsAsync=function(h,v,E,D,w,N,I){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");var V=this._gl,X=V.createBuffer();V.bindBuffer(V.PIXEL_PACK_BUFFER,X),V.bufferData(V.PIXEL_PACK_BUFFER,I.byteLength,V.STREAM_READ),V.readPixels(h,v,E,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,X),V.getBufferSubData(V.PIXEL_PACK_BUFFER,0,I),V.bindBuffer(V.PIXEL_PACK_BUFFER,null),V.deleteBuffer(X),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(),R.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)),R.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(R.a.IsWindowObjectExist()){var h=this.loadingScreen;h&&h.displayLoadingUI()}},l.prototype.hideLoadingUI=function(){if(R.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 v=h.requestFullscreen||h.msRequestFullscreen||h.webkitRequestFullscreen||h.mozRequestFullScreen;v&&v.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=P.a.ALPHA_DISABLE,l.ALPHA_ADD=P.a.ALPHA_ADD,l.ALPHA_COMBINE=P.a.ALPHA_COMBINE,l.ALPHA_SUBTRACT=P.a.ALPHA_SUBTRACT,l.ALPHA_MULTIPLY=P.a.ALPHA_MULTIPLY,l.ALPHA_MAXIMIZED=P.a.ALPHA_MAXIMIZED,l.ALPHA_ONEONE=P.a.ALPHA_ONEONE,l.ALPHA_PREMULTIPLIED=P.a.ALPHA_PREMULTIPLIED,l.ALPHA_PREMULTIPLIED_PORTERDUFF=P.a.ALPHA_PREMULTIPLIED_PORTERDUFF,l.ALPHA_INTERPOLATE=P.a.ALPHA_INTERPOLATE,l.ALPHA_SCREENMODE=P.a.ALPHA_SCREENMODE,l.DELAYLOADSTATE_NONE=P.a.DELAYLOADSTATE_NONE,l.DELAYLOADSTATE_LOADED=P.a.DELAYLOADSTATE_LOADED,l.DELAYLOADSTATE_LOADING=P.a.DELAYLOADSTATE_LOADING,l.DELAYLOADSTATE_NOTLOADED=P.a.DELAYLOADSTATE_NOTLOADED,l.NEVER=P.a.NEVER,l.ALWAYS=P.a.ALWAYS,l.LESS=P.a.LESS,l.EQUAL=P.a.EQUAL,l.LEQUAL=P.a.LEQUAL,l.GREATER=P.a.GREATER,l.GEQUAL=P.a.GEQUAL,l.NOTEQUAL=P.a.NOTEQUAL,l.KEEP=P.a.KEEP,l.REPLACE=P.a.REPLACE,l.INCR=P.a.INCR,l.DECR=P.a.DECR,l.INVERT=P.a.INVERT,l.INCR_WRAP=P.a.INCR_WRAP,l.DECR_WRAP=P.a.DECR_WRAP,l.TEXTURE_CLAMP_ADDRESSMODE=P.a.TEXTURE_CLAMP_ADDRESSMODE,l.TEXTURE_WRAP_ADDRESSMODE=P.a.TEXTURE_WRAP_ADDRESSMODE,l.TEXTURE_MIRROR_ADDRESSMODE=P.a.TEXTURE_MIRROR_ADDRESSMODE,l.TEXTUREFORMAT_ALPHA=P.a.TEXTUREFORMAT_ALPHA,l.TEXTUREFORMAT_LUMINANCE=P.a.TEXTUREFORMAT_LUMINANCE,l.TEXTUREFORMAT_LUMINANCE_ALPHA=P.a.TEXTUREFORMAT_LUMINANCE_ALPHA,l.TEXTUREFORMAT_RGB=P.a.TEXTUREFORMAT_RGB,l.TEXTUREFORMAT_RGBA=P.a.TEXTUREFORMAT_RGBA,l.TEXTUREFORMAT_RED=P.a.TEXTUREFORMAT_RED,l.TEXTUREFORMAT_R=P.a.TEXTUREFORMAT_R,l.TEXTUREFORMAT_RG=P.a.TEXTUREFORMAT_RG,l.TEXTUREFORMAT_RED_INTEGER=P.a.TEXTUREFORMAT_RED_INTEGER,l.TEXTUREFORMAT_R_INTEGER=P.a.TEXTUREFORMAT_R_INTEGER,l.TEXTUREFORMAT_RG_INTEGER=P.a.TEXTUREFORMAT_RG_INTEGER,l.TEXTUREFORMAT_RGB_INTEGER=P.a.TEXTUREFORMAT_RGB_INTEGER,l.TEXTUREFORMAT_RGBA_INTEGER=P.a.TEXTUREFORMAT_RGBA_INTEGER,l.TEXTURETYPE_UNSIGNED_BYTE=P.a.TEXTURETYPE_UNSIGNED_BYTE,l.TEXTURETYPE_UNSIGNED_INT=P.a.TEXTURETYPE_UNSIGNED_INT,l.TEXTURETYPE_FLOAT=P.a.TEXTURETYPE_FLOAT,l.TEXTURETYPE_HALF_FLOAT=P.a.TEXTURETYPE_HALF_FLOAT,l.TEXTURETYPE_BYTE=P.a.TEXTURETYPE_BYTE,l.TEXTURETYPE_SHORT=P.a.TEXTURETYPE_SHORT,l.TEXTURETYPE_UNSIGNED_SHORT=P.a.TEXTURETYPE_UNSIGNED_SHORT,l.TEXTURETYPE_INT=P.a.TEXTURETYPE_INT,l.TEXTURETYPE_UNSIGNED_INTEGER=P.a.TEXTURETYPE_UNSIGNED_INTEGER,l.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=P.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,l.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=P.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,l.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=P.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,l.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=P.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,l.TEXTURETYPE_UNSIGNED_INT_24_8=P.a.TEXTURETYPE_UNSIGNED_INT_24_8,l.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=P.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,l.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=P.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,l.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=P.a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,l.TEXTURE_NEAREST_SAMPLINGMODE=P.a.TEXTURE_NEAREST_SAMPLINGMODE,l.TEXTURE_BILINEAR_SAMPLINGMODE=P.a.TEXTURE_BILINEAR_SAMPLINGMODE,l.TEXTURE_TRILINEAR_SAMPLINGMODE=P.a.TEXTURE_TRILINEAR_SAMPLINGMODE,l.TEXTURE_NEAREST_NEAREST_MIPLINEAR=P.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,l.TEXTURE_LINEAR_LINEAR_MIPNEAREST=P.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,l.TEXTURE_LINEAR_LINEAR_MIPLINEAR=P.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,l.TEXTURE_NEAREST_NEAREST_MIPNEAREST=P.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,l.TEXTURE_NEAREST_LINEAR_MIPNEAREST=P.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,l.TEXTURE_NEAREST_LINEAR_MIPLINEAR=P.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,l.TEXTURE_NEAREST_LINEAR=P.a.TEXTURE_NEAREST_LINEAR,l.TEXTURE_NEAREST_NEAREST=P.a.TEXTURE_NEAREST_NEAREST,l.TEXTURE_LINEAR_NEAREST_MIPNEAREST=P.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,l.TEXTURE_LINEAR_NEAREST_MIPLINEAR=P.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,l.TEXTURE_LINEAR_LINEAR=P.a.TEXTURE_LINEAR_LINEAR,l.TEXTURE_LINEAR_NEAREST=P.a.TEXTURE_LINEAR_NEAREST,l.TEXTURE_EXPLICIT_MODE=P.a.TEXTURE_EXPLICIT_MODE,l.TEXTURE_SPHERICAL_MODE=P.a.TEXTURE_SPHERICAL_MODE,l.TEXTURE_PLANAR_MODE=P.a.TEXTURE_PLANAR_MODE,l.TEXTURE_CUBIC_MODE=P.a.TEXTURE_CUBIC_MODE,l.TEXTURE_PROJECTION_MODE=P.a.TEXTURE_PROJECTION_MODE,l.TEXTURE_SKYBOX_MODE=P.a.TEXTURE_SKYBOX_MODE,l.TEXTURE_INVCUBIC_MODE=P.a.TEXTURE_INVCUBIC_MODE,l.TEXTURE_EQUIRECTANGULAR_MODE=P.a.TEXTURE_EQUIRECTANGULAR_MODE,l.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=P.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,l.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=P.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,l.SCALEMODE_FLOOR=P.a.SCALEMODE_FLOOR,l.SCALEMODE_NEAREST=P.a.SCALEMODE_NEAREST,l.SCALEMODE_CEILING=P.a.SCALEMODE_CEILING,l._RescalePostProcessFactory=null,l}(C.a))},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(){}return _.WithinEpsilon=function(R,u,M){M===void 0&&(M=1401298e-51);var C=R-u;return-M<=C&&C<=M},_.ToHex=function(R){var u=R.toString(16);return R<=15?("0"+u).toUpperCase():u.toUpperCase()},_.Sign=function(R){return(R=+R)==0||isNaN(R)?R:R>0?1:-1},_.Clamp=function(R,u,M){return u===void 0&&(u=0),M===void 0&&(M=1),Math.min(M,Math.max(u,R))},_.Log2=function(R){return Math.log(R)*Math.LOG2E},_.Repeat=function(R,u){return R-Math.floor(R/u)*u},_.Normalize=function(R,u,M){return(R-u)/(M-u)},_.Denormalize=function(R,u,M){return R*(M-u)+u},_.DeltaAngle=function(R,u){var M=_.Repeat(u-R,360);return M>180&&(M-=360),M},_.PingPong=function(R,u){var M=_.Repeat(R,2*u);return u-Math.abs(M-u)},_.SmoothStep=function(R,u,M){var C=_.Clamp(M);return u*(C=-2*C*C*C+3*C*C)+R*(1-C)},_.MoveTowards=function(R,u,M){return Math.abs(u-R)<=M?u:R+_.Sign(u-R)*M},_.MoveTowardsAngle=function(R,u,M){var C=_.DeltaAngle(R,u),P=0;return-M180&&(C-=360),R+C*_.Clamp(M)},_.InverseLerp=function(R,u,M){return R!=u?_.Clamp((M-R)/(u-R)):0},_.Hermite=function(R,u,M,C,P){var m=P*P,c=P*m;return R*(2*c-3*m+1)+M*(-2*c+3*m)+u*(c-2*m+P)+C*(c-m)},_.RandomRange=function(R,u){return R===u?R:Math.random()*(u-R)+R},_.RangeToPercent=function(R,u,M){return(R-u)/(M-u)},_.PercentToRange=function(R,u,M){return(M-u)*R+u},_.NormalizeRadians=function(R){return R-=_.TwoPi*Math.floor((R+Math.PI)/_.TwoPi)},_.TwoPi=2*Math.PI,_}()},function(Ie,y,f){f.d(y,"a",function(){return c});var U=f(8),_=f(20),R=f(22),u=f(4),M=f(48),C=f(2),P=f(9),m=f(119),c=function(){function T(){}return T.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)}},T.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},T.BindTextureMatrix=function(A,S,g){var l=A.getTextureMatrix();S.updateMatrix(g+"Matrix",l)},T.GetFogState=function(A,S){return S.fogEnabled&&A.applyFog&&S.fogMode!==_.a.FOGMODE_NONE},T.PrepareDefinesForMisc=function(A,S,g,l,h,v,E){E._areMiscDirty&&(E.LOGARITHMICDEPTH=g,E.POINTSIZE=l,E.FOG=h&&this.GetFogState(A,S),E.NONUNIFORMSCALING=A.nonUniformScaling,E.ALPHATEST=v)},T.PrepareDefinesForFrameBoundValues=function(A,S,g,l,h,v){h===void 0&&(h=null),v===void 0&&(v=!1);var E,D,w,N,I,V,X=!1;E=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!==E&&(g.CLIPPLANE=E,X=!0),g.CLIPPLANE2!==D&&(g.CLIPPLANE2=D,X=!0),g.CLIPPLANE3!==w&&(g.CLIPPLANE3=w,X=!0),g.CLIPPLANE4!==N&&(g.CLIPPLANE4=N,X=!0),g.CLIPPLANE5!==I&&(g.CLIPPLANE5=I,X=!0),g.CLIPPLANE6!==V&&(g.CLIPPLANE6=V,X=!0),g.DEPTHPREPASS!==!S.getColorWrite()&&(g.DEPTHPREPASS=!g.DEPTHPREPASS,X=!0),g.INSTANCES!==l&&(g.INSTANCES=l,X=!0),g.THIN_INSTANCES!==v&&(g.THIN_INSTANCES=v,X=!0),X&&g.markAsUnprocessed()},T.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},T.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)},T.PrepareDefinesForAttributes=function(A,S,g,l,h,v){if(h===void 0&&(h=!1),v===void 0&&(v=!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 E=A.useVertexColors&&A.isVerticesDataPresent(u.b.ColorKind);S.VERTEXCOLOR=E,S.VERTEXALPHA=A.hasVertexAlpha&&E&&v}return l&&this.PrepareDefinesForBones(A,S),h&&this.PrepareDefinesForMorphTargets(A,S),!0},T.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()}},T.PrepareDefinesForPrePass=function(A,S,g){var l=S.PREPASS;if(S._arePrePassDirty){var h=[{type:C.a.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:C.a.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:C.a.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:C.a.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:C.a.PREPASS_ALBEDO_TEXTURE_TYPE,define:"PREPASS_ALBEDO",index:"PREPASS_ALBEDO_INDEX"},{type:C.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 v=0;v0&&(E.shadowEnabled=!0,D.prepareDefines(h,l))}}g.lightmapMode!=M.a.LIGHTMAP_DEFAULT?(E.lightmapMode=!0,h["LIGHTMAPEXCLUDED"+l]=!0,h["LIGHTMAPNOSPECULAR"+l]=g.lightmapMode==M.a.LIGHTMAP_SHADOWSONLY):(h["LIGHTMAPEXCLUDED"+l]=!1,h["LIGHTMAPNOSPECULAR"+l]=!1)},T.PrepareDefinesForLights=function(A,S,g,l,h,v){if(h===void 0&&(h=4),v===void 0&&(v=!1),!g._areLightsDirty)return g._needNormals;var E=0,D={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(A.lightsEnabled&&!v)for(var w=0,N=S.lightSources;w0&&(h=l+v,S.addFallback(h,"LIGHT"+v)),A.SHADOWS||(A["SHADOW"+v]&&S.addFallback(l,"SHADOW"+v),A["SHADOWPCF"+v]&&S.addFallback(l,"SHADOWPCF"+v),A["SHADOWPCSS"+v]&&S.addFallback(l,"SHADOWPCSS"+v),A["SHADOWPOISSON"+v]&&S.addFallback(l,"SHADOWPOISSON"+v),A["SHADOWESM"+v]&&S.addFallback(l,"SHADOWESM"+v),A["SHADOWCLOSEESM"+v]&&S.addFallback(l,"SHADOWCLOSEESM"+v));return h++},T.PrepareAttributesForMorphTargetsInfluencers=function(A,S,g){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=g,this.PrepareAttributesForMorphTargets(A,S,this._TmpMorphInfluencers)},T.PrepareAttributesForMorphTargets=function(A,S,g){var l=g.NUM_MORPH_INFLUENCERS;if(l>0&&R.a.LastCreatedEngine)for(var h=R.a.LastCreatedEngine.getCaps().maxVertexAttribs,v=S.morphTargetManager,E=v&&v.supportsNormals&&g.NORMAL,D=v&&v.supportsTangents&&g.TANGENT,w=v&&v.supportsUVs&&g.UV1,N=0;Nh&&U.a.Error("Cannot add more vertex attributes for mesh "+S.name)},T.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)))},T.PrepareAttributesForInstances=function(A,S){(S.INSTANCES||S.THIN_INSTANCES)&&this.PushAttributesForInstances(A)},T.PushAttributesForInstances=function(A){A.push("world0"),A.push("world1"),A.push("world2"),A.push("world3")},T.BindLightProperties=function(A,S,g){A.transferToEffect(S,g+"")},T.BindLight=function(A,S,g,l,h,v){v===void 0&&(v=!1),A._bindLight(S,g,l,h,v)},T.BindLights=function(A,S,g,l,h,v){h===void 0&&(h=4),v===void 0&&(v=!1);for(var E=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 v=l.getTransformMatrices(A);v&&(S.setMatrices("mBones",v),g&&A.getScene().prePassRenderer&&A.getScene().prePassRenderer.getIndex(C.a.PREPASS_VELOCITY_TEXTURE_TYPE)&&(g.previousBones[A.uniqueId]&&S.setMatrices("mPreviousBones",g.previousBones[A.uniqueId]),T._CopyBonesTransformationMatrices(v,g.previousBones[A.uniqueId])))}}},T._CopyBonesTransformationMatrices=function(A,S){return S.set(A),S},T.BindMorphTargetParameters=function(A,S){var g=A.morphTargetManager;A&&g&&S.setFloatArray("morphTargetInfluences",g.influences)},T.BindLogDepth=function(A,S,g){A.LOGARITHMICDEPTH&&S.setFloat("logarithmicDepthConstant",2/(Math.log(g.activeCamera.maxZ+1)/Math.LN2))},T.BindClipPlane=function(A,S){m.a.BindClipPlane(A,S)},T._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},T._tempFogColor=P.a.Black(),T}()},function(Ie,y,f){f.d(y,"a",function(){return C});var U=f(0),_=f(4),R=f(21),u=f(9),M=f(8),C=function(){function P(){}return P.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}},P.prototype.applyToMesh=function(m,c){return this._applyTo(m,c),this},P.prototype.applyToGeometry=function(m,c){return this._applyTo(m,c),this},P.prototype.updateMesh=function(m){return this._update(m),this},P.prototype.updateGeometry=function(m){return this._update(m),this},P.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},P.prototype._update=function(m,c,T){return this.positions&&m.updateVerticesData(_.b.PositionKind,this.positions,c,T),this.normals&&m.updateVerticesData(_.b.NormalKind,this.normals,c,T),this.tangents&&m.updateVerticesData(_.b.TangentKind,this.tangents,c,T),this.uvs&&m.updateVerticesData(_.b.UVKind,this.uvs,c,T),this.uvs2&&m.updateVerticesData(_.b.UV2Kind,this.uvs2,c,T),this.uvs3&&m.updateVerticesData(_.b.UV3Kind,this.uvs3,c,T),this.uvs4&&m.updateVerticesData(_.b.UV4Kind,this.uvs4,c,T),this.uvs5&&m.updateVerticesData(_.b.UV5Kind,this.uvs5,c,T),this.uvs6&&m.updateVerticesData(_.b.UV6Kind,this.uvs6,c,T),this.colors&&m.updateVerticesData(_.b.ColorKind,this.colors,c,T),this.matricesIndices&&m.updateVerticesData(_.b.MatricesIndicesKind,this.matricesIndices,c,T),this.matricesWeights&&m.updateVerticesData(_.b.MatricesWeightsKind,this.matricesWeights,c,T),this.matricesIndicesExtra&&m.updateVerticesData(_.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,c,T),this.matricesWeightsExtra&&m.updateVerticesData(_.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,c,T),this.indices&&m.setIndices(this.indices,null),this},P.prototype.transform=function(m){var c,T=m.determinant()<0,A=U.e.Zero();if(this.positions){var S=U.e.Zero();for(c=0;cA.bbSize.y?A.bbSize.x:A.bbSize.y;ct=ct>A.bbSize.z?ct:A.bbSize.z,H=A.subDiv.X*re/A.bbSize.x,Z=A.subDiv.Y*re/A.bbSize.y,W=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,W.processTrigger(I.a.ACTION_OnLongPressTrigger,E.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),W=new ae;H?W.doubleClick=!0:W.singleClick=!0,this._checkPrePointerObservable(Y,Z,te.a.POINTERUP)||this._processPointerUp(Y,Z,W)},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 W=te.a.POINTERPICK,q=new te.b(W,k,Y);this._setRayOnPointerInfo(q),Z.onPointerObservable.notifyObservers(q,W)}var he=Y.pickedMesh._getActionManagerForTrigger();if(he&&!H.ignore){he.processTrigger(I.a.ACTION_OnPickUpTrigger,E.a.CreateNew(Y.pickedMesh,k)),!H.hasSwiped&&H.singleClick&&he.processTrigger(I.a.ACTION_OnPickTrigger,E.a.CreateNew(Y.pickedMesh,k));var ge=Y.pickedMesh._getActionManagerForTrigger(I.a.ACTION_OnDoublePickTrigger);H.doubleClick&&ge&&ge.processTrigger(I.a.ACTION_OnDoublePickTrigger,E.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,E.a.CreateNew(this._pickedDownMesh,k))}var Pe=0;Z.onPointerObservable.hasObservers()&&(!H.ignore&&!H.hasSwiped&&(H.singleClick&&Z.onPointerObservable.hasSpecificMask(te.a.POINTERTAP)?Pe=te.a.POINTERTAP:H.doubleClick&&Z.onPointerObservable.hasSpecificMask(te.a.POINTERDOUBLETAP)&&(Pe=te.a.POINTERDOUBLETAP),Pe)&&(q=new te.b(Pe,k,Y),this._setRayOnPointerInfo(q),Z.onPointerObservable.notifyObservers(q,Pe)),H.ignore||(Pe=te.a.POINTERUP,q=new te.b(Pe,k,Y),this._setRayOnPointerInfo(q),Z.onPointerObservable.notifyObservers(q,Pe))),Z.onPointerUp&&!H.ignore&&Z.onPointerUp(k,Y,Pe)},re.prototype.isPointerCaptured=function(Y){return Y===void 0&&(Y=0),this._pointerCaptures[Y]},re.prototype.attachControl=function(Y,k,H,Z){var W=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,Pe){if(!W._meshPickProceed){var ye=q.pick(W._unTranslatedPointerX,W._unTranslatedPointerY,q.pointerDownPredicate,!1,q.cameraToUseForPointers);W._currentPickResult=ye,ye&&(be=ye.hit&&ye.pickedMesh?ye.pickedMesh._getActionManagerForTrigger():null),W._meshPickProceed=!0}return be},this._delayedSimpleClick=function(be,Pe,ye){(Date.now()-W._previousStartingPointerTime>re.DoubleClickDelay&&!W._doubleClickOccured||be!==W._previousButtonPressed)&&(W._doubleClickOccured=!1,Pe.singleClick=!0,Pe.ignore=!1,ye(Pe,W._currentPickResult))},this._initClickEvent=function(be,Pe,ye,Be){var ke=new ae;W._currentPickResult=null;var We=null,je=be.hasSpecificMask(te.a.POINTERPICK)||Pe.hasSpecificMask(te.a.POINTERPICK)||be.hasSpecificMask(te.a.POINTERTAP)||Pe.hasSpecificMask(te.a.POINTERTAP)||be.hasSpecificMask(te.a.POINTERDOUBLETAP)||Pe.hasSpecificMask(te.a.POINTERDOUBLETAP);!je&&de.a&&(We=W._initActionManager(We,ke))&&(je=We.hasPickTriggers);var He=!1;if(je){var Qe=ye.button;if(ke.hasSwiped=W._isPointerSwiping(),!ke.hasSwiped){var Ge=!re.ExclusiveDoubleClickMode;Ge||(Ge=!be.hasSpecificMask(te.a.POINTERDOUBLETAP)&&!Pe.hasSpecificMask(te.a.POINTERDOUBLETAP))&&!de.a.HasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)&&(We=W._initActionManager(We,ke))&&(Ge=!We.hasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)),Ge?(Date.now()-W._previousStartingPointerTime>re.DoubleClickDelay||Qe!==W._previousButtonPressed)&&(ke.singleClick=!0,Be(ke,W._currentPickResult),He=!0):(W._previousDelayedSimpleClickTimeout=W._delayedSimpleClickTimeout,W._delayedSimpleClickTimeout=window.setTimeout(W._delayedSimpleClick.bind(W,Qe,ke,Be),re.DoubleClickDelay));var nt=be.hasSpecificMask(te.a.POINTERDOUBLETAP)||Pe.hasSpecificMask(te.a.POINTERDOUBLETAP);!nt&&de.a.HasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)&&(We=W._initActionManager(We,ke))&&(nt=We.hasSpecificTrigger(I.a.ACTION_OnDoublePickTrigger)),nt&&(Qe===W._previousButtonPressed&&Date.now()-W._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=R.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,W){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,W):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(W){Z.addMesh(W)}))},Y.prototype.removeMesh=function(k,H){var Z=this;H===void 0&&(H=!1);var W=this.meshes.indexOf(k);return W!==-1&&(this.meshes[W]=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)}),W},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,W=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 W=this.getLightByID(k);if(W)return W;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 W=this.getLightByName(k);if(W)return W;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,Pe=this._preActiveMeshStage;be0)for(var Z=this.getActiveSubMeshCandidates(H),W=Z.length,q=0;q1)this.activeCamera.outputRenderTarget._bindFrameBuffer();else{var k=this.activeCamera.outputRenderTarget.getInternalTexture();k?this.getEngine().bindFramebuffer(k):X.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 W=0;W0&&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&&(W.trigger===I.a.ACTION_OnIntersectionExitTrigger&&W._executeCurrent(E.a.CreateNew(H,void 0,he)),H.actionManager.hasSpecificTrigger(I.a.ACTION_OnIntersectionExitTrigger,function(_e){var be=_e instanceof T.a?_e:_e.mesh;return he===be})&&W.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,W=0,q=this._engine.getLockstepMaxSteps(),he=Math.floor(k/H);for(he=Math.min(he,q);k>0&&W0)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 je=0,He=this._afterRenderStage;je-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):(E==null||E<0?this._postProcesses.push(v):this._postProcesses[E]===null?this._postProcesses[E]=v:this._postProcesses.splice(E,0,v),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(v))},h.prototype.detachPostProcess=function(v){var E=this._postProcesses.indexOf(v);E!==-1&&(this._postProcesses[E]=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 C.a.Identity()},h.prototype.getViewMatrix=function(v){return!v&&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(v){this._doNotComputeProjectionMatrix=!0,v!==void 0&&(this._projectionMatrix=v)},h.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},h.prototype.getProjectionMatrix=function(v){var E,D,w,N,I,V,X,j;if(this._doNotComputeProjectionMatrix||!v&&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?C.a.PerspectiveFovReverseRHToRef:C.a.PerspectiveFovRHToRef:de?C.a.PerspectiveFovReverseLHToRef:C.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?C.a.OrthoOffCenterRHToRef((E=this.orthoLeft)!==null&&E!==void 0?E:-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):C.a.OrthoOffCenterLHToRef((I=this.orthoLeft)!==null&&I!==void 0?I:-pe,(V=this.orthoRight)!==null&&V!==void 0?V:pe,(X=this.orthoBottom)!==null&&X!==void 0?X:-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(v,E){if(E===void 0&&(E=!1),this._updateFrustumPlanes(),E&&this.rigCameras.length>0){var D=!1;return this.rigCameras.forEach(function(w){w._updateFrustumPlanes(),D=D||v.isInFrustum(w._frustumPlanes)}),D}return v.isInFrustum(this._frustumPlanes)},h.prototype.isCompletelyInFrustum=function(v){return this._updateFrustumPlanes(),v.isCompletelyInFrustum(this._frustumPlanes)},h.prototype.getForwardRay=function(v,E,D){throw T.a.WarnImport("Ray")},h.prototype.getForwardRayToRef=function(v,E,D,w){throw T.a.WarnImport("Ray")},h.prototype.dispose=function(v,E){for(E===void 0&&(E=!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,v,E)},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(v,E){if(this.cameraRigMode!==v){for(;this._rigCameras.length>0;){var D=this._rigCameras.pop();D&&D.dispose()}if(this.cameraRigMode=v,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=E.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,E);break;case h.RIG_MODE_WEBVR:h._setWebVRRigMode(this,E)}this._cascadePostProcessesToRigCams(),this.update()}},h._setStereoscopicRigMode=function(v){throw"Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode"},h._setStereoscopicAnaglyphRigMode=function(v){throw"Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode"},h._setVRRigMode=function(v,E){throw"Import Cameras/RigModes/vrRigMode before using VR rig mode"},h._setWebVRRigMode=function(v,E){throw"Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode"},h.prototype._getVRProjectionMatrix=function(){return C.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 C.a.Identity()},h.prototype._getWebVRViewMatrix=function(){return C.a.Identity()},h.prototype.setCameraRigParameter=function(v,E){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[v]=E,v==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=u.b.ToRadians(E/.0637))},h.prototype.createRigCamera=function(v,E){return null},h.prototype._updateRigCameras=function(){for(var v=0;v=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,W,q):be.renderbufferStorage(be.RENDERBUFFER,ge,W,q),be.framebufferRenderbuffer(be.FRAMEBUFFER,_e,be.RENDERBUFFER,Pe),be.bindRenderbuffer(be.RENDERBUFFER,null),Pe},this._boundUniforms={};var te=null;if(I){if(X=X||{},E.a.SetMatrixPrecision(!!X.useHighPrecisionMatrix),I.getContext){if(te=I,this._renderingCanvas=te,V!=null&&(X.antialias=V),X.deterministicLockstep===void 0&&(X.deterministicLockstep=!1),X.lockstepMaxSteps===void 0&&(X.lockstepMaxSteps=4),X.timeStep===void 0&&(X.timeStep=1/60),X.preserveDrawingBuffer===void 0&&(X.preserveDrawingBuffer=!1),X.audioEngine===void 0&&(X.audioEngine=!0),X.stencil===void 0&&(X.stencil=!0),X.premultipliedAlpha===!1&&(this.premultipliedAlpha=!1),X.xrCompatible===void 0&&(X.xrCompatible=!0),this._doNotHandleContextLost=!!X.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=X,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 X=0;X<16;X++)this._gl["COLOR_ATTACHMENT"+X+"_WEBGL"]=V["COLOR_ATTACHMENT"+X+"_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,X,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),X&&(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,X,j){I===this._viewportCached.x&&V===this._viewportCached.y&&X===this._viewportCached.z&&j===this._viewportCached.w||(this._viewportCached.x=I,this._viewportCached.y=V,this._viewportCached.z=X,this._viewportCached.w=j,this._gl.viewport(I,V,X,j))},N.prototype.setViewport=function(I,V,X){var j=V||this.getRenderWidth(),ne=X||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,X,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,X,j):(X||(X=I.width,te&&(X/=Math.pow(2,te))),j||(j=I.height,te&&(j/=Math.pow(2,te))),this._viewport(0,0,X,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,X){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,X);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)),X&&(I._MSAAFramebuffer&&this._bindUnboundFramebuffer(I._framebuffer),X()),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 X=this._gl.createBuffer();if(!X)throw new Error("Unable to create vertex buffer");var j=new l.a(X);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 X=this._gl.createBuffer(),j=new l.a(X);if(!X)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,X){var j=I.program,ne=this._gl.getUniformBlockIndex(j,V);this._gl.uniformBlockBinding(j,ne,X)},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,X,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!==X&&(pe.size=X,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=X,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,X,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 X=V.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var j=0;j=0){var te=I[X[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,X){var j=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(j),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(I,X),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,X,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,X[pe],this._gl.FLOAT,!1,j,de)),de+=4*X[pe]}}this._bindIndexBufferWithCache(V)},N.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},N.prototype.bindBuffers=function(I,V,X){this._cachedVertexBuffers===I&&this._cachedEffectForVertexBuffers===X||(this._cachedVertexBuffers=I,this._cachedEffectForVertexBuffers=X,this._bindVertexBuffersAttributes(I,X)),this._bindIndexBufferWithCache(V)},N.prototype.unbindInstanceAttributes=function(){for(var I,V=0,X=this._currentInstanceLocations.length;V1?`#version 300 es -#define WEBGL2 -`:"",pe=this._compileShader(V,"vertex",j,de),ae=this._compileShader(X,"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,X,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,X),j.linkProgram(te),I.context=j,I.vertexShader=V,I.fragmentShader=X,I.isParallelCompiled||this._finalizePipelineContext(I),te},N.prototype._finalizePipelineContext=function(I){var V=I.context,X=I.vertexShader,j=I.fragmentShader,ne=I.program;if(!V.getProgramParameter(ne,V.LINK_STATUS)){var te,de;if(!this._gl.getShaderParameter(X,this._gl.COMPILE_STATUS)&&(te=this._gl.getShaderInfoLog(X)))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(X),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,X,j,ne,te,de){var pe=I;pe.program=j?this.createRawShaderProgram(pe,V,X,void 0,de):this.createShaderProgram(pe,V,X,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 X=I;if(X.isParallelCompiled){var j=X.onCompiled;X.onCompiled=j?function(){j(),V()}:V}else V()},N.prototype.getUniforms=function(I,V){for(var X=new Array,j=I,ne=0;ne-1?I.substring(H).toLowerCase():""),W=null;Z.indexOf("?")>-1&&(Z=Z.split("?")[0]);for(var q=0,he=N._TextureLoaders;qGe||ye.height>Ge||!G._supportsHardwareTextureRescaling)return G._prepareWorkingCanvas(),!(!G._workingCanvas||!G._workingContext)&&(G._workingCanvas.width=Be,G._workingCanvas.height=ke,G._workingContext.drawImage(ye,0,0,ye.width,ye.height,0,0,Be,ke),je.texImage2D(je.TEXTURE_2D,0,Qe,Qe,je.UNSIGNED_BYTE,G._workingCanvas),Y.width=Be,Y.height=ke,!1);var nt=new c.a(G,c.b.Temp);return G._bindTextureDirectly(je.TEXTURE_2D,nt,!0),je.texImage2D(je.TEXTURE_2D,0,Qe,Qe,je.UNSIGNED_BYTE,ye),G._rescaleTexture(nt,Y,j,Qe,function(){G._releaseTexture(nt),G._bindTextureDirectly(je.TEXTURE_2D,Y,!0),We()}),!0},ne)};!Q||re?pe&&(pe.decoding||pe.close)?Pe(pe):N._FileToolsLoadImage(I,Pe,_e,j?j.offlineProvider:null,$):typeof pe=="string"||pe instanceof ArrayBuffer||ArrayBuffer.isView(pe)||pe instanceof Blob?N._FileToolsLoadImage(pe,Pe,_e,j?j.offlineProvider:null,$):pe&&Pe(pe)}return Y},N._FileToolsLoadImage=function(I,V,X,j,ne){throw R.a.WarnImport("FileTools")},N.prototype._rescaleTexture=function(I,V,X,j,ne){},N.prototype.createRawTexture=function(I,V,X,j,ne,te,de,pe,ae){throw ae===void 0&&(ae=m.a.TEXTURETYPE_UNSIGNED_INT),R.a.WarnImport("Engine.RawTexture")},N.prototype.createRawCubeTexture=function(I,V,X,j,ne,te,de,pe){throw R.a.WarnImport("Engine.RawTexture")},N.prototype.createRawTexture3D=function(I,V,X,j,ne,te,de,pe,ae,ee){throw ee===void 0&&(ee=m.a.TEXTURETYPE_UNSIGNED_INT),R.a.WarnImport("Engine.RawTexture")},N.prototype.createRawTexture2DArray=function(I,V,X,j,ne,te,de,pe,ae,ee){throw ee===void 0&&(ee=m.a.TEXTURETYPE_UNSIGNED_INT),R.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,X){X===void 0&&(X=!1);var j=this._getTextureTarget(V),ne=this._getSamplingParameters(I,V.generateMipMaps||X);this._setTextureParameterInteger(j,this._gl.TEXTURE_MAG_FILTER,ne.mag,V),this._setTextureParameterInteger(j,this._gl.TEXTURE_MIN_FILTER,ne.min),X&&(V.generateMipMaps=!0,this._gl.generateMipmap(j)),this._bindTextureDirectly(j,null),V.samplingMode=I},N.prototype.updateTextureWrappingMode=function(I,V,X,j){X===void 0&&(X=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),X!==null&&(this._setTextureParameterInteger(ne,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(X),I),I._cachedWrapV=X),(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,X,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=X,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,X,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,X,j,0,ne)},N.prototype._uploadDataToTextureDirectly=function(I,V,X,j,ne,te){X===void 0&&(X=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+X);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,X,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,X,j,ne,te,K,ee,V)},N.prototype._uploadArrayBufferViewToTexture=function(I,V,X,j){X===void 0&&(X=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,X,j),this._bindTextureDirectly(te,null,!0)},N.prototype._prepareWebGLTextureContinuation=function(I,V,X,j,ne){var te=this._gl;if(te){var de=this._getSamplingParameters(ne,!X);te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MAG_FILTER,de.mag),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MIN_FILTER,de.min),X||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,X,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(X,K):X),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=X,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,X,j,ne){ne===void 0&&(ne=1);var te=this._gl;if(I&&V)return this._getDepthStencilBuffer(X,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(X,j,ne,de,de,te.DEPTH_ATTACHMENT)}return I?this._getDepthStencilBuffer(X,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 X=I.getSamplers(),j=0;j-1;return X&&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)):X&&(ne=!0,this._activateCurrentTexture()),te&&!X&&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 X=V?this._getTextureTarget(V):this._gl.TEXTURE_2D;this._bindTextureDirectly(X,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,X){I!==void 0&&(V&&(this._boundUniforms[I]=V),this._setTexture(I,X))},N.prototype._bindSamplerUniformToChannel=function(I,V){var X=this._boundUniforms[I];X&&X._currentState!==V&&(this._gl.uniform1i(X,V),X._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,X,j){if(X===void 0&&(X=!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,!X&&ne&&(ne._associatedChannel=I);var te=!0;this._boundTexturesCache[I]===ne&&(X||this._bindSamplerUniformToChannel(ne._associatedChannel,I),te=!1),this._activeChannel=I;var de=this._getTextureTarget(ne);if(te&&this._bindTextureDirectly(de,ne,X),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,X){if(I!==void 0&&V){this._textureUnits&&this._textureUnits.length===X.length||(this._textureUnits=new Int32Array(X.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 X=!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((X=(X=X&&te===V.FRAMEBUFFER_COMPLETE)&&V.getError()===V.NO_ERROR)&&(V.clear(V.COLOR_BUFFER_BIT),X=X&&V.getError()===V.NO_ERROR),X){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),X=X&&V.getError()===V.NO_ERROR}for(V.deleteTexture(j),V.deleteFramebuffer(ne),V.bindFramebuffer(V.FRAMEBUFFER,null);!X&&V.getError()!==V.NO_ERROR;);return X},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,X,j,ne,te){var de=this,pe=N._FileToolsLoadFile(I,V,X,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,X,j,ne,te){throw R.a.WarnImport("FileTools")},N.prototype.readPixels=function(I,V,X,j,ne){ne===void 0&&(ne=!0);var te=ne?4:3,de=ne?this._gl.RGBA:this._gl.RGB,pe=new Uint8Array(j*X*te);return this._gl.readPixels(I,V,X,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=v.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=v.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),X=N.FloorPOT(I);return V-I>I-X?X:V},N.GetExponentOfTwo=function(I,V,X){var j;switch(X===void 0&&(X=m.a.SCALEMODE_NEAREST),X){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(Ie,y,f){f.d(y,"b",function(){return U}),f.d(y,"a",function(){return C});var U,_=f(6),R=f(102),u=f(2),M=f(21);(function(P){P[P.Unknown=0]="Unknown",P[P.Url=1]="Url",P[P.Temp=2]="Temp",P[P.Raw=3]="Raw",P[P.Dynamic=4]="Dynamic",P[P.RenderTarget=5]="RenderTarget",P[P.MultiRenderTarget=6]="MultiRenderTarget",P[P.Cube=7]="Cube",P[P.CubeRaw=8]="CubeRaw",P[P.CubePrefiltered=9]="CubePrefiltered",P[P.Raw3D=10]="Raw3D",P[P.Raw2DArray=11]="Raw2DArray",P[P.Depth=12]="Depth",P[P.CubeRawRGBD=13]="CubeRawRGBD"})(U||(U={}));var C=function(){function P(m,c,T){T===void 0&&(T=!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=U.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,T||(this._webGLTexture=m._createTexture())}return P.prototype.getEngine=function(){return this._engine},Object.defineProperty(P.prototype,"source",{get:function(){return this._source},enumerable:!1,configurable:!0}),P.prototype.incrementReferences=function(){this._references++},P.prototype.updateSize=function(m,c,T){T===void 0&&(T=1),this.width=m,this.height=c,this.depth=T,this.baseWidth=m,this.baseHeight=c,this.baseDepth=T,this._size=m*c*T},P.prototype._rebuild=function(){var m,c,T=this;switch(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedAnisotropicFilteringLevel=null,this.source){case U.Temp:return;case U.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(T),T.isReady=!0},null,this._buffer,void 0,this.format));case U.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 U.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 U.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 U.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 U.RenderTarget:var A=new R.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 U.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 U.Cube:return void(c=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,function(){c._swapAndDie(T),T.isReady=!0},null,this.format,this._extension));case U.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 U.CubeRawRGBD:return c=this._engine.createRawCubeTexture(null,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),void P._UpdateRGBDAsync(c,this._bufferViewArrayArray,this._sphericalPolynomial,this._lodGenerationScale,this._lodGenerationOffset).then(function(){c._swapAndDie(T),T.isReady=!0});case U.CubePrefiltered:return void((c=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,function(h){h&&h._swapAndDie(T),T.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial)}},P.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,T=this._engine.getLoadedTexturesCache();(c=T.indexOf(this))!==-1&&T.splice(c,1),(c=T.indexOf(m))===-1&&T.push(m)},P.prototype.dispose=function(){this._webGLTexture&&(this._references--,this._references===0&&(this._engine._releaseTexture(this),this._webGLTexture=null))},P._UpdateRGBDAsync=function(m,c,T,A,S){throw M.a.WarnImport("environmentTextureTools")},P}()},function(Ie,y,f){f.d(y,"b",function(){return U}),f.d(y,"c",function(){return _}),f.d(y,"a",function(){return R});var U=1/2.2,_=2.2,R=.001},function(Ie,y,f){f.d(y,"a",function(){return P});var U=f(1),_=f(0),R=f(3),u=f(6),M=f(22),C=f(21),P=function(){function m(c,T){T===void 0&&(T=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=T||M.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}return m.AddNodeConstructor=function(c,T){this._NodeConstructors[c]=T},m.Construct=function(c,T,A,S){var g=this._NodeConstructors[c];return g?g(T,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 T=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),T||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,T=c.length-1;c[this._sceneRootNodesIndex]=c[T],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,T){var A=this;return T===void 0&&(T=!1),this._behaviors.indexOf(c)!==-1||(c.init(),this._scene.isLoading&&!T?this._scene.onDataLoadedObservable.addOnce(function(){c.attach(A)}):c.attach(this),this._behaviors.push(c)),this},m.prototype.removeBehavior=function(c){var T=this._behaviors.indexOf(c);return T===-1||(this._behaviors[T].detach(),this._behaviors.splice(T,1)),this},Object.defineProperty(m.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!1,configurable:!0}),m.prototype.getBehaviorByName=function(c){for(var T=0,A=this._behaviors;T -#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 -} -`;E.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 -`;E.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),E.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 -} -`;E.a.ShadersStore.defaultVertexShader=V;var X=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(U.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===X.a.ALPHA_PREMULTIPLIED||this.alphaMode===X.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=[P.b.PositionKind];Q.NORMAL&&k.push(P.b.NormalKind),Q.UV1&&k.push(P.b.UVKind),Q.UV2&&k.push(P.b.UV2Kind),Q.VERTEXCOLOR&&k.push(P.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"],W=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler"],q=["Material","Scene"];ne.a.AddUniforms(Z),ne.a.AddSamplers(W),m.a.AddUniforms(Z),m.a.AddSamplers(Z),c.a&&(c.a.PrepareUniforms(Z,Q),c.a.PrepareSamplers(W,Q)),g.a.PrepareUniformsAndSamplersList({uniformsNames:Z,uniformBuffersNames:q,samplers:W,defines:Q,maxSimultaneousLights:this._maxSimultaneousLights});var he={};this.customShaderNameResolve&&(H=this.customShaderNameResolve(H,Z,q,W,Q,k,he));var ge=Q.toString(),me=$.effect,_e=G.getEngine().createEffect(H,{attributes:k,uniformsNames:Z,uniformBuffersNames:q,samplers:W,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 C.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:C.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 v.a.DiffuseTextureEnabled},set:function(K){v.a.DiffuseTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"DetailTextureEnabled",{get:function(){return v.a.DetailTextureEnabled},set:function(K){v.a.DetailTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"AmbientTextureEnabled",{get:function(){return v.a.AmbientTextureEnabled},set:function(K){v.a.AmbientTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"OpacityTextureEnabled",{get:function(){return v.a.OpacityTextureEnabled},set:function(K){v.a.OpacityTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"ReflectionTextureEnabled",{get:function(){return v.a.ReflectionTextureEnabled},set:function(K){v.a.ReflectionTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"EmissiveTextureEnabled",{get:function(){return v.a.EmissiveTextureEnabled},set:function(K){v.a.EmissiveTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"SpecularTextureEnabled",{get:function(){return v.a.SpecularTextureEnabled},set:function(K){v.a.SpecularTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"BumpTextureEnabled",{get:function(){return v.a.BumpTextureEnabled},set:function(K){v.a.BumpTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"LightmapTextureEnabled",{get:function(){return v.a.LightmapTextureEnabled},set:function(K){v.a.LightmapTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"RefractionTextureEnabled",{get:function(){return v.a.RefractionTextureEnabled},set:function(K){v.a.RefractionTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"ColorGradingTextureEnabled",{get:function(){return v.a.ColorGradingTextureEnabled},set:function(K){v.a.ColorGradingTextureEnabled=K},enumerable:!1,configurable:!0}),Object.defineProperty(ee,"FresnelEnabled",{get:function(){return v.a.FresnelEnabled},set:function(K){v.a.FresnelEnabled=K},enumerable:!1,configurable:!0}),Object(U.c)([Object(_.m)("diffuseTexture")],ee.prototype,"_diffuseTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"diffuseTexture",void 0),Object(U.c)([Object(_.m)("ambientTexture")],ee.prototype,"_ambientTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"ambientTexture",void 0),Object(U.c)([Object(_.m)("opacityTexture")],ee.prototype,"_opacityTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"opacityTexture",void 0),Object(U.c)([Object(_.m)("reflectionTexture")],ee.prototype,"_reflectionTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"reflectionTexture",void 0),Object(U.c)([Object(_.m)("emissiveTexture")],ee.prototype,"_emissiveTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"emissiveTexture",void 0),Object(U.c)([Object(_.m)("specularTexture")],ee.prototype,"_specularTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"specularTexture",void 0),Object(U.c)([Object(_.m)("bumpTexture")],ee.prototype,"_bumpTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"bumpTexture",void 0),Object(U.c)([Object(_.m)("lightmapTexture")],ee.prototype,"_lightmapTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"lightmapTexture",void 0),Object(U.c)([Object(_.m)("refractionTexture")],ee.prototype,"_refractionTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"refractionTexture",void 0),Object(U.c)([Object(_.e)("ambient")],ee.prototype,"ambientColor",void 0),Object(U.c)([Object(_.e)("diffuse")],ee.prototype,"diffuseColor",void 0),Object(U.c)([Object(_.e)("specular")],ee.prototype,"specularColor",void 0),Object(U.c)([Object(_.e)("emissive")],ee.prototype,"emissiveColor",void 0),Object(U.c)([Object(_.c)()],ee.prototype,"specularPower",void 0),Object(U.c)([Object(_.c)("useAlphaFromDiffuseTexture")],ee.prototype,"_useAlphaFromDiffuseTexture",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],ee.prototype,"useAlphaFromDiffuseTexture",void 0),Object(U.c)([Object(_.c)("useEmissiveAsIllumination")],ee.prototype,"_useEmissiveAsIllumination",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useEmissiveAsIllumination",void 0),Object(U.c)([Object(_.c)("linkEmissiveWithDiffuse")],ee.prototype,"_linkEmissiveWithDiffuse",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"linkEmissiveWithDiffuse",void 0),Object(U.c)([Object(_.c)("useSpecularOverAlpha")],ee.prototype,"_useSpecularOverAlpha",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useSpecularOverAlpha",void 0),Object(U.c)([Object(_.c)("useReflectionOverAlpha")],ee.prototype,"_useReflectionOverAlpha",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useReflectionOverAlpha",void 0),Object(U.c)([Object(_.c)("disableLighting")],ee.prototype,"_disableLighting",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsLightsDirty")],ee.prototype,"disableLighting",void 0),Object(U.c)([Object(_.c)("useObjectSpaceNormalMap")],ee.prototype,"_useObjectSpaceNormalMap",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useObjectSpaceNormalMap",void 0),Object(U.c)([Object(_.c)("useParallax")],ee.prototype,"_useParallax",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useParallax",void 0),Object(U.c)([Object(_.c)("useParallaxOcclusion")],ee.prototype,"_useParallaxOcclusion",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useParallaxOcclusion",void 0),Object(U.c)([Object(_.c)()],ee.prototype,"parallaxScaleBias",void 0),Object(U.c)([Object(_.c)("roughness")],ee.prototype,"_roughness",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"roughness",void 0),Object(U.c)([Object(_.c)()],ee.prototype,"indexOfRefraction",void 0),Object(U.c)([Object(_.c)()],ee.prototype,"invertRefractionY",void 0),Object(U.c)([Object(_.c)()],ee.prototype,"alphaCutOff",void 0),Object(U.c)([Object(_.c)("useLightmapAsShadowmap")],ee.prototype,"_useLightmapAsShadowmap",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useLightmapAsShadowmap",void 0),Object(U.c)([Object(_.h)("diffuseFresnelParameters")],ee.prototype,"_diffuseFresnelParameters",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"diffuseFresnelParameters",void 0),Object(U.c)([Object(_.h)("opacityFresnelParameters")],ee.prototype,"_opacityFresnelParameters",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsFresnelAndMiscDirty")],ee.prototype,"opacityFresnelParameters",void 0),Object(U.c)([Object(_.h)("reflectionFresnelParameters")],ee.prototype,"_reflectionFresnelParameters",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"reflectionFresnelParameters",void 0),Object(U.c)([Object(_.h)("refractionFresnelParameters")],ee.prototype,"_refractionFresnelParameters",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"refractionFresnelParameters",void 0),Object(U.c)([Object(_.h)("emissiveFresnelParameters")],ee.prototype,"_emissiveFresnelParameters",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"emissiveFresnelParameters",void 0),Object(U.c)([Object(_.c)("useReflectionFresnelFromSpecular")],ee.prototype,"_useReflectionFresnelFromSpecular",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsFresnelDirty")],ee.prototype,"useReflectionFresnelFromSpecular",void 0),Object(U.c)([Object(_.c)("useGlossinessFromSpecularMapAlpha")],ee.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"useGlossinessFromSpecularMapAlpha",void 0),Object(U.c)([Object(_.c)("maxSimultaneousLights")],ee.prototype,"_maxSimultaneousLights",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsLightsDirty")],ee.prototype,"maxSimultaneousLights",void 0),Object(U.c)([Object(_.c)("invertNormalMapX")],ee.prototype,"_invertNormalMapX",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"invertNormalMapX",void 0),Object(U.c)([Object(_.c)("invertNormalMapY")],ee.prototype,"_invertNormalMapY",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"invertNormalMapY",void 0),Object(U.c)([Object(_.c)("twoSidedLighting")],ee.prototype,"_twoSidedLighting",void 0),Object(U.c)([Object(_.b)("_markAllSubMeshesAsTexturesDirty")],ee.prototype,"twoSidedLighting",void 0),Object(U.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(Ie,y,f){f.d(y,"a",function(){return I});var U=f(1),_=f(12),R=f(6),u=f(0),M=f(13),C=f(4),P=f(16),m=f(46),c=f(54),T=f(43),A=f(2),S=f(147),g=f(21),l=f(101),h=f(9),v=f(28),E=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 X(j,ne){ne===void 0&&(ne=null);var te=V.call(this,j,ne,!1)||this;return te._internalAbstractMeshDataInfo=new N,te.cullingStrategy=X.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,te.onCollideObservable=new R.c,te.onCollisionPositionChangeObservable=new R.c,te.onMaterialChangedObservable=new R.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 R.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(U.d)(X,V),Object.defineProperty(X,"BILLBOARDMODE_NONE",{get:function(){return m.a.BILLBOARDMODE_NONE},enumerable:!1,configurable:!0}),Object.defineProperty(X,"BILLBOARDMODE_X",{get:function(){return m.a.BILLBOARDMODE_X},enumerable:!1,configurable:!0}),Object.defineProperty(X,"BILLBOARDMODE_Y",{get:function(){return m.a.BILLBOARDMODE_Y},enumerable:!1,configurable:!0}),Object.defineProperty(X,"BILLBOARDMODE_Z",{get:function(){return m.a.BILLBOARDMODE_Z},enumerable:!1,configurable:!0}),Object.defineProperty(X,"BILLBOARDMODE_ALL",{get:function(){return m.a.BILLBOARDMODE_ALL},enumerable:!1,configurable:!0}),Object.defineProperty(X,"BILLBOARDMODE_USE_POSITION",{get:function(){return m.a.BILLBOARDMODE_USE_POSITION},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"facetNb",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetNb},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"partitioningSubdivisions",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions},set:function(j){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"partitioningBBoxRatio",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio},set:function(j){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"mustDepthSortFacets",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort},set:function(j){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"facetDepthSortFrom",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom},set:function(j){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"isFacetDataEnabled",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled},enumerable:!1,configurable:!0}),X.prototype._updateNonUniformScalingState=function(j){return!!V.prototype._updateNonUniformScalingState.call(this,j)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(X.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(X.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(X.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(X.prototype,"renderingGroupId",{get:function(){return this._renderingGroupId},set:function(j){this._renderingGroupId=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.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(X.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(X.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(X.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(X.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(X.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(X.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(X.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(X.prototype,"collisionMask",{get:function(){return this._meshCollisionData._collisionMask},set:function(j){this._meshCollisionData._collisionMask=isNaN(j)?-1:j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"collisionResponse",{get:function(){return this._meshCollisionData._collisionResponse},set:function(j){this._meshCollisionData._collisionResponse=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"collisionGroup",{get:function(){return this._meshCollisionData._collisionGroup},set:function(j){this._meshCollisionData._collisionGroup=isNaN(j)?-1:j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"surroundingMeshes",{get:function(){return this._meshCollisionData._surroundingMeshes},set:function(j){this._meshCollisionData._surroundingMeshes=j},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"lightSources",{get:function(){return this._lightSources},enumerable:!1,configurable:!0}),Object.defineProperty(X.prototype,"_positions",{get:function(){return null},enumerable:!1,configurable:!0}),Object.defineProperty(X.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}),X.prototype.getClassName=function(){return"AbstractMesh"},X.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},X.prototype._getEffectiveParent=function(){return this._masterMesh&&this.billboardMode!==m.a.BILLBOARDMODE_NONE?this._masterMesh:V.prototype._getEffectiveParent.call(this)},X.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},X.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(C.b.MatricesIndicesExtraKind):null,ee=pe?this.getVerticesData(C.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},X.prototype._updateBoundingInfo=function(){var j=this._effectiveMesh;return this._boundingInfo?this._boundingInfo.update(j.worldMatrixFromCache):this._boundingInfo=new T.a(this.absolutePosition,this.absolutePosition,j.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(j.worldMatrixFromCache),this},X.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},X.prototype._afterComputeWorldMatrix=function(){this.doNotSyncBoundingInfo||this._updateBoundingInfo()},Object.defineProperty(X.prototype,"_effectiveMesh",{get:function(){return this.skeleton&&this.skeleton.overrideMesh||this},enumerable:!1,configurable:!0}),X.prototype.isInFrustum=function(j){return this._boundingInfo!==null&&this._boundingInfo.isInFrustum(j,this.cullingStrategy)},X.prototype.isCompletelyInFrustum=function(j){return this._boundingInfo!==null&&this._boundingInfo.isCompletelyInFrustum(j)},X.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},X.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},X.prototype._generatePointsArray=function(){return!1},X.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;$v.a?pe.maximum.x-pe.minimum.x:v.a,j.bbSize.y=pe.maximum.y-pe.minimum.y>v.a?pe.maximum.y-pe.minimum.y:v.a,j.bbSize.z=pe.maximum.z-pe.minimum.z>v.a?pe.maximum.z-pe.minimum.z:v.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,P.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]},X.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},X.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 W,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=R.b.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new R.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&&U.a.Warn("You must affect impostors to children before affecting impostor to parent.")):U.a.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):U.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(T){this.setMass(T)},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"friction",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0},set:function(T){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,T)},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"restitution",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0},set:function(T){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,T)},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"pressure",{get:function(){if(!this._physicsEngine)return 0;var T=this._physicsEngine.getPhysicsPlugin();return T.setBodyPressure?T.getBodyPressure(this):0},set:function(T){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyPressure&&A.setBodyPressure(this,T)}},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"stiffness",{get:function(){if(!this._physicsEngine)return 0;var T=this._physicsEngine.getPhysicsPlugin();return T.getBodyStiffness?T.getBodyStiffness(this):0},set:function(T){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyStiffness&&A.setBodyStiffness(this,T)}},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"velocityIterations",{get:function(){if(!this._physicsEngine)return 0;var T=this._physicsEngine.getPhysicsPlugin();return T.getBodyVelocityIterations?T.getBodyVelocityIterations(this):0},set:function(T){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyVelocityIterations&&A.setBodyVelocityIterations(this,T)}},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"positionIterations",{get:function(){if(!this._physicsEngine)return 0;var T=this._physicsEngine.getPhysicsPlugin();return T.getBodyPositionIterations?T.getBodyPositionIterations(this):0},set:function(T){if(this._physicsEngine){var A=this._physicsEngine.getPhysicsPlugin();A.setBodyPositionIterations&&A.setBodyPositionIterations(this,T)}},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(T){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=T,this.resetUpdateFlags()},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"parent",{get:function(){return!this._options.ignoreParent&&this._parent?this._parent:null},set:function(T){this._parent=T},enumerable:!1,configurable:!0}),c.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},c.prototype.getObjectExtendSize=function(){if(this.object.getBoundingInfo){var T=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=T,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(T){return this._options[T]},c.prototype.setParam=function(T,A){this._options[T]=A,this._bodyUpdateRequired=!0},c.prototype.setMass=function(T){this.getParam("mass")!==T&&this.setParam("mass",T),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,T)},c.prototype.getLinearVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):R.e.Zero()},c.prototype.setLinearVelocity=function(T){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,T)},c.prototype.getAngularVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):R.e.Zero()},c.prototype.setAngularVelocity=function(T){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,T)},c.prototype.executeNativeFunction=function(T){this._physicsEngine&&T(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},c.prototype.registerBeforePhysicsStep=function(T){this._onBeforePhysicsStepCallbacks.push(T)},c.prototype.unregisterBeforePhysicsStep=function(T){var A=this._onBeforePhysicsStepCallbacks.indexOf(T);A>-1?this._onBeforePhysicsStepCallbacks.splice(A,1):U.a.Warn("Function to remove was not found")},c.prototype.registerAfterPhysicsStep=function(T){this._onAfterPhysicsStepCallbacks.push(T)},c.prototype.unregisterAfterPhysicsStep=function(T){var A=this._onAfterPhysicsStepCallbacks.indexOf(T);A>-1?this._onAfterPhysicsStepCallbacks.splice(A,1):U.a.Warn("Function to remove was not found")},c.prototype.registerOnPhysicsCollide=function(T,A){var S=T instanceof Array?T:[T];this._onPhysicsCollideCallbacks.push({callback:A,otherImpostors:S})},c.prototype.unregisterOnPhysicsCollide=function(T,A){var S=T instanceof Array?T:[T],g=-1;this._onPhysicsCollideCallbacks.some(function(l,h){if(l.callback===A&&l.otherImpostors.length===S.length){var v=l.otherImpostors.every(function(E){return S.indexOf(E)>-1});return v&&(g=h),v}return!1})?this._onPhysicsCollideCallbacks.splice(g,1):U.a.Warn("Function to remove was not found")},c.prototype.getParentsRotation=function(){var T=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);T;)T.rotationQuaternion?this._tmpQuat2.copyFrom(T.rotationQuaternion):R.b.RotationYawPitchRollToRef(T.rotation.y,T.rotation.x,T.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),T=T.parent;return this._tmpQuat},c.prototype.applyForce=function(T,A){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,T,A),this},c.prototype.applyImpulse=function(T,A){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,T,A),this},c.prototype.createJoint=function(T,A,S){var g=new C.e(A,S);return this.addJoint(T,g),this},c.prototype.addJoint=function(T,A){return this._joints.push({otherImpostor:T,joint:A}),this._physicsEngine&&this._physicsEngine.addJoint(this,T,A),this},c.prototype.addAnchor=function(T,A,S,g,l){if(!this._physicsEngine)return this;var h=this._physicsEngine.getPhysicsPlugin();return h.appendAnchor?(this._physicsEngine&&h.appendAnchor(this,T,A,S,g,l),this):this},c.prototype.addHook=function(T,A,S,g){if(!this._physicsEngine)return this;var l=this._physicsEngine.getPhysicsPlugin();return l.appendAnchor?(this._physicsEngine&&l.appendHook(this,T,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(T){return T?new c(T,this.type,this._options,this._scene):null},c.prototype.dispose=function(){var T=this;this._physicsEngine&&(this._joints.forEach(function(A){T._physicsEngine&&T._physicsEngine.removeJoint(T,A.otherImpostor,A.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},c.prototype.setDeltaPosition=function(T){this._deltaPosition.copyFrom(T)},c.prototype.setDeltaRotation=function(T){this._deltaRotation||(this._deltaRotation=new R.b),this._deltaRotation.copyFrom(T),this._deltaRotationConjugated=this._deltaRotation.conjugate()},c.prototype.getBoxSizeToRef=function(T){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,T),this},c.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},c.prototype.syncBoneWithImpostor=function(T,A,S,g,l){var h=c._tmpVecs[0],v=this.object;if(v.rotationQuaternion)if(l){var E=c._tmpQuat;v.rotationQuaternion.multiplyToRef(l,E),T.setRotationQuaternion(E,P.c.WORLD,A)}else T.setRotationQuaternion(v.rotationQuaternion,P.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,T.getDirectionToRef(h,A,h),g==null&&(g=S.length()),h.x*=g,h.y*=g,h.z*=g),T.getParent()?(h.addInPlace(v.getAbsolutePosition()),T.setAbsolutePosition(h,A)):(A.setAbsolutePosition(v.getAbsolutePosition()),A.position.x-=h.x,A.position.y-=h.y,A.position.z-=h.z)},c.prototype.syncImpostorWithBone=function(T,A,S,g,l,h){var v=this.object;if(v.rotationQuaternion)if(l){var E=c._tmpQuat;T.getRotationQuaternionToRef(P.c.WORLD,A,E),E.multiplyToRef(l,v.rotationQuaternion)}else T.getRotationQuaternionToRef(P.c.WORLD,A,v.rotationQuaternion);var D=c._tmpVecs[0],w=c._tmpVecs[1];h||((h=c._tmpVecs[2]).x=0,h.y=1,h.z=0),T.getDirectionToRef(h,A,w),T.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),v.setAbsolutePosition(D)},c.DEFAULT_OBJECT_SIZE=new R.e(1,1,1),c.IDENTITY_QUATERNION=R.b.Identity(),c._tmpVecs=_.a.BuildArray(3,R.e.Zero),c._tmpQuat=R.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(Ie,y,f){f.d(y,"a",function(){return _}),f.d(y,"b",function(){return R});var U=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 C=0;Cthis.data.length&&(this.data.length=2*(this.length+M.length));for(var C=0;C=this.length?-1:C},u.prototype.contains=function(M){return this.indexOf(M)!==-1},u._GlobalId=0,u}(),R=function(u){function M(){var C=u!==null&&u.apply(this,arguments)||this;return C._duplicateId=0,C}return Object(U.d)(M,u),M.prototype.push=function(C){u.prototype.push.call(this,C),C.__smartArrayFlags||(C.__smartArrayFlags={}),C.__smartArrayFlags[this._id]=this._duplicateId},M.prototype.pushNoDuplicate=function(C){return(!C.__smartArrayFlags||C.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(C),!0)},M.prototype.reset=function(){u.prototype.reset.call(this),this._duplicateId++},M.prototype.concatWithNoDuplicate=function(C){if(C.length!==0){this.length+C.length>this.data.length&&(this.data.length=2*(this.length+C.length));for(var P=0;P>2,m=(3&u)<<4|(M=g>4,c=(15&M)<<2|(C=g>6,T=63&C,isNaN(M)?c=T=64:isNaN(C)&&(T=64),S+=A.charAt(P)+A.charAt(m)+A.charAt(c)+A.charAt(T);return S},_.PadNumber=function(R,u){for(var M=String(R);M.length0)):!S._pointerCaptures[D.pointerId]&&v.distance>E.distance&&(S.mainSceneTrackerPredicate&&S.mainSceneTrackerPredicate(E.pickedMesh)?(S._notifyObservers(g,E,D),g.skipOnPointerObservable=!0):S._lastPointerEvents[D.pointerId]&&(S.onPointerOutObservable.notifyObservers(D.pointerId),delete S._lastPointerEvents[D.pointerId])),g.type===R.a.POINTERUP&&S._pointerCaptures[D.pointerId]&&(S._pointerCaptures[D.pointerId]=!1))}}}}),this._originalPointerObserver&&T.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(T){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,T&&A&&A.isRigCamera?A.rigParent:A},c.prototype.setRenderCamera=function(T){this._renderCamera=T},c.prototype._getSharedGizmoLight=function(){return this._sharedGizmoLight||(this._sharedGizmoLight=new M.a("shared gizmo light",new C.e(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=P.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(T,A,S){T.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new R.b(T.type,T.event,A),T.type),this._lastPointerEvents[S.pointerId]=!0)},c.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var T=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=T,A.leftCamera&&(A.leftCamera._scene=T),A.rightCamera&&(A.rightCamera._scene=T)}},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(Ie,y,f){f.d(y,"a",function(){return _});var U=f(139),_=function(){function R(){}return R.EnableFor=function(u){u._tags=u._tags||{},u.hasTags=function(){return R.HasTags(u)},u.addTags=function(M){return R.AddTagsTo(u,M)},u.removeTags=function(M){return R.RemoveTagsFrom(u,M)},u.matchesTagsQuery=function(M){return R.MatchesQuery(u,M)}},R.DisableFor=function(u){delete u._tags,delete u.hasTags,delete u.addTags,delete u.removeTags,delete u.matchesTagsQuery},R.HasTags=function(u){if(!u._tags)return!1;var M=u._tags;for(var C in M)if(M.hasOwnProperty(C))return!0;return!1},R.GetTags=function(u,M){if(M===void 0&&(M=!0),!u._tags)return null;if(M){var C=[];for(var P in u._tags)u._tags.hasOwnProperty(P)&&u._tags[P]===!0&&C.push(P);return C.join(" ")}return u._tags},R.AddTagsTo=function(u,M){M&&typeof M=="string"&&M.split(" ").forEach(function(C,P,m){R._AddTagTo(u,C)})},R._AddTagTo=function(u,M){(M=M.trim())!==""&&M!=="true"&&M!=="false"&&(M.match(/[\s]/)||M.match(/^([!]|([|]|[&]){2})/)||(R.EnableFor(u),u._tags[M]=!0))},R.RemoveTagsFrom=function(u,M){if(R.HasTags(u)){var C=M.split(" ");for(var P in C)R._RemoveTagFrom(u,C[P])}},R._RemoveTagFrom=function(u,M){delete u._tags[M]},R.MatchesQuery=function(u,M){return M===void 0||(M===""?R.HasTags(u):U.a.Eval(M,function(C){return R.HasTags(u)&&u._tags[C]}))},R}()},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(){}return _.IsWindowObjectExist=function(){return typeof window<"u"},_.IsNavigatorAvailable=function(){return typeof navigator<"u"},_.IsDocumentAvailable=function(){return typeof document<"u"},_.GetDOMTextContent=function(R){for(var u="",M=R.firstChild;M;)M.nodeType===3&&(u+=M.textContent),M=M.nextSibling;return u},_}()},function(Ie,y,f){f.d(y,"a",function(){return P});var U=f(44),_=f(0),R=f(54),u=f(114),M=f(20),C=f(24),P=function(){function m(c,T,A){A===void 0&&(A=Number.MAX_VALUE),this.origin=c,this.direction=T,this.length=A}return m.prototype.intersectsBoxMinMax=function(c,T,A){A===void 0&&(A=0);var S,g,l,h,v=m._TmpVector3[0].copyFromFloats(c.x-A,c.y-A,c.z-A),E=m._TmpVector3[1].copyFromFloats(T.x+A,T.y+A,T.z+A),D=0,w=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xE.x)return!1}else if(S=1/this.direction.x,g=(v.x-this.origin.x)*S,(l=(E.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.yE.y)return!1}else if(S=1/this.direction.y,g=(v.y-this.origin.y)*S,(l=(E.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.zE.z)return!1}else if(S=1/this.direction.z,g=(v.z-this.origin.z)*S,(l=(E.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,T){return T===void 0&&(T=0),this.intersectsBoxMinMax(c.minimum,c.maximum,T)},m.prototype.intersectsSphere=function(c,T){T===void 0&&(T=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+T,v=h*h;if(l<=v)return!0;var E=A*this.direction.x+S*this.direction.y+g*this.direction.z;return!(E<0)&&l-E*E<=v},m.prototype.intersectsTriangle=function(c,T,A){var S=m._TmpVector3[0],g=m._TmpVector3[1],l=m._TmpVector3[2],h=m._TmpVector3[3],v=m._TmpVector3[4];T.subtractToRef(c,S),A.subtractToRef(c,g),_.e.CrossToRef(this.direction,g,l);var E=_.e.Dot(S,l);if(E===0)return null;var D=1/E;this.origin.subtractToRef(c,h);var w=_.e.Dot(h,l)*D;if(w<0||w>1)return null;_.e.CrossToRef(h,S,v);var N=_.e.Dot(this.direction,v)*D;if(N<0||w+N>1)return null;var I=_.e.Dot(g,v)*D;return I>this.length?null:new u.a(1-w-N,w,I)},m.prototype.intersectsPlane=function(c){var T,A=_.e.Dot(c.normal,this.direction);if(Math.abs(A)<999999997475243e-21)return null;var S=_.e.Dot(c.normal,this.origin);return(T=(-c.d-S)/A)<0?T<-999999997475243e-21?null:0:T},m.prototype.intersectsAxis=function(c,T){switch(T===void 0&&(T=0),c){case"y":return(A=(this.origin.y-T)/this.direction.y)>0?null:new _.e(this.origin.x+this.direction.x*-A,T,this.origin.z+this.direction.z*-A);case"x":return(A=(this.origin.x-T)/this.direction.x)>0?null:new _.e(T,this.origin.y+this.direction.y*-A,this.origin.z+this.direction.z*-A);case"z":var A;return(A=(this.origin.z-T)/this.direction.z)>0?null:new _.e(this.origin.x+this.direction.x*-A,this.origin.y+this.direction.y*-A,T);default:return null}},m.prototype.intersectsMesh=function(c,T){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,T)},m.prototype.intersectsMeshes=function(c,T,A){A?A.length=0:A=[];for(var S=0;ST.distance?1:0},m.prototype.intersectionSegment=function(c,T,A){var S=this.origin,g=_.c.Vector3[0],l=_.c.Vector3[1],h=_.c.Vector3[2],v=_.c.Vector3[3];T.subtractToRef(c,g),this.direction.scaleToRef(m.rayl,h),S.addToRef(h,l),c.subtractToRef(S,v);var E,D,w,N,I=_.e.Dot(g,g),V=_.e.Dot(g,h),X=_.e.Dot(h,h),j=_.e.Dot(g,v),ne=_.e.Dot(h,v),te=I*X-V*V,de=te,pe=te;tede&&(D=de,N=ne+V,pe=X)),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)),E=Math.abs(D)0&&w<=this.length&&K.lengthSquared()=m.distance?null:E:null},M.a.prototype._internalPick=function(m,c,T,A,S){if(!R.a)return null;for(var g=null,l=0;l0&&(m.push(g-1),m.push(g)),g++}var D=new R.a;return D.indices=m,D.positions=c,A&&(D.colors=S),D},R.a.CreateDashedLines=function(P){var m,c,T=P.dashSize||3,A=P.gapSize||1,S=P.dashNb||200,g=P.points,l=new Array,h=new Array,v=U.e.Zero(),E=0,D=0,w=0,N=0,I=0;for(I=0;I0)if(typeof g[0]=="object")for(var h=0;hP.max||P.min>C.max)},T=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=R.a.MESHES_CULLINGSTRATEGY_STANDARD),!(g!==R.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION&&g!==R.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY||!this.boundingSphere.isCenterInFrustum(S))||!!this.boundingSphere.isInFrustum(S)&&(!(g!==R.a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&g!==R.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=U.a.BuildArray(2,_.e.Zero),A}()},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(){}return _.BuildArray=function(R,u){for(var M=[],C=0;C1)?1:M.arc||1,A=M.slice&&M.slice<=0?1:M.slice||1,S=M.sideOrientation===0?0:M.sideOrientation||R.a.DEFAULTSIDE,g=!!M.dedupTopBottomIndices,l=new U.e(P/2,m/2,c/2),h=2+C,v=2*h,E=[],D=[],w=[],N=[],I=0;I<=h;I++){for(var V=I/h,X=V*Math.PI*A,j=0;j<=v;j++){var ne=j/v,te=ne*Math.PI*2*T,de=U.a.RotationZ(-X),pe=U.a.RotationY(te),ae=U.e.TransformCoordinates(U.e.Up(),de),ee=U.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*(v+1);G+v+21&&(E.push(G),E.push(G+1),E.push(G+v+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)},T.CompareLightsPriority=function(A,S){return A.shadowEnabled!==S.shadowEnabled?(S.shadowEnabled?1:0)-(A.shadowEnabled?1:0):S.renderPriority-A.renderPriority},T.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},T.GetConstructorFromName=function(A,S,g){var l=M.a.Construct("Light_Type_"+A,S,g);return l||null},T.Parse=function(A,S){var g=T.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(),T.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&&v?2:0))*(h?l:1);for(S=0;S1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=u,this._lastSecAccumulated=0,this._lastSecValueCount=0)},R.Enabled=!0,R}()},function(Ie,y,f){f.d(y,"b",function(){return A}),f.d(y,"d",function(){return S}),f.d(y,"c",function(){return g}),f.d(y,"a",function(){return l});var U=f(1),_=f(49),R=f(38),u=f(6),M=f(83),C=f(140),P=function(h){function v(){return h!==null&&h.apply(this,arguments)||this}return Object(U.d)(v,h),v._setPrototypeOf=Object.setPrototypeOf||function(E,D){return E.__proto__=D,E},v}(Error),m=f(34),c=f(26),T=f(128),A=function(h){function v(E,D){var w=h.call(this,E)||this;return w.name="LoadFileError",P._setPrototypeOf(w,v.prototype),D instanceof _.a?w.request=D:w.file=D,w}return Object(U.d)(v,h),v}(P),S=function(h){function v(E,D){var w=h.call(this,E)||this;return w.request=D,w.name="RequestFileError",P._setPrototypeOf(w,v.prototype),w}return Object(U.d)(v,h),v}(P),g=function(h){function v(E,D){var w=h.call(this,E)||this;return w.file=D,w.name="ReadFileError",P._setPrototypeOf(w,v.prototype),w}return Object(U.d)(v,h),v}(P),l=function(){function h(){}return h._CleanUrl=function(v){return v=v.replace(/#/gm,"%23")},h.SetCorsBehavior=function(v,E){if((!v||v.indexOf("data:")!==0)&&h.CorsBehavior)if(typeof h.CorsBehavior=="string"||this.CorsBehavior instanceof String)E.crossOrigin=h.CorsBehavior;else{var D=h.CorsBehavior(v);D&&(E.crossOrigin=D)}},h.LoadImage=function(v,E,D,w,N){var I;N===void 0&&(N="");var V=!1;if(v instanceof ArrayBuffer||ArrayBuffer.isView(v)?typeof Blob<"u"?(I=URL.createObjectURL(new Blob([v],{type:N})),V=!0):I="data:"+N+";base64,"+m.a.EncodeArrayBufferToBase64(v):v instanceof Blob?(I=URL.createObjectURL(v),V=!0):(I=h._CleanUrl(v),I=h.PreprocessUrl(v)),typeof Image>"u")return h.LoadFile(I,function(ae){createImageBitmap(new Blob([ae],{type:N})).then(function(ee){E(ee),V&&URL.revokeObjectURL(I)}).catch(function(ee){D&&D("Error while trying to load image: "+v,ee)})},void 0,w||void 0,!0,function(ae,ee){D&&D("Error while trying to load image: "+v,ee)}),null;var X=new Image;h.SetCorsBehavior(I,X);var j=function(){X.removeEventListener("load",j),X.removeEventListener("error",ne),E(X),V&&X.src&&URL.revokeObjectURL(X.src)},ne=function(ae){if(X.removeEventListener("load",j),X.removeEventListener("error",ne),D){var ee=v.toString();D("Error while trying to load image: "+(ee.length<32?ee:ee.slice(0,32)+"..."),ae)}V&&X.src&&URL.revokeObjectURL(X.src)};X.addEventListener("load",j),X.addEventListener("error",ne);var te=function(){X.src=I};if(I.substr(0,5)!=="data:"&&w&&w.enableTexturesOffline)w.open(function(){w&&w.loadImage(I,X)},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])}X.src=pe,V=!0}catch{X.src=""}return X}}te()}return X},h.ReadFile=function(v,E,D,w,N){var I=new FileReader,V={onCompleteObservable:new u.c,abort:function(){return I.abort()}};return I.onloadend=function(X){return V.onCompleteObservable.notifyObservers(V)},N&&(I.onerror=function(X){N(new g("Unable to read "+v.name,v))}),I.onload=function(X){E(X.target.result)},D&&(I.onprogress=D),w?I.readAsArrayBuffer(v):I.readAsText(v),V},h.LoadFile=function(v,E,D,w,N,I){if(v.indexOf("file:")!==-1){var V=decodeURIComponent(v.substring(5).toLowerCase());V.indexOf("./")===0&&(V=V.substring(2));var X=M.a.FilesToLoad[V];if(X)return h.ReadFile(X,E,D,N,I?function(j){return I(void 0,new A(j.message,j.file))}:void 0)}return h.RequestFile(v,function(j,ne){E(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(v,E,D,w,N,I,V){v=h._CleanUrl(v),v=h.PreprocessUrl(v);var X=h.BaseUrl+v,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",X),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&&(!R.a.IsWindowObjectExist()||h.IsFileURL()))return void E(N?pe.response:pe.responseText,pe);var G=h.DefaultRetryStrategy;if(G){var Q=G(X,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 "+X,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+v,function(pe){j||E(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=C.a.ExponentialBackoff(),h.BaseUrl="",h.CorsBehavior="anonymous",h.PreprocessUrl=function(v){return v},h}();c.a._FileToolsLoadImage=l.LoadImage.bind(l),c.a._FileToolsLoadFile=l.LoadFile.bind(l),T.a._FileToolsLoadFile=l.LoadFile.bind(l)},function(Ie,y,f){f.d(y,"a",function(){return _});var U=f(38),_=function(){function R(){}return Object.defineProperty(R,"Now",{get:function(){return U.a.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!1,configurable:!0}),R}()},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(R,u,M,C){this.x=R,this.y=u,this.width=M,this.height=C}return _.prototype.toGlobal=function(R,u){return new _(this.x*R,this.y*u,this.width*R,this.height*u)},_.prototype.toGlobalToRef=function(R,u,M){return M.x=this.x*R,M.y=this.y*u,M.width=this.width*R,M.height=this.height*u,this},_.prototype.clone=function(){return new _(this.x,this.y,this.width,this.height)},_}()},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){f.d(y,"a",function(){return _});var U=f(0),_=function(){function R(){}return R._RemoveAndStorePivotPoint=function(u){u&&R._PivotCached===0&&(u.getPivotPointToRef(R._OldPivotPoint),R._PivotPostMultiplyPivotMatrix=u._postMultiplyPivotMatrix,R._OldPivotPoint.equalsToFloats(0,0,0)||(u.setPivotMatrix(U.a.IdentityReadOnly),R._OldPivotPoint.subtractToRef(u.getPivotPoint(),R._PivotTranslation),R._PivotTmpVector.copyFromFloats(1,1,1),R._PivotTmpVector.subtractInPlace(u.scaling),R._PivotTmpVector.multiplyInPlace(R._PivotTranslation),u.position.addInPlace(R._PivotTmpVector))),R._PivotCached++},R._RestorePivotPoint=function(u){u&&!R._OldPivotPoint.equalsToFloats(0,0,0)&&R._PivotCached===1&&(u.setPivotPoint(R._OldPivotPoint),u._postMultiplyPivotMatrix=R._PivotPostMultiplyPivotMatrix,R._PivotTmpVector.copyFromFloats(1,1,1),R._PivotTmpVector.subtractInPlace(u.scaling),R._PivotTmpVector.multiplyInPlace(R._PivotTranslation),u.position.subtractInPlace(R._PivotTmpVector)),this._PivotCached--},R._PivotCached=0,R._OldPivotPoint=new U.e,R._PivotTranslation=new U.e,R._PivotTmpVector=new U.e,R._PivotPostMultiplyPivotMatrix=!1,R}()},function(Ie,y,f){f.d(y,"a",function(){return C});var U=f(4),_=f(114),R=f(43),u=f(2),M=f(101),C=function(){function P(m,c,T,A,S,g,l,h,v){h===void 0&&(h=!0),v===void 0&&(v=!0),this.materialIndex=m,this.verticesStart=c,this.verticesCount=T,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,v&&g.subMeshes.push(this),this._trianglePlanes=[],this._id=g.subMeshes.length-1,h&&(this.refreshBoundingInfo(),g.computeWorldMatrix(!0))}return Object.defineProperty(P.prototype,"materialDefines",{get:function(){return this._materialDefines},set:function(m){this._materialDefines=m},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"effect",{get:function(){var m;return(m=this._effectOverride)!==null&&m!==void 0?m:this._materialEffect},enumerable:!1,configurable:!0}),P.prototype.setEffect=function(m,c){c===void 0&&(c=null),this._materialEffect!==m?(this._materialDefines=c,this._materialEffect=m):m||(this._materialDefines=null)},P.AddToMesh=function(m,c,T,A,S,g,l,h){return h===void 0&&(h=!0),new P(m,c,T,A,S,g,l,h)},Object.defineProperty(P.prototype,"IsGlobal",{get:function(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()},enumerable:!1,configurable:!0}),P.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},P.prototype.setBoundingInfo=function(m){return this._boundingInfo=m,this},P.prototype.getMesh=function(){return this._mesh},P.prototype.getRenderingMesh=function(){return this._renderingMesh},P.prototype.getReplacementMesh=function(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null},P.prototype.getEffectiveMesh=function(){var m=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return m||this._renderingMesh},P.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},P.prototype._IsMultiMaterial=function(m){return m.getSubMaterial!==void 0},P.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(U.b.PositionKind)),!m)return this._boundingInfo=this._mesh.getBoundingInfo(),this;var c,T=this._renderingMesh.getIndices();if(this.indexStart===0&&this.indexCount===T.length){var A=this._renderingMesh.getBoundingInfo();c={minimum:A.minimum.clone(),maximum:A.maximum.clone()}}else c=Object(M.b)(m,T,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(c.minimum,c.maximum):this._boundingInfo=new R.a(c.minimum,c.maximum),this},P.prototype._checkCollision=function(m){return this.getBoundingInfo()._checkCollision(m)},P.prototype.updateBoundingInfo=function(m){var c=this.getBoundingInfo();return c||(this.refreshBoundingInfo(),c=this.getBoundingInfo()),c&&c.update(m),this},P.prototype.isInFrustum=function(m){var c=this.getBoundingInfo();return!!c&&c.isInFrustum(m,this._mesh.cullingStrategy)},P.prototype.isCompletelyInFrustum=function(m){var c=this.getBoundingInfo();return!!c&&c.isCompletelyInFrustum(m)},P.prototype.render=function(m){return this._renderingMesh.render(this,m,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this},P.prototype._getLinesIndexBuffer=function(m,c){if(!this._linesIndexBuffer){for(var T=[],A=this.indexStart;Al&&(l=E)}return new P(m,g,l-g+1,c,T,A,S)},P}()},function(Ie,y,f){f.d(y,"a",function(){return C});var U=f(1),_=f(8),R=f(10),u=f(2),M=(f(126),f(70)),C=function(P){function m(c,T,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 v=P.call(this,null,A,!S,h,g,void 0,void 0,void 0,void 0,l)||this;v.name=c,v.wrapU=R.a.CLAMP_ADDRESSMODE,v.wrapV=R.a.CLAMP_ADDRESSMODE,v._generateMipMaps=S;var E=v._getEngine();if(!E)return v;T.getContext?(v._canvas=T,v._texture=E.createDynamicTexture(T.width,T.height,S,g)):(v._canvas=M.a.CreateCanvas(1,1),T.width||T.width===0?v._texture=E.createDynamicTexture(T.width,T.height,S,g):v._texture=E.createDynamicTexture(T,T,S,g));var D=v.getSize();return v._canvas.width=D.width,v._canvas.height=D.height,v._context=v._canvas.getContext("2d"),v}return Object(U.d)(m,P),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 T=this.getSize();T.width*=c,T.height*=c,this._recreate(T)},m.prototype.scaleTo=function(c,T){var A=this.getSize();A.width=c,A.height=T,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,T){T===void 0&&(T=!1),this._getEngine().updateDynamicTexture(this._texture,this._canvas,c===void 0||c,T,this._format||void 0)},m.prototype.drawText=function(c,T,A,S,g,l,h,v){v===void 0&&(v=!0);var E=this.getSize();if(l&&(this._context.fillStyle=l,this._context.fillRect(0,0,E.width,E.height)),this._context.font=S,T==null){var D=this._context.measureText(c);T=(E.width-D.width)/2}if(A==null){var w=parseInt(S.replace(/\D/g,""));A=E.height/2+w/3.65}this._context.fillStyle=g||"",this._context.fillText(c,T,A),v&&this.update(h)},m.prototype.clone=function(){var c=this.getScene();if(!c)return this;var T=this.getSize(),A=new m(this.name,T,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 T=P.prototype.serialize.call(this);return this._IsCanvasElement(this._canvas)&&(T.base64String=this._canvas.toDataURL()),T.invertY=this._invertY,T.samplingMode=this.samplingMode,T},m.prototype._IsCanvasElement=function(c){return c.toDataURL!==void 0},m.prototype._rebuild=function(){this.update()},m}(R.a)},function(Ie,y,f){f.d(y,"a",function(){return M});var U=f(0),_=f(9),R=f(7),u=f(16);u.a.CreateBox=function(C){var P,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],T=[],A=C.width||C.size||1,S=C.height||C.size||1,g=C.depth||C.size||1,l=C.wrap||!1,h=C.topBaseAt===void 0?1:C.topBaseAt,v=C.bottomBaseAt===void 0?0:C.bottomBaseAt,E=[2,0,3,1][h=(h+4)%4],D=[2,0,1,3][v=(v+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],X=[22,23,20,21];E>0;)N.unshift(N.pop()),V.unshift(V.pop()),E--;for(;D>0;)I.unshift(I.pop()),X.unshift(X.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(X[0],X[2],X[3],X[0],X[1],X[2])}var j=[A/2,S/2,g/2];P=w.reduce(function(G,Q,oe){return G.concat(Q*j[oe%3])},[]);for(var ne=C.sideOrientation===0?0:C.sideOrientation||u.a.DEFAULTSIDE,te=C.faceUV||new Array(6),de=C.faceColors,pe=[],ae=0;ae<6;ae++)te[ae]===void 0&&(te[ae]=new U.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(T.push(te[ee].z,te[ee].w),T.push(te[ee].x,te[ee].w),T.push(te[ee].x,te[ee].y),T.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,P,m,c,T,C.frontUVs,C.backUVs);var $=new u.a;if($.indices=m,$.positions=P,$.normals=c,$.uvs=T,de){var L=ne===u.a.DOUBLESIDE?pe.concat(pe):pe;$.colors=L}return $},R.a.CreateBox=function(C,P,m,c,T){m===void 0&&(m=null);var A={size:P,sideOrientation:T,updatable:c};return M.CreateBox(C,A,m)};var M=function(){function C(){}return C.CreateBox=function(P,m,c){c===void 0&&(c=null);var T=new R.a(P,c);return m.sideOrientation=R.a._GetDefaultSideOrientation(m.sideOrientation),T._originalBuilderSideOrientation=m.sideOrientation,u.a.CreateBox(m).applyToMesh(T,m.updatable),T},C}()},function(Ie,y,f){f.d(y,"a",function(){return _});var U=f(0),_=function(){function R(u,M,C,P){this.normal=new U.e(u,M,C),this.d=P}return R.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},R.prototype.clone=function(){return new R(this.normal.x,this.normal.y,this.normal.z,this.d)},R.prototype.getClassName=function(){return"Plane"},R.prototype.getHashCode=function(){var u=this.normal.getHashCode();return u=397*u^(0|this.d)},R.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},R.prototype.transform=function(u){var M=R._TmpMatrix;u.invertToRef(M);var C=M.m,P=this.normal.x,m=this.normal.y,c=this.normal.z,T=this.d;return new R(P*C[0]+m*C[1]+c*C[2]+T*C[3],P*C[4]+m*C[5]+c*C[6]+T*C[7],P*C[8]+m*C[9]+c*C[10]+T*C[11],P*C[12]+m*C[13]+c*C[14]+T*C[15])},R.prototype.dotCoordinate=function(u){return this.normal.x*u.x+this.normal.y*u.y+this.normal.z*u.z+this.d},R.prototype.copyFromPoints=function(u,M,C){var P,m=M.x-u.x,c=M.y-u.y,T=M.z-u.z,A=C.x-u.x,S=C.y-u.y,g=C.z-u.z,l=c*g-T*S,h=T*A-m*g,v=m*S-c*A,E=Math.sqrt(l*l+h*h+v*v);return P=E!==0?1/E:0,this.normal.x=l*P,this.normal.y=h*P,this.normal.z=v*P,this.d=-(this.normal.x*u.x+this.normal.y*u.y+this.normal.z*u.z),this},R.prototype.isFrontFacingTo=function(u,M){return U.e.Dot(this.normal,u)<=M},R.prototype.signedDistanceTo=function(u){return U.e.Dot(u,this.normal)+this.d},R.FromArray=function(u){return new R(u[0],u[1],u[2],u[3])},R.FromPoints=function(u,M,C){var P=new R(0,0,0,0);return P.copyFromPoints(u,M,C),P},R.FromPositionAndNormal=function(u,M){var C=new R(0,0,0,0);return M.normalize(),C.normal=M,C.d=-(M.x*u.x+M.y*u.y+M.z*u.z),C},R.SignedDistanceToPlaneFromPositionAndNormal=function(u,M,C){var P=-(M.x*u.x+M.y*u.y+M.z*u.z);return U.e.Dot(C,M)+P},R._TmpMatrix=U.a.Identity(),R}()},function(Ie,y,f){f.d(y,"a",function(){return m});var U=f(7),_=f(20),R=f(6),u=f(0),M=f(18),C=f(39),P=f(60),m=(f(84),function(){function c(T){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 R.c,this.onDragStartObservable=new R.c,this.onDragEndObservable=new R.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 C.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=T||{};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(T){this._options=T},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(T,A){var S=this;this._scene=T.getScene(),this.attachedNode=T,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=U.a.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,c._planeScene,!1,U.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 v=l.event.pointerId;if(S.currentDraggingPointerID===c._AnyMouseID&&v!==c._AnyMouseID){var E=l.event;(E.pointerType==="mouse"||!S._scene.getEngine().hostInformation.isMobile&&E instanceof MouseEvent)&&(S._lastPointerRay[S.currentDraggingPointerID]&&(S._lastPointerRay[v]=S._lastPointerRay[S.currentDraggingPointerID],delete S._lastPointerRay[S.currentDraggingPointerID]),S.currentDraggingPointerID=v)}S._lastPointerRay[v]||(S._lastPointerRay[v]=new C.a(new u.e,new u.e)),l.pickInfo&&l.pickInfo.ray&&(S._lastPointerRay[v].origin.copyFrom(l.pickInfo.ray.origin),S._lastPointerRay[v].direction.copyFrom(l.pickInfo.ray.direction),S.currentDraggingPointerID==v&&S.dragging&&S._moveDrag(l.pickInfo.ray))}}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(function(){S._moving&&S.moveAttached&&(P.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),P.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 T=this._scene.activeCamera;T.attachControl(!T.inputs||T.inputs.noPreventDefault,T._useCtrlForPanning,T._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}},c.prototype.startDrag=function(T,A,S){T===void 0&&(T=c._AnyMouseID),this._startDrag(T,A,S);var g=this._lastPointerRay[T];T===c._AnyMouseID&&(g=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),g&&this._moveDrag(g)},c.prototype._startDrag=function(T,A,S){if(this._scene.activeCamera&&!this.dragging&&this.attachedNode){P.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=T,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)),P.a._RestorePivotPoint(this.attachedNode)}},c.prototype._moveDrag=function(T){this._moving=!0;var A=this._pickWithRayOnDragPlane(T);if(A){this.updateDragPlane&&this._updateDragPlanePosition(T,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(T){var A=this;if(!T)return null;var S=Math.acos(u.e.Dot(this._dragPlane.forward,T.direction));if(S>Math.PI/2&&(S=Math.PI-S),this.maxDragAngle>0&&S>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(T.direction),this.attachedNode.absolutePosition.subtractToRef(T.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(T,function(h){return h==A._dragPlane});return l&&l.hit&&l.pickedMesh&&l.pickedPoint?l.pickedPoint:null},c.prototype._updateDragPlanePosition=function(T,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),T.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(T.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(Ie,y,f){f.d(y,"a",function(){return _}),f.d(y,"b",function(){return R}),f.d(y,"c",function(){return u});var U=f(1),_=function(){function M(){}return M.KEYDOWN=1,M.KEYUP=2,M}(),R=function(M,C){this.type=M,this.event=C},u=function(M){function C(P,m){var c=M.call(this,P,m)||this;return c.type=P,c.event=m,c.skipOnPointerObservable=!1,c}return Object(U.d)(C,M),C}(R)},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}return _.prototype.unBindMesh=function(){this._mesh=null},_.prototype.addFallback=function(R,u){this._defines[R]||(Rthis._maxRank&&(this._maxRank=R),this._defines[R]=new Array),this._defines[R].push(u)},_.prototype.addCPUSkinningFallback=function(R,u){this._mesh=u,Rthis._maxRank&&(this._maxRank=R)},Object.defineProperty(_.prototype,"hasMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!1,configurable:!0}),_.prototype.reduce=function(R,u){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,R=R.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),u._bonesComputationForcedToCPU=!0;for(var M=this._mesh.getScene(),C=0;C0&&(P.computeBonesUsingShaders=!1)}}else{var T=this._defines[this._currentRank];if(T)for(C=0;C=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[m]},P.prototype.getActiveTextures=function(){var m;return(m=C.prototype.getActiveTextures.call(this)).concat.apply(m,this.subMaterials.map(function(c){return c?c.getActiveTextures():[]}))},P.prototype.hasTexture=function(m){var c;if(C.prototype.hasTexture.call(this,m))return!0;for(var T=0;T=0&&A.multiMaterials.splice(S,1),C.prototype.dispose.call(this,m,c)}},P.ParseMultiMaterial=function(m,c){var T=new P(m.name,c);T.id=m.id,R.a&&R.a.AddTagsTo(T,m.tags);for(var A=0;A"u")return new OffscreenCanvas(R,u);var M=document.createElement("canvas");return M.width=R,M.height=u,M},_}()},function(Ie,y,f){f.d(y,"a",function(){return S});var U=f(0),_=f(9),R=f(16),u=f(4),M=f(61),C=f(69),P=f(43),m=f(2),c=f(12),T=f(37),A=f(101),S=function(){function g(l,h,v,E,D){E===void 0&&(E=!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=E,v?this.setAllVerticesData(v,E):(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,v=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 X=new Float32Array(l,w.uvsAttrDesc.offset,w.uvsAttrDesc.count);h.setVerticesData(u.b.UVKind,X,!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&W)>>16),K.push(W>>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&W)>>16),K.push(W>>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 E=h.getScene().getLastSkeletonByID(l.skeletonId);if(E){v=E.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,X=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]=v):(N[j+te]=1-ne,D[j+te]=v)}h.setVerticesData(u.b.MatricesIndicesKind,D),l.matricesWeightsExtra&&h.setVerticesData(u.b.MatricesIndicesExtraKind,w)}}}},g.Parse=function(l,h,v){if(h.getGeometryByID(l.id))return null;var E=new g(l.id,h,void 0,l.updatable);return T.a&&T.a.AddTagsTo(E,l.tags),l.delayLoadingFile?(E.delayLoadState=m.a.DELAYLOADSTATE_NOTLOADED,E.delayLoadingFile=v+l.delayLoadingFile,E._boundingInfo=new P.a(U.e.FromArray(l.boundingBoxMinimum),U.e.FromArray(l.boundingBoxMaximum)),E._delayInfo=[],l.hasUVs&&E._delayInfo.push(u.b.UVKind),l.hasUVs2&&E._delayInfo.push(u.b.UV2Kind),l.hasUVs3&&E._delayInfo.push(u.b.UV3Kind),l.hasUVs4&&E._delayInfo.push(u.b.UV4Kind),l.hasUVs5&&E._delayInfo.push(u.b.UV5Kind),l.hasUVs6&&E._delayInfo.push(u.b.UV6Kind),l.hasColors&&E._delayInfo.push(u.b.ColorKind),l.hasMatricesIndices&&E._delayInfo.push(u.b.MatricesIndicesKind),l.hasMatricesWeights&&E._delayInfo.push(u.b.MatricesWeightsKind),E._delayLoadingFunction=R.a.ImportVertexData):R.a.ImportVertexData(l,E),h.pushGeometry(E,!0),E},g}()},function(Ie,y,f){f.d(y,"e",function(){return U}),f.d(y,"c",function(){return M}),f.d(y,"a",function(){return C}),f.d(y,"b",function(){return P}),f.d(y,"f",function(){return m}),f.d(y,"g",function(){return c}),f.d(y,"d",function(){return T});var U,_=f(14),R=f(0),u=f(28);(function(A){A[A.CW=0]="CW",A[A.CCW=1]="CCW"})(U||(U={}));var M=function(){function A(){}return A.Interpolate=function(S,g,l,h,v){for(var E=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-=(E*(V*N)+D*V+w*N-S)*(1/(3*E*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)*v+Math.pow(N,3)},A}(),C=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}(),P=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,v=(l-Math.pow(g.x,2)-Math.pow(g.y,2))/2,E=(A.x-S.x)*(S.y-g.y)-(S.x-g.x)*(A.y-S.y);this.centerPoint=new R.d((h*(S.y-g.y)-v*(A.y-S.y))/E,((A.x-S.x)*v-(S.x-g.x)*h)/E),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=C.BetweenTwoPoints(this.centerPoint,this.startPoint);var D=this.startAngle.degrees(),w=C.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),N=C.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?U.CW:U.CCW,this.angle=C.FromDegrees(this.orientation===U.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 R.d(S,g))}return A.prototype.addLineTo=function(S,g){if(this.closed)return this;var l=new R.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,v){if(v===void 0&&(v=36),this.closed)return this;var E=this._points[this._points.length-1],D=new R.d(S,g),w=new R.d(l,h),N=new P(E,D,w),I=N.angle.radians()/v;N.orientation===U.CW&&(I*=-1);for(var V=N.startAngle.radians()+I,X=0;X1)return R.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 R.d(E.x+N.x*I,E.y+N.y*I)}l=w}return R.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:R.e.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:R.a.Identity()};for(var v=0;vg){var l=S;S=g,g=l}var h=this.getCurve(),v=this.getPointAt(S),E=this.getPreviousPointIndexAt(S),D=this.getPointAt(g),w=this.getPreviousPointIndexAt(g)+1,N=[];return S!==0&&(E++,N.push(v)),N.push.apply(N,h.slice(E,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,v=S.length();return v===0&&(v=1),g==null?(h=_.a.WithinEpsilon(Math.abs(S.y)/v,1,u.a)?_.a.WithinEpsilon(Math.abs(S.x)/v,1,u.a)?_.a.WithinEpsilon(Math.abs(S.z)/v,1,u.a)?R.e.Zero():new R.e(0,0,1):new R.e(1,0,0):new R.e(0,-1,0),l=R.e.Cross(S,h)):(l=R.e.Cross(S,g),R.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,v=l[0],E=0,D=S*this.length(),w=1;wD){var I=(E-D)/N,V=v.subtract(h),X=h.add(V.scaleInPlace(I));return this._setPointAtData(S,1-I,X,w-1,g)}v=h}return this._pointAtData},A.prototype._setPointAtData=function(S,g,l,h,v){return this._pointAtData.point=l,this._pointAtData.position=S,this._pointAtData.subPosition=g,this._pointAtData.previousPointArrayIndex=h,this._pointAtData.interpolateReady=v,v&&this._updateInterpolationMatrix(),this._pointAtData},A.prototype._updateInterpolationMatrix=function(){this._pointAtData.interpolationMatrix=R.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(),v=this._binormals[S].clone(),E=this._tangents[g].clone(),D=this._normals[g].clone(),w=this._binormals[g].clone(),N=R.b.RotationQuaternionFromAxis(h,v,l),I=R.b.RotationQuaternionFromAxis(D,w,E);R.b.Slerp(N,I,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}},A}(),T=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 v=new Array,E=function(w,N,I,V){return(1-w)*(1-w)*N+2*w*(1-w)*I+w*w*V},D=0;D<=h;D++)v.push(new R.e(E(D/h,S.x,g.x,l.x),E(D/h,S.y,g.y,l.y),E(D/h,S.z,g.z,l.z)));return new A(v)},A.CreateCubicBezier=function(S,g,l,h,v){v=v>3?v:4;for(var E=new Array,D=function(N,I,V,X,j){return(1-N)*(1-N)*(1-N)*I+3*N*(1-N)*(1-N)*V+3*N*N*(1-N)*X+N*N*N*j},w=0;w<=v;w++)E.push(new R.e(D(w/v,S.x,g.x,l.x,h.x),D(w/v,S.y,g.y,l.y,h.y),D(w/v,S.z,g.z,l.z,h.z)));return new A(E)},A.CreateHermiteSpline=function(S,g,l,h,v){for(var E=new Array,D=1/v,w=0;w<=v;w++)E.push(R.e.Hermite(S,g,l,h,w*D));return new A(E)},A.CreateCatmullRomSpline=function(S,g,l){var h=new Array,v=1/g,E=0;if(l){for(var D=S.length,w=0;w1&&(this._multiview=!0,X.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=E.skeleton;de=E.numBoneInfluencers,X.push("#define NUM_BONE_INFLUENCERS "+de),ne.addCPUSkinningFallback(0,E),pe.isUsingTextureForMatrices?(X.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")):(X.push("#define BonesPerMesh "+(pe.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else X.push("#define NUM_BONE_INFLUENCERS 0");for(var ae in this._textures)if(!this._textures[ae].isReady())return!1;E&&this._shouldTurnAlphaTestOn(E)&&X.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,X,j));var G=this._effect,Q=X.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)},v.prototype.bindOnlyWorldMatrix=function(E,D){var w=this.getScene(),N=D??this._effect;N&&(this._options.uniforms.indexOf("world")!==-1&&N.setMatrix("world",E),this._options.uniforms.indexOf("worldView")!==-1&&(E.multiplyToRef(w.getViewMatrix(),this._cachedWorldViewMatrix),N.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(E.multiplyToRef(w.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),N.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))},v.prototype.bindForSubMesh=function(E,D,w){this.bind(E,D,w._effectOverride)},v.prototype.bind=function(E,D,w){this.bindOnlyWorldMatrix(E,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),C.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 X=this._effect;this._effect=N,this._afterBind(D),this._effect=X},v.prototype._afterBind=function(E){h.prototype._afterBind.call(this,E),this.getScene()._cachedEffect=this._effect},v.prototype.getActiveTextures=function(){var E=h.prototype.getActiveTextures.call(this);for(var D in this._textures)E.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=E._getSharedGizmoLight();de.includedOnlyMeshes=de.includedOnlyMeshes.concat(I._rootMesh.getChildMeshes(!1));var pe={gizmoMeshes:V.getChildMeshes(),colliderMeshes:X.getChildMeshes(),material:I._coloredMaterial,hoverMaterial:I._hoverMaterial,disableMaterial:I._disableMaterial,active:!1};return(N=I._parent)===null||N===void 0||N.addToAxisCache(X,pe),I._pointerObserver=E.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(U.d)(l,g),l._CreateArrow=function(h,v,E,D){E===void 0&&(E=1),D===void 0&&(D=!1);var w=new u.a("arrow",h),N=C.a.CreateCylinder("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(E-1)/4),tessellation:96},h),I=C.a.CreateCylinder("cylinder",{diameterTop:.005*E,height:.275,diameterBottom:.005*E,tessellation:96},h);return N.parent=w,N.material=v,N.rotation.x=Math.PI/2,N.position.z+=.3,I.parent=w,I.material=v,I.position.z+=.1375,I.rotation.x=Math.PI/2,D&&(I.visibility=0,N.visibility=0),w},l._CreateArrowInstance=function(h,v){for(var E=new u.a("arrow",h),D=0,w=v.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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U=`#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=U},function(Ie,y,f){f.d(y,"a",function(){return C});var U=f(0),_=f(7),R=f(4),u=f(16),M=f(43);u.a.CreateRibbon=function(P){var m=P.pathArray,c=P.closeArray||!1,T=P.closePath||!1,A=P.invertUV||!1,S=Math.floor(m[0].length/2),g=P.offset||S;g=g>S?S:Math.floor(g);var l,h,v,E,D=P.sideOrientation===0?0:P.sideOrientation||u.a.DEFAULTSIDE,w=P.uvs,N=P.colors,I=[],V=[],X=[],j=[],ne=[],te=[],de=[],pe=[],ae=[],ee=[];if(m.length<2){var K=[],$=[];for(v=0;v0&&(Q=L[E].subtract(L[E-1]).length()+de[h],ne[h].push(Q),de[h]=Q),E++;T&&(E--,I.push(L[0].x,L[0].y,L[0].z),Q=L[E].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,W=null,q=null;for(v=0;v=U.a.ACTION_OnPickTrigger&&M<=U.a.ACTION_OnPickUpTrigger)return!0}return!1},enumerable:!1,configurable:!0}),R.HasSpecificTrigger=function(u){for(var M in R.Triggers)if(R.Triggers.hasOwnProperty(M)&&parseInt(M)===u)return!0;return!1},R.Triggers={},R}()},function(Ie,y,f){f.d(y,"a",function(){return C});var U=f(1),_=f(25),R=f(3),u=f(19),M=f(15),C=function(){function P(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 P.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},P.prototype.isReadyForSubMesh=function(m,c){var T=c.getEngine();return!(m._areTexturesDirty&&c.texturesEnabled&&T.getCaps().standardDerivatives&&this._texture&&u.a.DetailTextureEnabled&&!this._texture.isReady())},P.prototype.prepareDefines=function(m,c){if(this._isEnabled){m.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;var T=c.getEngine();m._areTexturesDirty&&(T.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},P.prototype.bindForSubMesh=function(m,c,T){this._isEnabled&&(m.useUbo&&T&&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))},P.prototype.hasTexture=function(m){return this._texture===m},P.prototype.getActiveTextures=function(m){this._texture&&m.push(this._texture)},P.prototype.getAnimatables=function(m){this._texture&&this._texture.animations&&this._texture.animations.length>0&&m.push(this._texture)},P.prototype.dispose=function(m){var c;m&&((c=this._texture)===null||c===void 0||c.dispose())},P.prototype.getClassName=function(){return"DetailMap"},P.AddUniforms=function(m){m.push("vDetailInfos")},P.AddSamplers=function(m){m.push("detailSampler")},P.PrepareUniformBuffer=function(m){m.addUniform("vDetailInfos",4),m.addUniform("detailMatrix",16)},P.prototype.copyTo=function(m){R.a.Clone(function(){return m},this)},P.prototype.serialize=function(){return R.a.Serialize(this)},P.prototype.parse=function(m,c,T){var A=this;R.a.Parse(function(){return A},m,c,T)},Object(U.c)([Object(R.m)("detailTexture"),Object(R.b)("_markAllSubMeshesAsTexturesDirty")],P.prototype,"texture",void 0),Object(U.c)([Object(R.c)()],P.prototype,"diffuseBlendLevel",void 0),Object(U.c)([Object(R.c)()],P.prototype,"roughnessBlendLevel",void 0),Object(U.c)([Object(R.c)()],P.prototype,"bumpLevel",void 0),Object(U.c)([Object(R.c)(),Object(R.b)("_markAllSubMeshesAsTexturesDirty")],P.prototype,"normalBlendMethod",void 0),Object(U.c)([Object(R.c)(),Object(R.b)("_markAllSubMeshesAsTexturesDirty")],P.prototype,"isEnabled",void 0),P}()},function(Ie,y,f){var U="morphTargetsVertexGlobalDeclaration",_=`#ifdef MORPHTARGETS -uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; -#endif`;f(5).a.IncludesShadersStore[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){f.d(y,"a",function(){return u});var U=f(25),_=f(4),R=f(2),u=function(){function M(C){this._vertexBuffers={},this._scene=C}return M.prototype._prepareBuffers=function(){if(!this._vertexBuffers[_.b.PositionKind]){var C=[];C.push(1,1),C.push(-1,1),C.push(-1,-1),C.push(1,-1),this._vertexBuffers[_.b.PositionKind]=new _.b(this._scene.getEngine(),C,_.b.PositionKind,!1,!1,2),this._buildIndexBuffer()}},M.prototype._buildIndexBuffer=function(){var C=[];C.push(0),C.push(1),C.push(2),C.push(0),C.push(2),C.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(C)},M.prototype._rebuild=function(){var C=this._vertexBuffers[_.b.PositionKind];C&&(C._rebuild(),this._buildIndexBuffer())},M.prototype._prepareFrame=function(C,P){C===void 0&&(C=null),P===void 0&&(P=null);var m=this._scene.activeCamera;return!!m&&!(!(P=P||m._postProcesses.filter(function(c){return c!=null}))||P.length===0||!this._scene.postProcessesEnabled)&&(P[0].activate(m,C,P!=null),!0)},M.prototype.directRender=function(C,P,m,c,T,A){P===void 0&&(P=null),m===void 0&&(m=!1),c===void 0&&(c=0),T===void 0&&(T=0),A===void 0&&(A=!1);for(var S=this._scene.getEngine(),g=0;g3?0:v,E);var ae=R.a.CreateRibbon(P,{pathArray:te,closeArray:l,closePath:h,updatable:w,sideOrientation:N,invertUV:V,frontUVs:X||void 0,backUVs:j||void 0},D);return ae._creationDataStorage.pathArray=te,ae._creationDataStorage.path3D=ne,ae._creationDataStorage.cap=v,ae},C}()},function(Ie,y,f){f.d(y,"b",function(){return c}),f.d(y,"a",function(){return T});var U=f(1),_=f(9),R=f(4),u=f(7),M=f(151),C=f(25),P=f(73),m=f(15),c=(f(166),f(167),function(A){function S(g,l,h,v,E,D,w){l===void 0&&(l=null),h===void 0&&(h=null),v===void 0&&(v=null);var N=A.call(this,g,l,h,v,E)||this;N.useVertexColor=D,N.useVertexAlpha=w,N.color=new _.a(1,1,1),N.alpha=1,v&&(N.color=v.color.clone(),N.alpha=v.alpha,N.useVertexColor=v.useVertexColor,N.useVertexAlpha=v.useVertexAlpha),N.intersectionThreshold=.1;var I={attributes:[R.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(R.b.ColorKind)):(I.uniforms.push("color"),N.color4=new _.b),N._colorShader=new P.a("colorShader",N.getScene(),"color",I),N}return Object(U.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 v=this._colorShader.getEffect(),E=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._geometry._bind(v,E),!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(v,this.getScene()),this},S.prototype._draw=function(g,l,h){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var v=this.getScene().getEngine();return this._unIndexed?v.drawArraysType(C.a.LineListDrawMode,g.verticesStart,g.verticesCount,h):v.drawElementsType(C.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 T(g,this)},S}(u.a)),T=function(A){function S(g,l){var h=A.call(this,g,l)||this;return h.intersectionThreshold=l.intersectionThreshold,h}return Object(U.d)(S,A),S.prototype.getClassName=function(){return"InstancedLinesMesh"},S}(M.a)},function(Ie,y,f){f.r(y),f.d(y,"AxesViewer",function(){return C}),f.d(y,"BoneAxesViewer",function(){return c}),f.d(y,"DebugLayerTab",function(){return U}),f.d(y,"DebugLayer",function(){return l}),f.d(y,"PhysicsViewer",function(){return V}),f.d(y,"RayHelper",function(){return j}),f.d(y,"SkeletonViewer",function(){return K});var U,_=f(0),R=f(30),u=f(75),M=f(9),C=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 R.a("",L);k.disableLighting=!0,k.emissiveColor=M.a.Red().scale(.5),oe=u.a._CreateArrow(L,k)}if(!re){var H=new R.a("",L);H.disableLighting=!0,H.emissiveColor=M.a.Green().scale(.5),re=u.a._CreateArrow(L,H)}if(!Y){var Z=new R.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})},$}(),P=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(P.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}(C),T=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"}(U||(U={}));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 R.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=v.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=E.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&&(Ge=$.DISPLAY_LINES),this.displayMode=Ge,this.update(),this._bindObs()}return $.CreateBoneWeightShader=function(L,G){var Q,oe,re,Y,k,H,Z=L.skeleton,W=(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",W),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(W){Y.addColorStop(W.location,W.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,W=this.options.displayOptions||{},q=function(He){var Qe=re[He];if(Qe._index===-1||!he._boneIndices.has(Qe.getIndex())&&!he.options.useAllBones)return"continue";var Ge=new _.a;he._getAbsoluteBindPoseToRef(Qe,Ge);var nt=new _.e;Ge.decompose(void 0,void 0,nt),Qe.children.forEach(function(It,Pt){var Ot=new _.a;It.getBindPose().multiplyToRef(Ge,Ot);var on=new _.e;Ot.decompose(void 0,void 0,on);var Zt=_.e.Distance(nt,on);if(Zt>Z&&(Z=Zt),!L){for(var tn=on.clone().subtract(nt.clone()),De=tn.length(),Pn=tn.normalize().scale(De),nn=W.midStep||.165,xn=W.midStepFactor||.215,Ue=Pn.scale(nn),Cn=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,Pn],scaleFunction:function(No){switch(No){case 0:case 2:return 0;case 1:return De*xn}return 0},sideOrientation:h.a.DEFAULTSIDE,updatable:!1},oe),dr=Cn.getTotalVertices(),Xe=[],An=[],ei=0;ei9?An.push(It.getIndex(),0,0,0):An.push(Qe.getIndex(),0,0,0);Cn.position=nt.clone(),Cn.setVerticesData(pe.b.MatricesWeightsKind,Xe,!1),Cn.setVerticesData(pe.b.MatricesIndicesKind,An,!1),Cn.convertToFlatShadedMesh(),k.push(Cn)}});for(var $e=W.sphereBaseSize||.2,ct=E.a.CreateSphere("skeletonViewer",{segments:6,diameter:$e,updatable:!0},oe),st=ct.getTotalVertices(),mt=[],St=[],wt=0;wth-c)&&!(g-vv-T)&&!(l-EE-A)},M.prototype.intersectsSphere=function(C){return M.IntersectsSphere(this.minimumWorld,this.maximumWorld,C.centerWorld,C.radiusWorld)},M.prototype.intersectsMinMax=function(C,P){var m=this.minimumWorld,c=this.maximumWorld,T=m.x,A=m.y,S=m.z,g=c.x,l=c.y,h=c.z,v=C.x,E=C.y,D=C.z,w=P.x,N=P.y,I=P.z;return!(gw)&&!(lN)&&!(hI)},M.Intersects=function(C,P){return C.intersectsMinMax(P.minimumWorld,P.maximumWorld)},M.IntersectsSphere=function(C,P,m,c){var T=M.TmpVector3[0];return _.e.ClampToRef(m,C,P,T),_.e.DistanceSquared(m,T)<=c*c},M.IsCompletelyInFrustum=function(C,P){for(var m=0;m<6;++m)for(var c=P[m],T=0;T<8;++T)if(c.dotCoordinate(C[T])<0)return!1;return!0},M.IsInFrustum=function(C,P){for(var m=0;m<6;++m){for(var c=!0,T=P[m],A=0;A<8;++A)if(T.dotCoordinate(C[A])>=0){c=!1;break}if(c)return!1}return!0},M.TmpVector3=U.a.BuildArray(3,_.e.Zero),M}()},function(Ie,y,f){f.d(y,"a",function(){return _});var U=f(38),_=function(){function R(){}return R.SetImmediate=function(u){U.a.IsWindowObjectExist()&&window.setImmediate?window.setImmediate(u):setTimeout(u,1)},R}()},function(Ie,y,f){f.d(y,"a",function(){return R});var U=f(0),_=f(2),R=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,C,P,m,c){C.prePassRenderer&&C.prePassRenderer.enabled&&C.prePassRenderer.getIndex(_.a.PREPASS_VELOCITY_TEXTURE_TYPE)!==-1&&(this.previousWorldMatrices[P.uniqueId]||(this.previousWorldMatrices[P.uniqueId]=U.a.Identity()),this.previousViewProjection||(this.previousViewProjection=C.getTransformMatrix()),M.setMatrix("previousWorld",this.previousWorldMatrices[P.uniqueId]),M.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[P.uniqueId]=m.clone(),this.previousViewProjection=C.getTransformMatrix().clone())},u}()},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){f.d(y,"a",function(){return U});var U=function(){function _(){this._count=0,this._data={}}return _.prototype.copyFrom=function(R){var u=this;this.clear(),R.forEach(function(M,C){return u.add(M,C)})},_.prototype.get=function(R){var u=this._data[R];if(u!==void 0)return u},_.prototype.getOrAddWithFactory=function(R,u){var M=this.get(R);return M!==void 0||(M=u(R))&&this.add(R,M),M},_.prototype.getOrAdd=function(R,u){var M=this.get(R);return M!==void 0?M:(this.add(R,u),u)},_.prototype.contains=function(R){return this._data[R]!==void 0},_.prototype.add=function(R,u){return this._data[R]===void 0&&(this._data[R]=u,++this._count,!0)},_.prototype.set=function(R,u){return this._data[R]!==void 0&&(this._data[R]=u,!0)},_.prototype.getAndRemove=function(R){var u=this.get(R);return u!==void 0?(delete this._data[R],--this._count,u):null},_.prototype.remove=function(R){return!!this.contains(R)&&(delete this._data[R],--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(R){for(var u in this._data)R(u,this._data[u])},_.prototype.first=function(R){for(var u in this._data){var M=R(u,this._data[u]);if(M)return M}return null},_}()},function(Ie,y,f){f.d(y,"a",function(){return R});var U=f(44),_=f(0),R=function(){function u(M,C,P){this.center=_.e.Zero(),this.centerWorld=_.e.Zero(),this.minimum=_.e.Zero(),this.maximum=_.e.Zero(),this.reConstruct(M,C,P)}return u.prototype.reConstruct=function(M,C,P){this.minimum.copyFrom(M),this.maximum.copyFrom(C);var m=_.e.Distance(M,C);C.addToRef(M,this.center).scaleInPlace(.5),this.radius=.5*m,this._update(P||_.a.IdentityReadOnly)},u.prototype.scale=function(M){var C=this.radius*M,P=u.TmpVector3,m=P[0].setAll(C),c=this.center.subtractToRef(m,P[1]),T=this.center.addToRef(m,P[2]);return this.reConstruct(c,T,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 C=u.TmpVector3[0];_.e.TransformNormalFromFloatsToRef(1,1,1,M,C),this.radiusWorld=Math.max(Math.abs(C.x),Math.abs(C.y),Math.abs(C.z))*this.radius}},u.prototype.isInFrustum=function(M){for(var C=this.centerWorld,P=this.radiusWorld,m=0;m<6;m++)if(M[m].dotCoordinate(C)<=-P)return!1;return!0},u.prototype.isCenterInFrustum=function(M){for(var C=this.centerWorld,P=0;P<6;P++)if(M[P].dotCoordinate(C)<0)return!1;return!0},u.prototype.intersectsPoint=function(M){var C=_.e.DistanceSquared(this.centerWorld,M);return!(this.radiusWorld*this.radiusWorld=C&&u===0?R instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,u,new Float32Array(R)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,u,R):R instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(R).subarray(u,u+M)):(R=R instanceof ArrayBuffer?new Uint8Array(R,u,M):new Uint8Array(R.buffer,R.byteOffset+u,M),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,R)),this._resetVertexBufferBinding()}},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U=f(26),_=f(27);U.a.prototype.createDynamicTexture=function(R,u,M,C){var P=new _.a(this,_.b.Dynamic);return P.baseWidth=R,P.baseHeight=u,M&&(R=this.needPOTTextures?U.a.GetExponentOfTwo(R,this._caps.maxTextureSize):R,u=this.needPOTTextures?U.a.GetExponentOfTwo(u,this._caps.maxTextureSize):u),P.width=R,P.height=u,P.isReady=!1,P.generateMipMaps=M,P.samplingMode=C,this.updateTextureSamplingMode(C,P),this._internalTexturesCache.push(P),P},U.a.prototype.updateDynamicTexture=function(R,u,M,C,P,m){if(C===void 0&&(C=!1),m===void 0&&(m=!1),R){var c=this._gl,T=c.TEXTURE_2D,A=this._bindTextureDirectly(T,R,!0,m);this._unpackFlipY(M===void 0?R.invertY:M),C&&c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var S=this._getWebGLTextureType(R.type),g=this._getInternalFormat(P||R.format),l=this._getRGBABufferInternalSizedFormat(R.type,g);c.texImage2D(T,0,l,g,S,u),R.generateMipMaps&&c.generateMipmap(T),A||this._bindTextureDirectly(T,null),C&&c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),R.isReady=!0}}},function(Ie,y,f){f.r(y),f.d(y,"AbstractScene",function(){return U.a}),f.d(y,"AbstractActionManager",function(){return _.a}),f.d(y,"Action",function(){return P}),f.d(y,"ActionEvent",function(){return m.a}),f.d(y,"ActionManager",function(){return pe}),f.d(y,"Condition",function(){return T}),f.d(y,"ValueCondition",function(){return A}),f.d(y,"PredicateCondition",function(){return S}),f.d(y,"StateCondition",function(){return g}),f.d(y,"SwitchBooleanAction",function(){return v}),f.d(y,"SetStateAction",function(){return E}),f.d(y,"SetValueAction",function(){return D}),f.d(y,"IncrementValueAction",function(){return w}),f.d(y,"PlayAnimationAction",function(){return N}),f.d(y,"StopAnimationAction",function(){return I}),f.d(y,"DoNothingAction",function(){return V}),f.d(y,"CombineAction",function(){return X}),f.d(y,"ExecuteCodeAction",function(){return j}),f.d(y,"SetParentAction",function(){return ne}),f.d(y,"PlaySoundAction",function(){return ae}),f.d(y,"StopSoundAction",function(){return ee}),f.d(y,"InterpolateValueAction",function(){return H}),f.d(y,"Animatable",function(){return ke}),f.d(y,"_IAnimationState",function(){return Y}),f.d(y,"Animation",function(){return k}),f.d(y,"TargetedAnimation",function(){return We}),f.d(y,"AnimationGroup",function(){return je}),f.d(y,"AnimationPropertiesOverride",function(){return He}),f.d(y,"EasingFunction",function(){return Ge}),f.d(y,"CircleEase",function(){return nt}),f.d(y,"BackEase",function(){return $e}),f.d(y,"BounceEase",function(){return ct}),f.d(y,"CubicEase",function(){return st}),f.d(y,"ElasticEase",function(){return mt}),f.d(y,"ExponentialEase",function(){return St}),f.d(y,"PowerEase",function(){return wt}),f.d(y,"QuadraticEase",function(){return It}),f.d(y,"QuarticEase",function(){return Pt}),f.d(y,"QuinticEase",function(){return Ot}),f.d(y,"SineEase",function(){return on}),f.d(y,"BezierCurveEase",function(){return Zt}),f.d(y,"RuntimeAnimation",function(){return me}),f.d(y,"AnimationEvent",function(){return tn}),f.d(y,"AnimationKeyInterpolation",function(){return K}),f.d(y,"AnimationRange",function(){return G}),f.d(y,"KeepAssets",function(){return Pn}),f.d(y,"InstantiatedEntries",function(){return nn}),f.d(y,"AssetContainer",function(){return xn}),f.d(y,"Analyser",function(){return Cn}),f.d(y,"AudioEngine",function(){return dr}),f.d(y,"AudioSceneComponent",function(){return ti}),f.d(y,"Sound",function(){return ei}),f.d(y,"SoundTrack",function(){return No}),f.d(y,"WeightedSound",function(){return Mf}),f.d(y,"AutoRotationBehavior",function(){return _l}),f.d(y,"BouncingBehavior",function(){return ml}),f.d(y,"FramingBehavior",function(){return gl}),f.d(y,"AttachToBoxBehavior",function(){return If}),f.d(y,"FadeInOutBehavior",function(){return Df}),f.d(y,"MultiPointerScaleBehavior",function(){return Lf}),f.d(y,"PointerDragBehavior",function(){return vi.a}),f.d(y,"SixDofDragBehavior",function(){return vl}),f.d(y,"Bone",function(){return Be}),f.d(y,"BoneIKController",function(){return Nf}),f.d(y,"BoneLookController",function(){return wf}),f.d(y,"Skeleton",function(){return wo}),f.d(y,"ArcRotateCameraGamepadInput",function(){return ja}),f.d(y,"ArcRotateCameraKeyboardMoveInput",function(){return Ha}),f.d(y,"ArcRotateCameraMouseWheelInput",function(){return Wa}),f.d(y,"ArcRotateCameraPointersInput",function(){return Xa}),f.d(y,"ArcRotateCameraVRDeviceOrientationInput",function(){return Ya}),f.d(y,"FlyCameraKeyboardInput",function(){return Ka}),f.d(y,"FlyCameraMouseInput",function(){return Qa}),f.d(y,"FollowCameraKeyboardMoveInput",function(){return qa}),f.d(y,"FollowCameraMouseWheelInput",function(){return Za}),f.d(y,"FollowCameraPointersInput",function(){return Ja}),f.d(y,"FreeCameraDeviceOrientationInput",function(){return is}),f.d(y,"FreeCameraGamepadInput",function(){return rs}),f.d(y,"FreeCameraKeyboardMoveInput",function(){return $a}),f.d(y,"FreeCameraMouseInput",function(){return es}),f.d(y,"FreeCameraMouseWheelInput",function(){return ts}),f.d(y,"FreeCameraTouchInput",function(){return ns}),f.d(y,"FreeCameraVirtualJoystickInput",function(){return as}),f.d(y,"CameraInputTypes",function(){return un}),f.d(y,"CameraInputsManager",function(){return Zr}),f.d(y,"Camera",function(){return gt.a}),f.d(y,"TargetCamera",function(){return Li}),f.d(y,"FreeCamera",function(){return Yn}),f.d(y,"FreeCameraInputsManager",function(){return Jr}),f.d(y,"TouchCamera",function(){return ss}),f.d(y,"ArcRotateCamera",function(){return Zi}),f.d(y,"ArcRotateCameraInputsManager",function(){return Fo}),f.d(y,"DeviceOrientationCamera",function(){return Bo}),f.d(y,"FlyCamera",function(){return Uf}),f.d(y,"FlyCameraInputsManager",function(){return Pl}),f.d(y,"FollowCamera",function(){return Cl}),f.d(y,"ArcFollowCamera",function(){return Rl}),f.d(y,"FollowCameraInputsManager",function(){return xl}),f.d(y,"GamepadCamera",function(){return Uo}),f.d(y,"AnaglyphArcRotateCamera",function(){return Nl}),f.d(y,"AnaglyphFreeCamera",function(){return wl}),f.d(y,"AnaglyphGamepadCamera",function(){return Fl}),f.d(y,"AnaglyphUniversalCamera",function(){return Bl}),f.d(y,"StereoscopicArcRotateCamera",function(){return Ul}),f.d(y,"StereoscopicFreeCamera",function(){return Vl}),f.d(y,"StereoscopicGamepadCamera",function(){return kl}),f.d(y,"StereoscopicUniversalCamera",function(){return Gl}),f.d(y,"UniversalCamera",function(){return _r}),f.d(y,"VirtualJoysticksCamera",function(){return zl}),f.d(y,"VRCameraMetrics",function(){return mr}),f.d(y,"VRDeviceOrientationArcRotateCamera",function(){return Xl}),f.d(y,"VRDeviceOrientationFreeCamera",function(){return Vo}),f.d(y,"VRDeviceOrientationGamepadCamera",function(){return Yl}),f.d(y,"OnAfterEnteringVRObservableEvent",function(){return Kf}),f.d(y,"VRExperienceHelper",function(){return Zl}),f.d(y,"WebVRFreeCamera",function(){return Go}),f.d(y,"Collider",function(){return Jl}),f.d(y,"DefaultCollisionCoordinator",function(){return $l}),f.d(y,"PickingInfo",function(){return tr.a}),f.d(y,"IntersectionInfo",function(){return Qf.a}),f.d(y,"_MeshCollisionData",function(){return qf.a}),f.d(y,"BoundingBox",function(){return ms.a}),f.d(y,"BoundingInfo",function(){return Ui.a}),f.d(y,"BoundingSphere",function(){return eu.a}),f.d(y,"Octree",function(){return eo}),f.d(y,"OctreeBlock",function(){return tu}),f.d(y,"OctreeSceneComponent",function(){return Ts}),f.d(y,"Ray",function(){return dn.a}),f.d(y,"AxesViewer",function(){return nr.AxesViewer}),f.d(y,"BoneAxesViewer",function(){return nr.BoneAxesViewer}),f.d(y,"DebugLayerTab",function(){return nr.DebugLayerTab}),f.d(y,"DebugLayer",function(){return nr.DebugLayer}),f.d(y,"PhysicsViewer",function(){return nr.PhysicsViewer}),f.d(y,"RayHelper",function(){return nr.RayHelper}),f.d(y,"SkeletonViewer",function(){return nr.SkeletonViewer}),f.d(y,"DeviceInputSystem",function(){return nu}),f.d(y,"DeviceType",function(){return Kt}),f.d(y,"PointerInput",function(){return gs}),f.d(y,"DualShockInput",function(){return vs}),f.d(y,"XboxInput",function(){return bs}),f.d(y,"SwitchInput",function(){return ys}),f.d(y,"DeviceSource",function(){return iu}),f.d(y,"DeviceSourceManager",function(){return Zf}),f.d(y,"Constants",function(){return h.a}),f.d(y,"ThinEngine",function(){return Bt.a}),f.d(y,"Engine",function(){return Ue.a}),f.d(y,"EngineStore",function(){return te.a}),f.d(y,"NullEngineOptions",function(){return ru.b}),f.d(y,"NullEngine",function(){return ru.a}),f.d(y,"_OcclusionDataStorage",function(){return au}),f.d(y,"_forceTransformFeedbackToBundle",function(){return Jf}),f.d(y,"EngineView",function(){return $f}),f.d(y,"WebGLPipelineContext",function(){return tp.a}),f.d(y,"WebGL2ShaderProcessor",function(){return su.a}),f.d(y,"NativeEngine",function(){return ap}),f.d(y,"ShaderCodeInliner",function(){return Ss}),f.d(y,"PerformanceConfigurator",function(){return sp.a}),f.d(y,"KeyboardEventTypes",function(){return qi.a}),f.d(y,"KeyboardInfo",function(){return qi.b}),f.d(y,"KeyboardInfoPre",function(){return qi.c}),f.d(y,"PointerEventTypes",function(){return Tt.a}),f.d(y,"PointerInfoBase",function(){return Tt.c}),f.d(y,"PointerInfoPre",function(){return Tt.d}),f.d(y,"PointerInfo",function(){return Tt.b}),f.d(y,"ClipboardEventTypes",function(){return Wo}),f.d(y,"ClipboardInfo",function(){return cp}),f.d(y,"DaydreamController",function(){return Ps}),f.d(y,"GearVRController",function(){return xs}),f.d(y,"GenericController",function(){return Xo}),f.d(y,"OculusTouchController",function(){return Cs}),f.d(y,"PoseEnabledControllerType",function(){return ii}),f.d(y,"PoseEnabledControllerHelper",function(){return Ni}),f.d(y,"PoseEnabledController",function(){return pr}),f.d(y,"ViveController",function(){return hu}),f.d(y,"WebVRController",function(){return Fi}),f.d(y,"WindowsMotionController",function(){return Yo}),f.d(y,"XRWindowsMotionController",function(){return up}),f.d(y,"StickValues",function(){return Ff}),f.d(y,"Gamepad",function(){return hn}),f.d(y,"GenericPad",function(){return El}),f.d(y,"GamepadManager",function(){return Il}),f.d(y,"GamepadSystemSceneComponent",function(){return Dl}),f.d(y,"Xbox360Button",function(){return Rn}),f.d(y,"Xbox360Dpad",function(){return Ji}),f.d(y,"Xbox360Pad",function(){return Ol}),f.d(y,"DualShockButton",function(){return Hn}),f.d(y,"DualShockDpad",function(){return $i}),f.d(y,"DualShockPad",function(){return Ml}),f.d(y,"AxisDragGizmo",function(){return Ko.a}),f.d(y,"AxisScaleGizmo",function(){return io}),f.d(y,"BoundingBoxGizmo",function(){return du}),f.d(y,"Gizmo",function(){return Bn.a}),f.d(y,"GizmoManager",function(){return hp}),f.d(y,"PlaneRotationGizmo",function(){return Qo}),f.d(y,"PositionGizmo",function(){return pu}),f.d(y,"RotationGizmo",function(){return fu}),f.d(y,"ScaleGizmo",function(){return _u}),f.d(y,"LightGizmo",function(){return dp}),f.d(y,"CameraGizmo",function(){return pp}),f.d(y,"PlaneDragGizmo",function(){return qo}),f.d(y,"EnvironmentHelper",function(){return Ls}),f.d(y,"PhotoDome",function(){return xp}),f.d(y,"_forceSceneHelpersToBundle",function(){return g_}),f.d(y,"VideoDome",function(){return v_}),f.d(y,"EngineInstrumentation",function(){return b_}),f.d(y,"SceneInstrumentation",function(){return y_}),f.d(y,"_TimeToken",function(){return ou}),f.d(y,"EffectLayer",function(){return ho}),f.d(y,"EffectLayerSceneComponent",function(){return Du}),f.d(y,"GlowLayer",function(){return oa}),f.d(y,"HighlightLayer",function(){return Gs}),f.d(y,"Layer",function(){return R_}),f.d(y,"LayerSceneComponent",function(){return Nu}),f.d(y,"LensFlare",function(){return wu}),f.d(y,"LensFlareSystem",function(){return zs}),f.d(y,"LensFlareSystemSceneComponent",function(){return Fu}),f.d(y,"Light",function(){return Pi.a}),f.d(y,"ShadowLight",function(){return Zo}),f.d(y,"ShadowGenerator",function(){return kn}),f.d(y,"CascadedShadowGenerator",function(){return js}),f.d(y,"ShadowGeneratorSceneComponent",function(){return ju}),f.d(y,"DirectionalLight",function(){return Os}),f.d(y,"HemisphericLight",function(){return ko.a}),f.d(y,"PointLight",function(){return Hs}),f.d(y,"SpotLight",function(){return Ms}),f.d(y,"DefaultLoadingScreen",function(){return Hu}),f.d(y,"_BabylonLoaderRegistered",function(){return Y_}),f.d(y,"BabylonFileLoaderConfiguration",function(){return ua}),f.d(y,"SceneLoaderAnimationGroupLoadingMode",function(){return Si}),f.d(y,"SceneLoader",function(){return Ut}),f.d(y,"SceneLoaderFlags",function(){return Ai.a}),f.d(y,"BackgroundMaterial",function(){return oo}),f.d(y,"ColorCurves",function(){return Q_.a}),f.d(y,"EffectFallbacks",function(){return Sr.a}),f.d(y,"Effect",function(){return ze.a}),f.d(y,"FresnelParameters",function(){return nh}),f.d(y,"ImageProcessingConfigurationDefines",function(){return vn.b}),f.d(y,"ImageProcessingConfiguration",function(){return vn.a}),f.d(y,"Material",function(){return Ht.a}),f.d(y,"MaterialDefines",function(){return $o.a}),f.d(y,"ThinMaterialHelper",function(){return ih.a}),f.d(y,"MaterialHelper",function(){return et.a}),f.d(y,"MultiMaterial",function(){return ir.a}),f.d(y,"PBRMaterialDefines",function(){return ws}),f.d(y,"PBRBaseMaterial",function(){return pn}),f.d(y,"PBRBaseSimpleMaterial",function(){return Qs}),f.d(y,"PBRMaterial",function(){return co}),f.d(y,"PBRMetallicRoughnessMaterial",function(){return rh}),f.d(y,"PBRSpecularGlossinessMaterial",function(){return oh}),f.d(y,"PushMaterial",function(){return ea.a}),f.d(y,"ShaderMaterial",function(){return ha.a}),f.d(y,"StandardMaterialDefines",function(){return Ft.b}),f.d(y,"StandardMaterial",function(){return Ft.a}),f.d(y,"BaseTexture",function(){return Wn.a}),f.d(y,"ColorGradingTexture",function(){return ah}),f.d(y,"CubeTexture",function(){return oi}),f.d(y,"DynamicTexture",function(){return bi.a}),f.d(y,"EquiRectangularCubeTexture",function(){return sh}),f.d(y,"HDRFiltering",function(){return Ku}),f.d(y,"HDRCubeTexture",function(){return sa}),f.d(y,"HtmlElementTexture",function(){return q_}),f.d(y,"InternalTextureSource",function(){return Ct.b}),f.d(y,"InternalTexture",function(){return Ct.a}),f.d(y,"_DDSTextureLoader",function(){return yu}),f.d(y,"_ENVTextureLoader",function(){return Tu}),f.d(y,"_KTXTextureLoader",function(){return Eu}),f.d(y,"_TGATextureLoader",function(){return ch}),f.d(y,"_BasisTextureLoader",function(){return lh}),f.d(y,"MirrorTexture",function(){return Ds}),f.d(y,"MultiRenderTarget",function(){return qs}),f.d(y,"TexturePacker",function(){return $_}),f.d(y,"TexturePackerFrame",function(){return Zs}),f.d(y,"CustomProceduralTexture",function(){return tm}),f.d(y,"NoiseProceduralTexture",function(){return hh}),f.d(y,"ProceduralTexture",function(){return _o}),f.d(y,"ProceduralTextureSceneComponent",function(){return uh}),f.d(y,"RawCubeTexture",function(){return im}),f.d(y,"RawTexture",function(){return ni}),f.d(y,"RawTexture2DArray",function(){return rm}),f.d(y,"RawTexture3D",function(){return om}),f.d(y,"RefractionTexture",function(){return am}),f.d(y,"RenderTargetTexture",function(){return sn}),f.d(y,"Texture",function(){return we.a}),f.d(y,"VideoTexture",function(){return Iu}),f.d(y,"UniformBuffer",function(){return jl.a}),f.d(y,"MaterialFlags",function(){return ut.a}),f.d(y,"NodeMaterialBlockTargets",function(){return Ce}),f.d(y,"NodeMaterialBlockConnectionPointTypes",function(){return le}),f.d(y,"NodeMaterialBlockConnectionPointMode",function(){return gn}),f.d(y,"NodeMaterialSystemValues",function(){return bt}),f.d(y,"NodeMaterialModes",function(){return Mn}),f.d(y,"NodeMaterialConnectionPointCompatibilityStates",function(){return ci}),f.d(y,"NodeMaterialConnectionPointDirection",function(){return Tn}),f.d(y,"NodeMaterialConnectionPoint",function(){return fa}),f.d(y,"NodeMaterialBlock",function(){return pt}),f.d(y,"NodeMaterialDefines",function(){return bo}),f.d(y,"NodeMaterial",function(){return va}),f.d(y,"VertexOutputBlock",function(){return mo}),f.d(y,"BonesBlock",function(){return mh}),f.d(y,"InstancesBlock",function(){return gh}),f.d(y,"MorphTargetsBlock",function(){return vh}),f.d(y,"LightInformationBlock",function(){return bh}),f.d(y,"FragmentOutputBlock",function(){return Lr}),f.d(y,"ImageProcessingBlock",function(){return yh}),f.d(y,"PerturbNormalBlock",function(){return Th}),f.d(y,"DiscardBlock",function(){return Eh}),f.d(y,"FrontFacingBlock",function(){return Sh}),f.d(y,"DerivativeBlock",function(){return Ah}),f.d(y,"FragCoordBlock",function(){return Ph}),f.d(y,"ScreenSizeBlock",function(){return xh}),f.d(y,"FogBlock",function(){return Ch}),f.d(y,"LightBlock",function(){return Rh}),f.d(y,"TextureBlock",function(){return Oh}),f.d(y,"ReflectionTextureBlock",function(){return Mh}),f.d(y,"CurrentScreenBlock",function(){return $s}),f.d(y,"InputBlock",function(){return At}),f.d(y,"AnimatedInputBlockTypes",function(){return zi}),f.d(y,"MultiplyBlock",function(){return _a}),f.d(y,"AddBlock",function(){return Ih}),f.d(y,"ScaleBlock",function(){return Dh}),f.d(y,"ClampBlock",function(){return Lh}),f.d(y,"CrossBlock",function(){return Nh}),f.d(y,"DotBlock",function(){return wh}),f.d(y,"TransformBlock",function(){return pa}),f.d(y,"RemapBlock",function(){return ic}),f.d(y,"NormalizeBlock",function(){return Fh}),f.d(y,"TrigonometryBlockOperations",function(){return rn}),f.d(y,"TrigonometryBlock",function(){return uc}),f.d(y,"ColorMergerBlock",function(){return Bh}),f.d(y,"VectorMergerBlock",function(){return go}),f.d(y,"ColorSplitterBlock",function(){return lc}),f.d(y,"VectorSplitterBlock",function(){return Uh}),f.d(y,"LerpBlock",function(){return Vh}),f.d(y,"DivideBlock",function(){return kh}),f.d(y,"SubtractBlock",function(){return Gh}),f.d(y,"StepBlock",function(){return zh}),f.d(y,"OneMinusBlock",function(){return fc}),f.d(y,"ViewDirectionBlock",function(){return pc}),f.d(y,"FresnelBlock",function(){return jh}),f.d(y,"MaxBlock",function(){return Hh}),f.d(y,"MinBlock",function(){return Wh}),f.d(y,"DistanceBlock",function(){return Xh}),f.d(y,"LengthBlock",function(){return Yh}),f.d(y,"NegateBlock",function(){return Kh}),f.d(y,"PowBlock",function(){return Qh}),f.d(y,"RandomNumberBlock",function(){return qh}),f.d(y,"ArcTan2Block",function(){return Zh}),f.d(y,"SmoothStepBlock",function(){return Jh}),f.d(y,"ReciprocalBlock",function(){return $h}),f.d(y,"ReplaceColorBlock",function(){return ed}),f.d(y,"PosterizeBlock",function(){return td}),f.d(y,"WaveBlockKind",function(){return rr}),f.d(y,"WaveBlock",function(){return nd}),f.d(y,"GradientBlockColorStep",function(){return ba}),f.d(y,"GradientBlock",function(){return id}),f.d(y,"NLerpBlock",function(){return rd}),f.d(y,"WorleyNoise3DBlock",function(){return od}),f.d(y,"SimplexPerlin3DBlock",function(){return ad}),f.d(y,"NormalBlendBlock",function(){return sd}),f.d(y,"Rotate2dBlock",function(){return cd}),f.d(y,"ReflectBlock",function(){return ld}),f.d(y,"RefractBlock",function(){return ud}),f.d(y,"DesaturateBlock",function(){return hd}),f.d(y,"PBRMetallicRoughnessBlock",function(){return dd}),f.d(y,"SheenBlock",function(){return _c}),f.d(y,"AnisotropyBlock",function(){return mc}),f.d(y,"ReflectionBlock",function(){return gc}),f.d(y,"ClearCoatBlock",function(){return ya}),f.d(y,"RefractionBlock",function(){return vc}),f.d(y,"SubSurfaceBlock",function(){return Ta}),f.d(y,"ParticleTextureBlock",function(){return ec}),f.d(y,"ParticleRampGradientBlock",function(){return tc}),f.d(y,"ParticleBlendMultiplyBlock",function(){return nc}),f.d(y,"ModBlock",function(){return fd}),f.d(y,"NodeMaterialOptimizer",function(){return hm}),f.d(y,"PropertyTypeForEdition",function(){return Lt}),f.d(y,"editableInPropertyPage",function(){return Vt}),f.d(y,"EffectRenderer",function(){return Xu}),f.d(y,"EffectWrapper",function(){return Yu}),f.d(y,"ShadowDepthWrapper",function(){return pm}),f.d(y,"Scalar",function(){return $.a}),f.d(y,"extractMinAndMaxIndexed",function(){return pd.b}),f.d(y,"extractMinAndMax",function(){return pd.a}),f.d(y,"Space",function(){return ye.c}),f.d(y,"Axis",function(){return ye.a}),f.d(y,"Coordinate",function(){return ye.b}),f.d(y,"Color3",function(){return M.a}),f.d(y,"Color4",function(){return M.b}),f.d(y,"TmpColors",function(){return M.c}),f.d(y,"ToGammaSpace",function(){return Gt.b}),f.d(y,"ToLinearSpace",function(){return Gt.c}),f.d(y,"Epsilon",function(){return Gt.a}),f.d(y,"Frustum",function(){return Wl.a}),f.d(y,"Orientation",function(){return Qe.e}),f.d(y,"BezierCurve",function(){return Qe.c}),f.d(y,"Angle",function(){return Qe.a}),f.d(y,"Arc2",function(){return Qe.b}),f.d(y,"Path2",function(){return Qe.f}),f.d(y,"Path3D",function(){return Qe.g}),f.d(y,"Curve3",function(){return Qe.d}),f.d(y,"Plane",function(){return vr.a}),f.d(y,"Size",function(){return oe.a}),f.d(y,"Vector2",function(){return u.d}),f.d(y,"Vector3",function(){return u.e}),f.d(y,"Vector4",function(){return u.f}),f.d(y,"Quaternion",function(){return u.b}),f.d(y,"Matrix",function(){return u.a}),f.d(y,"TmpVectors",function(){return u.c}),f.d(y,"PositionNormalVertex",function(){return Is}),f.d(y,"PositionNormalTextureVertex",function(){return fp}),f.d(y,"Viewport",function(){return Kn.a}),f.d(y,"SphericalHarmonics",function(){return Es}),f.d(y,"SphericalPolynomial",function(){return no}),f.d(y,"AbstractMesh",function(){return Dt.a}),f.d(y,"Buffer",function(){return Oe.a}),f.d(y,"VertexBuffer",function(){return Oe.b}),f.d(y,"DracoCompression",function(){return mm}),f.d(y,"CSG",function(){return bm}),f.d(y,"Geometry",function(){return Ws.a}),f.d(y,"GroundMesh",function(){return jo}),f.d(y,"TrailMesh",function(){return ym}),f.d(y,"InstancedMesh",function(){return Tm.a}),f.d(y,"LinesMesh",function(){return To.b}),f.d(y,"InstancedLinesMesh",function(){return To.a}),f.d(y,"_CreationDataStorage",function(){return De.b}),f.d(y,"_InstancesBatch",function(){return De.c}),f.d(y,"Mesh",function(){return De.a}),f.d(y,"VertexData",function(){return dt.a}),f.d(y,"MeshBuilder",function(){return Am}),f.d(y,"SimplificationSettings",function(){return Pm}),f.d(y,"SimplificationQueue",function(){return yd}),f.d(y,"SimplificationType",function(){return Ao}),f.d(y,"QuadraticErrorSimplification",function(){return Ed}),f.d(y,"SimplicationQueueSceneComponent",function(){return Sd}),f.d(y,"Polygon",function(){return Sm}),f.d(y,"PolygonMeshBuilder",function(){return vd}),f.d(y,"SubMesh",function(){return yo.a}),f.d(y,"MeshLODLevel",function(){return Om.a}),f.d(y,"TransformNode",function(){return Er.a}),f.d(y,"BoxBuilder",function(){return Tr.a}),f.d(y,"TiledBoxBuilder",function(){return gd}),f.d(y,"DiscBuilder",function(){return Ea}),f.d(y,"RibbonBuilder",function(){return Eo.a}),f.d(y,"SphereBuilder",function(){return Un.a}),f.d(y,"HemisphereBuilder",function(){return Jo}),f.d(y,"CylinderBuilder",function(){return fi.a}),f.d(y,"TorusBuilder",function(){return gr}),f.d(y,"TorusKnotBuilder",function(){return Tc}),f.d(y,"LinesBuilder",function(){return cn.a}),f.d(y,"PolygonBuilder",function(){return So}),f.d(y,"ShapeBuilder",function(){return la.a}),f.d(y,"LatheBuilder",function(){return Sc}),f.d(y,"PlaneBuilder",function(){return Rs.a}),f.d(y,"TiledPlaneBuilder",function(){return bd}),f.d(y,"GroundBuilder",function(){return Bi}),f.d(y,"TubeBuilder",function(){return Ac}),f.d(y,"PolyhedronBuilder",function(){return ro}),f.d(y,"IcoSphereBuilder",function(){return Pc}),f.d(y,"DecalBuilder",function(){return xc}),f.d(y,"CapsuleBuilder",function(){return Cc}),f.d(y,"DataBuffer",function(){return cu.a}),f.d(y,"WebGLDataBuffer",function(){return Mm.a}),f.d(y,"MorphTarget",function(){return Qu}),f.d(y,"MorphTargetManager",function(){return ca}),f.d(y,"RecastJSPlugin",function(){return Im}),f.d(y,"RecastJSCrowd",function(){return Ad}),f.d(y,"Node",function(){return Q.a}),f.d(y,"Database",function(){return Pd}),f.d(y,"BaseParticleSystem",function(){return vo}),f.d(y,"BoxParticleEmitter",function(){return Nr}),f.d(y,"ConeParticleEmitter",function(){return rc}),f.d(y,"CylinderParticleEmitter",function(){return ma}),f.d(y,"CylinderDirectedParticleEmitter",function(){return oc}),f.d(y,"HemisphericParticleEmitter",function(){return ac}),f.d(y,"PointParticleEmitter",function(){return sc}),f.d(y,"SphereParticleEmitter",function(){return ga}),f.d(y,"SphereDirectedParticleEmitter",function(){return cc}),f.d(y,"CustomParticleEmitter",function(){return wr}),f.d(y,"MeshParticleEmitter",function(){return ph}),f.d(y,"GPUParticleSystem",function(){return or}),f.d(y,"Particle",function(){return Cd}),f.d(y,"ParticleHelper",function(){return Vm}),f.d(y,"ParticleSystem",function(){return ln}),f.d(y,"ParticleSystemSet",function(){return Sa}),f.d(y,"SolidParticle",function(){return Mc}),f.d(y,"ModelShape",function(){return Ic}),f.d(y,"DepthSortedParticle",function(){return Rd}),f.d(y,"SolidParticleVertex",function(){return Od}),f.d(y,"SolidParticleSystem",function(){return km}),f.d(y,"CloudPoint",function(){return Md}),f.d(y,"PointsGroup",function(){return Aa}),f.d(y,"PointColor",function(){return En}),f.d(y,"PointsCloudSystem",function(){return Gm}),f.d(y,"SubEmitterType",function(){return Fr}),f.d(y,"SubEmitter",function(){return Po}),f.d(y,"PhysicsEngine",function(){return Ir}),f.d(y,"PhysicsEngineSceneComponent",function(){return Id}),f.d(y,"PhysicsHelper",function(){return zm}),f.d(y,"PhysicsRadialExplosionEventOptions",function(){return Ur}),f.d(y,"PhysicsUpdraftEventOptions",function(){return Dc}),f.d(y,"PhysicsVortexEventOptions",function(){return Lc}),f.d(y,"PhysicsRadialImpulseFalloff",function(){return xo}),f.d(y,"PhysicsUpdraftMode",function(){return Br}),f.d(y,"PhysicsImpostor",function(){return xt.a}),f.d(y,"PhysicsJoint",function(){return en.e}),f.d(y,"DistanceJoint",function(){return en.a}),f.d(y,"MotorEnabledJoint",function(){return en.d}),f.d(y,"HingeJoint",function(){return en.c}),f.d(y,"Hinge2Joint",function(){return en.b}),f.d(y,"CannonJSPlugin",function(){return Ks}),f.d(y,"AmmoJSPlugin",function(){return Zu}),f.d(y,"OimoJSPlugin",function(){return qu}),f.d(y,"AnaglyphPostProcess",function(){return ls}),f.d(y,"BlackAndWhitePostProcess",function(){return Ld}),f.d(y,"BloomEffect",function(){return Fc}),f.d(y,"BloomMergePostProcess",function(){return wc}),f.d(y,"BlurPostProcess",function(){return _n}),f.d(y,"ChromaticAberrationPostProcess",function(){return Bc}),f.d(y,"CircleOfConfusionPostProcess",function(){return Uc}),f.d(y,"ColorCorrectionPostProcess",function(){return Nd}),f.d(y,"ConvolutionPostProcess",function(){return wd}),f.d(y,"DepthOfFieldBlurPostProcess",function(){return Pa}),f.d(y,"DepthOfFieldEffectBlurLevel",function(){return ar}),f.d(y,"DepthOfFieldEffect",function(){return Vc}),f.d(y,"DepthOfFieldMergePostProcessOptions",function(){return eg}),f.d(y,"DepthOfFieldMergePostProcess",function(){return Fd}),f.d(y,"DisplayPassPostProcess",function(){return Bd}),f.d(y,"ExtractHighlightsPostProcess",function(){return Nc}),f.d(y,"FilterPostProcess",function(){return Ud}),f.d(y,"FxaaPostProcess",function(){return Co}),f.d(y,"GrainPostProcess",function(){return kc}),f.d(y,"HighlightsPostProcess",function(){return sg}),f.d(y,"ImageProcessingPostProcess",function(){return zo}),f.d(y,"MotionBlurPostProcess",function(){return Gc}),f.d(y,"PassPostProcess",function(){return wi}),f.d(y,"PassCubePostProcess",function(){return zf}),f.d(y,"PostProcess",function(){return _t}),f.d(y,"PostProcessManager",function(){return hs.a}),f.d(y,"RefractionPostProcess",function(){return kd}),f.d(y,"DefaultRenderingPipeline",function(){return jd}),f.d(y,"LensRenderingPipeline",function(){return mg}),f.d(y,"SSAO2RenderingPipeline",function(){return Hd}),f.d(y,"SSAORenderingPipeline",function(){return Tg}),f.d(y,"StandardRenderingPipeline",function(){return Wd}),f.d(y,"PostProcessRenderEffect",function(){return Rt}),f.d(y,"PostProcessRenderPipeline",function(){return Vr}),f.d(y,"PostProcessRenderPipelineManager",function(){return Gd}),f.d(y,"PostProcessRenderPipelineManagerSceneComponent",function(){return zd}),f.d(y,"SharpenPostProcess",function(){return zc}),f.d(y,"StereoscopicInterlacePostProcessI",function(){return xg}),f.d(y,"StereoscopicInterlacePostProcess",function(){return Cg}),f.d(y,"TonemappingOperator",function(){return sr}),f.d(y,"TonemapPostProcess",function(){return Og}),f.d(y,"VolumetricLightScatteringPostProcess",function(){return Xd}),f.d(y,"VRDistortionCorrectionPostProcess",function(){return us}),f.d(y,"VRMultiviewToSingleviewPostProcess",function(){return ds}),f.d(y,"ScreenSpaceReflectionPostProcess",function(){return jc}),f.d(y,"ScreenSpaceCurvaturePostProcess",function(){return Yd}),f.d(y,"ReflectionProbe",function(){return Ju}),f.d(y,"BoundingBoxRenderer",function(){return Kd}),f.d(y,"DepthRenderer",function(){return aa}),f.d(y,"DepthRendererSceneComponent",function(){return Qd}),f.d(y,"EdgesRenderer",function(){return Hc}),f.d(y,"LineEdgesRenderer",function(){return qd}),f.d(y,"GeometryBufferRenderer",function(){return li}),f.d(y,"GeometryBufferRendererSceneComponent",function(){return Vd}),f.d(y,"PrePassRenderer",function(){return Wc}),f.d(y,"PrePassRendererSceneComponent",function(){return Zd}),f.d(y,"SubSurfaceSceneComponent",function(){return $d}),f.d(y,"OutlineRenderer",function(){return ef}),f.d(y,"RenderingGroup",function(){return zg.a}),f.d(y,"RenderingGroupInfo",function(){return $r.a}),f.d(y,"RenderingManager",function(){return $r.b}),f.d(y,"UtilityLayerRenderer",function(){return On.a}),f.d(y,"Scene",function(){return _e.a}),f.d(y,"SceneComponentConstants",function(){return at.a}),f.d(y,"Stage",function(){return at.b}),f.d(y,"Sprite",function(){return tf}),f.d(y,"SpriteManager",function(){return rf}),f.d(y,"SpriteMap",function(){return Kg}),f.d(y,"SpritePackedManager",function(){return Qg}),f.d(y,"SpriteSceneComponent",function(){return nf}),f.d(y,"AlphaState",function(){return qg.a}),f.d(y,"DepthCullingState",function(){return Zg.a}),f.d(y,"StencilState",function(){return Jg.a}),f.d(y,"AndOrNotEvaluator",function(){return $g.a}),f.d(y,"AssetTaskState",function(){return _i}),f.d(y,"AbstractAssetTask",function(){return mi}),f.d(y,"AssetsProgressEvent",function(){return of}),f.d(y,"ContainerAssetTask",function(){return af}),f.d(y,"MeshAssetTask",function(){return sf}),f.d(y,"TextFileAssetTask",function(){return cf}),f.d(y,"BinaryFileAssetTask",function(){return lf}),f.d(y,"ImageAssetTask",function(){return uf}),f.d(y,"TextureAssetTask",function(){return hf}),f.d(y,"CubeTextureAssetTask",function(){return df}),f.d(y,"HDRCubeTextureAssetTask",function(){return ff}),f.d(y,"EquiRectangularCubeTextureAssetTask",function(){return pf}),f.d(y,"AssetsManager",function(){return ev}),f.d(y,"BasisTranscodeConfiguration",function(){return Z_}),f.d(y,"BasisTools",function(){return po}),f.d(y,"DDSTools",function(){return ki}),f.d(y,"expandToProperty",function(){return L.b}),f.d(y,"serialize",function(){return L.c}),f.d(y,"serializeAsTexture",function(){return L.m}),f.d(y,"serializeAsColor3",function(){return L.e}),f.d(y,"serializeAsFresnelParameters",function(){return L.h}),f.d(y,"serializeAsVector2",function(){return L.n}),f.d(y,"serializeAsVector3",function(){return L.o}),f.d(y,"serializeAsMeshReference",function(){return L.k}),f.d(y,"serializeAsColorCurves",function(){return L.g}),f.d(y,"serializeAsColor4",function(){return L.f}),f.d(y,"serializeAsImageProcessingConfiguration",function(){return L.i}),f.d(y,"serializeAsQuaternion",function(){return L.l}),f.d(y,"serializeAsMatrix",function(){return L.j}),f.d(y,"serializeAsCameraReference",function(){return L.d}),f.d(y,"SerializationHelper",function(){return L.a}),f.d(y,"Deferred",function(){return tv}),f.d(y,"EnvironmentTextureTools",function(){return Ei}),f.d(y,"MeshExploder",function(){return nv}),f.d(y,"FilesInput",function(){return iv}),f.d(y,"CubeMapToSphericalPolynomialTools",function(){return Ho}),f.d(y,"HDRTools",function(){return Wu}),f.d(y,"PanoramaToCubeMapTools",function(){return Xs}),f.d(y,"KhronosTextureContainer",function(){return ra}),f.d(y,"EventState",function(){return R.a}),f.d(y,"Observer",function(){return R.d}),f.d(y,"MultiObserver",function(){return R.b}),f.d(y,"Observable",function(){return R.c}),f.d(y,"PerformanceMonitor",function(){return _f.a}),f.d(y,"RollingAverage",function(){return _f.b}),f.d(y,"PromisePolyfill",function(){return rv.a}),f.d(y,"SceneOptimization",function(){return gi}),f.d(y,"TextureOptimization",function(){return xa}),f.d(y,"HardwareScalingOptimization",function(){return Yc}),f.d(y,"ShadowsOptimization",function(){return Ca}),f.d(y,"PostProcessesOptimization",function(){return Ra}),f.d(y,"LensFlaresOptimization",function(){return Oa}),f.d(y,"CustomOptimization",function(){return mf}),f.d(y,"ParticlesOptimization",function(){return Ma}),f.d(y,"RenderTargetsOptimization",function(){return Kc}),f.d(y,"MergeMeshesOptimization",function(){return Ia}),f.d(y,"SceneOptimizerOptions",function(){return Qc}),f.d(y,"SceneOptimizer",function(){return ov}),f.d(y,"SceneSerializer",function(){return Zc}),f.d(y,"SmartArray",function(){return di.a}),f.d(y,"SmartArrayNoDuplicate",function(){return di.b}),f.d(y,"StringDictionary",function(){return Al.a}),f.d(y,"Tags",function(){return av.a}),f.d(y,"TextureTools",function(){return sv}),f.d(y,"TGATools",function(){return da}),f.d(y,"Tools",function(){return Xe.b}),f.d(y,"className",function(){return Xe.c}),f.d(y,"AsyncLoop",function(){return Xe.a}),f.d(y,"VideoRecorder",function(){return cv}),f.d(y,"JoystickAxis",function(){return an}),f.d(y,"VirtualJoystick",function(){return os}),f.d(y,"WorkerPool",function(){return Bs}),f.d(y,"Logger",function(){return l.a}),f.d(y,"_TypeStore",function(){return C.a}),f.d(y,"FilesInputStore",function(){return As.a}),f.d(y,"DeepCopier",function(){return de.a}),f.d(y,"PivotTools",function(){return jn.a}),f.d(y,"PrecisionDate",function(){return be.a}),f.d(y,"ScreenshotTools",function(){return Ro}),f.d(y,"WebRequest",function(){return re.a}),f.d(y,"InspectableType",function(){return Xc}),f.d(y,"BRDFTextureTools",function(){return ta}),f.d(y,"RGBDTextureTools",function(){return mu}),f.d(y,"ColorGradient",function(){return Rc}),f.d(y,"Color3Gradient",function(){return xd}),f.d(y,"FactorGradient",function(){return Oc}),f.d(y,"GradientHelper",function(){return In}),f.d(y,"PerfCounter",function(){return Xn.a}),f.d(y,"RetryStrategy",function(){return lv.a}),f.d(y,"CanvasGenerator",function(){return fs.a}),f.d(y,"LoadFileError",function(){return to.b}),f.d(y,"RequestFileError",function(){return to.d}),f.d(y,"ReadFileError",function(){return to.c}),f.d(y,"FileTools",function(){return to.a}),f.d(y,"StringTools",function(){return Qn.a}),f.d(y,"DataReader",function(){return uv}),f.d(y,"MinMaxReducer",function(){return Vu}),f.d(y,"DepthReducer",function(){return ku}),f.d(y,"DataStorage",function(){return hv}),f.d(y,"SceneRecorder",function(){return dv}),f.d(y,"KhronosTextureContainer2",function(){return Us}),f.d(y,"Trajectory",function(){return fv}),f.d(y,"TrajectoryClassifier",function(){return pv}),f.d(y,"TimerState",function(){return Gi}),f.d(y,"setAndStartTimer",function(){return ks}),f.d(y,"AdvancedTimer",function(){return __}),f.d(y,"CopyTools",function(){return _v.a}),f.d(y,"WebXRCamera",function(){return Su}),f.d(y,"WebXREnterExitUIButton",function(){return Ru}),f.d(y,"WebXREnterExitUIOptions",function(){return p_}),f.d(y,"WebXREnterExitUI",function(){return Ou}),f.d(y,"WebXRExperienceHelper",function(){return Au}),f.d(y,"WebXRInput",function(){return Cu}),f.d(y,"WebXRInputSource",function(){return xu}),f.d(y,"WebXRManagedOutputCanvasOptions",function(){return ps}),f.d(y,"WebXRManagedOutputCanvas",function(){return Kl}),f.d(y,"WebXRState",function(){return fn}),f.d(y,"WebXRTrackingState",function(){return er}),f.d(y,"WebXRSessionManager",function(){return _s}),f.d(y,"WebXRDefaultExperienceOptions",function(){return m_}),f.d(y,"WebXRDefaultExperience",function(){return Mu}),f.d(y,"WebXRFeatureName",function(){return ai}),f.d(y,"WebXRFeaturesManager",function(){return qn}),f.d(y,"WebXRAbstractFeature",function(){return si}),f.d(y,"WebXRHitTestLegacy",function(){return La}),f.d(y,"WebXRAnchorSystem",function(){return Na}),f.d(y,"WebXRPlaneDetector",function(){return wa}),f.d(y,"WebXRBackgroundRemover",function(){return Fa}),f.d(y,"WebXRMotionControllerTeleportation",function(){return uo}),f.d(y,"WebXRControllerPointerSelection",function(){return lo}),f.d(y,"IWebXRControllerPhysicsOptions",function(){return vv}),f.d(y,"WebXRControllerPhysics",function(){return Ba}),f.d(y,"WebXRHitTest",function(){return Ua}),f.d(y,"WebXRFeaturePointSystem",function(){return Va}),f.d(y,"WebXRHand",function(){return yf}),f.d(y,"WebXRHandTracking",function(){return ka}),f.d(y,"WebXRAbstractMotionController",function(){return Rr}),f.d(y,"WebXRControllerComponent",function(){return Cr}),f.d(y,"WebXRGenericTriggerMotionController",function(){return Vs}),f.d(y,"WebXRMicrosoftMixedRealityController",function(){return Tf}),f.d(y,"WebXRMotionControllerManager",function(){return Vn}),f.d(y,"WebXROculusTouchMotionController",function(){return $c}),f.d(y,"WebXRHTCViveMotionController",function(){return Ef}),f.d(y,"WebXRProfiledMotionController",function(){return Pu});var U=f(35),_=f(91),R=f(6),u=f(0),M=f(9),C=f(11),P=function(){function r(t,e){this.triggerOptions=t,this.onBeforeExecuteObservable=new R.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}();C.a.RegisteredTypes["BABYLON.Action"]=P;var m=f(47),c=f(1),T=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,Re=0;Re0){var x=b.properties[0].value,O=b.properties[0].targetType===null?x:i.getMeshByName(x);O._meshId&&(O.mesh=i.getMeshByID(O._meshId)),p={trigger:t[b.name],parameter:O}}else p=t[b.name];for(var B=0;B=0?e:0;var s=0,d=a._keys[0],p=a._keys.length-1,b=a._keys[p],x={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,B=d.frame,F=b.frame;if(n){var z=a.getRange(n);z&&(B=z.from,F=z.to)}var J=d.frame===B,ie=b.frame===F;if(a._keys.length===1){var se=a._getKeyValue(a._keys[0]);x.referenceValue=se.clone?se.clone():se,O=!0}else e<=d.frame?(se=a._getKeyValue(d.value),x.referenceValue=se.clone?se.clone():se,O=!0):e>=b.frame&&(se=a._getKeyValue(b.value),x.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)}x.referenceValue=se.clone?se.clone():se,O=!0}if(!J&&B>=ue.frame&&B<=fe.frame){if(B===ue.frame)s=ce;else if(B===fe.frame)s=ce+1;else{ve={key:ce,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};var Te={frame:B,value:(se=a._interpolate(B,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?x.referenceValue.normalize().conjugateInPlace():a.dataType===r.ANIMATIONTYPE_MATRIX&&(x.referenceValue.decompose(x.referenceScaling,x.referenceQuaternion,x.referencePosition),x.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(x.keyScaling,x.keyQuaternion,x.keyPosition),x.keyPosition.subtractInPlace(x.referencePosition),x.keyScaling.divideInPlace(x.referenceScaling),x.referenceQuaternion.multiplyToRef(x.keyQuaternion,x.keyQuaternion),u.a.ComposeToRef(x.keyScaling,x.keyQuaternion,x.keyPosition,Te.value);break;case r.ANIMATIONTYPE_QUATERNION:x.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(x.referenceValue,Te.value);break;case r.ANIMATIONTYPE_SIZE:Te.value.width-=x.referenceValue.width,Te.value.height-=x.referenceValue.height;break;default:Te.value-=x.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 b=i.beginAnimation(n,0,p,!1);return b.onAnimationEnd=d,b},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),b=s.outTangent!==void 0&&a.inTangent!==void 0,x=a.frame-s.frame,O=(t-s.frame)/x,B=this.getEasingFunction();switch(B!=null&&(O=B.ease(O)),this.dataType){case r.ANIMATIONTYPE_FLOAT:var F=b?this.floatInterpolateFunctionWithTangents(d,s.outTangent*x,p,a.inTangent*x,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=b?this.quaternionInterpolateFunctionWithTangents(d,s.outTangent.scale(x),p,a.inTangent.scale(x),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=b?this.vector3InterpolateFunctionWithTangents(d,s.outTangent.scale(x),p,a.inTangent.scale(x),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=b?this.vector2InterpolateFunctionWithTangents(d,s.outTangent.scale(x),p,a.inTangent.scale(x),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 b=u.b.FromArray(p.values.slice(4,8));b.equals(u.b.Zero())||(s=b)}if(p.values.length>=12){var x=u.b.FromArray(p.values.slice(8,12));x.equals(u.b.Zero())||(d=x)}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&&x.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 b,x,O=n-e,B=t*(s.framePerSecond*o)/1e3+this._ratioOffset,F=0;if(this._previousDelay=t,this._previousRatio=B,!i&&n>=e&&B>=O)p=!1,F=s._getKeyValue(this._maxValue);else if(!i&&e>=n&&B<=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],b=this._offsetsCache[z]}if(b===void 0)switch(s.dataType){case k.ANIMATIONTYPE_FLOAT:b=0;break;case k.ANIMATIONTYPE_QUATERNION:b=Z;break;case k.ANIMATIONTYPE_VECTOR3:b=W;break;case k.ANIMATIONTYPE_VECTOR2:b=q;break;case k.ANIMATIONTYPE_SIZE:b=he;break;case k.ANIMATIONTYPE_COLOR3:b=ge}if(this._host&&this._host.syncRoot){var se=this._host.syncRoot;x=e+(n-e)*((se.masterFrame-se.fromFrame)/(se.toFrame-se.fromFrame))}else x=p&&O!==0?e+B%O:n;var ce=this._events;if((O>0&&this.currentFrame>x||O<0&&this.currentFrame>0,this._animationState.highLimitValue=F,this._animationState.offsetValue=b;var fe=s._interpolate(x,this._animationState);if(this.setValue(fe,a),ce.length){for(ue=0;ue0&&x>=ce[ue].frame&&ce[ue].frame>=e||O<0&&x<=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(x))}}return p||(this._stopped=!0),p},r}(),_e=f(20),be=f(57),Pe=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 ke(this,r,t,e,n,i,o,void 0,p,b));var x=!d||d(r);if(r.animations&&x&&a.appendAnimations(r,r.animations),r.getAnimatables)for(var O=r.getAnimatables(),B=0;Bn&&o>0&&(o*=-1),new ke(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 b=r.getDescendants(t),x=[];x.push(this.beginDirectAnimation(r,e,n,i,o,a,s,d,p));for(var O=0,B=b;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<=b&&(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,b+e),!0};var We=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}(),je=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 R.c,this.onAnimationLoopObservable=new R.c,this.onAnimationGroupLoopObservable=new R.c,this.onAnimationGroupEndObservable=new R.c,this.onAnimationGroupPauseObservable=new R.c,this.onAnimationGroupPlayObservable=new R.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}(),nt=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}(Ge),$e=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}(Ge),ct=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),b=Math.floor(p),x=b+1,O=(1-Math.pow(i,b))/(a*s),B=.5*(O+(1-Math.pow(i,x))/(a*s)),F=e-B,z=B-O;return-Math.pow(1/i,n-b)/(z*z)*(F-z)*(F+z)},t}(Ge),st=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}(Ge),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}(Ge),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}(Ge),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}(Ge),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}(Ge),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}(Ge),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}(Ge),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}(Ge),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 Qe.c.Interpolate(e,this.x1,this.y1,this.x2,this.y2)},t}(Ge),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),Pn=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return Object(c.d)(t,r),t}(U.a),nn=function(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]},xn=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=[],b={doNotInstantiate:!0},x=function(O,B){if(o[O.uniqueId]=B.uniqueId,a[B.uniqueId]=B,e&&(B.name=e(O.name)),B instanceof De.a){var F=B;if(F.morphTargetManager){var z=O.morphTargetManager;F.morphTargetManager=z.clone();for(var J=0;J-1&&d.animations.splice(J,1)}},b=0,x=s.animations;b0&&(B=!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 b=u.e.FromArray(t.position);s.setPosition(b)}if(t.isDirectional&&(s.setDirectionalCone(t.coneInnerAngle||360,t.coneOuterAngle||360,t.coneOuterGain||0),t.localDirectionToMesh)){var x=u.e.FromArray(t.localDirectionToMesh);s.setLocalDirectionToMesh(x)}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 An.a.WarnImport("AudioSceneComponent")},r}(),No=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}(),ml=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 $e(.3),r.EasingMode=Ge.EASINGMODE_EASEOUT,r}(),gl=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=Ge.EASINGMODE_EASEINOUT,r.IgnoreBoundsSizeMode=0,r.FitFrustumSidesMode=1,r}(),fr=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},If=function(){function r(t){this.ui=t,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new fr(u.e.Up()),new fr(u.e.Down()),new fr(u.e.Left()),new fr(u.e.Right()),new fr(u.e.Forward()),new fr(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}(),vi=f(65),Lf=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 vi.a({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new vi.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),jn=f(60),vl=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 R.c,this.onDragObservable=new R.c,this.onDragEndObservable=new R.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,jn.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),jn.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 b=a.pickInfo.ray.origin.subtract(i);i.copyFrom(a.pickInfo.ray.origin);var x=-u.e.Dot(b,a.pickInfo.ray.direction);e._virtualOriginMesh.addChild(e._virtualDragMesh),e._virtualDragMesh.position.z-=e._virtualDragMesh.position.z<1?x*e.zDragFactor:x*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(jn.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))}jn.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}(),Nf=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],b=r._tmpVecs[4],x=r._tmpQuat;t.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,b),b.x==0&&b.y==0&&b.z==0?b.y=1:b.normalize(),e.subtractToRef(a,p),p.normalize(),u.e.CrossToRef(p,b,s),s.normalize(),u.e.CrossToRef(p,s,d),d.normalize(),u.a.FromXYZAxesToRef(d,p,s,i);var O=this._bone1Length,B=this._bone2Length,F=u.e.Distance(a,e);this._maxReach>0&&(F=Math.min(this._maxReach,F));var z=(B*B+F*F-O*O)/(2*B*F),J=(F*F+O*O-B*B)/(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,x),u.b.SlerpToRef(this._bone1Quat,x,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}(),wf=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,b=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(p=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(b=!0),p||b){var x=r._tmpMats[2],O=r._tmpMats[3];if(this.upAxisSpace==ye.c.BONE&&d.y==1&&s)s.getRotationMatrixToRef(ye.c.WORLD,this.mesh,x);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 B=u.e.Cross(d,F);B.normalize();var F=u.e.Cross(B,d);u.a.FromXYZAxesToRef(B,d,F,x)}else x.copyFrom(a.getWorldMatrix());x.invertToRef(O);var z=null;if(b){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 Re=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>Re,Ee=0;Ee<6;Ee++){var Se=Te[Re][Ee];ve&&(Se=bl(Se,Ae,Ae,i)),B.texImage2D(Ee,Re,fe,Ae,Ae,0,ue,ce,Se)}O._bindTextureDirectly(B.TEXTURE_CUBE_MAP,null)}else O.updateRawCubeTexture(F,se,n,i,x);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=yl(!1),Bt.a.prototype.createRawTexture3D=yl(!0),Bt.a.prototype.updateRawTexture2DArray=Tl(!1),Bt.a.prototype.updateRawTexture3D=Tl(!0);var ni=function(r){function t(e,n,i,o,a,s,d,p,b){s===void 0&&(s=!0),d===void 0&&(d=!1),p===void 0&&(p=h.a.TEXTURE_TRILINEAR_SAMPLINGMODE),b===void 0&&(b=h.a.TEXTURETYPE_UNSIGNED_INT);var x=r.call(this,null,a,!s,d)||this;return x.format=o,x._engine&&(x._texture=x._engine.createRawTexture(e,n,i,o,s,d,p,null,b),x.wrapU=we.a.CLAMP_ADDRESSMODE,x.wrapV=we.a.CLAMP_ADDRESSMODE),x}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),wo=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 R.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 b={};b.name=d,b.from=p.from,b.to=p.to,n.ranges.push(b)}}}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}(),El=function(r){function t(e,n,i){var o=r.call(this,e,n,i)||this;return o.onButtonDownObservable=new R.c,o.onButtonUpObservable=new R.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=ja;var qi=f(66),Ha=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=Xe.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=Xe.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,b=e.camera.inertialRadiusOffset+a,x=0;x<20&&Math.abs(b)>.001;x++)p-=b,b*=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=Wa;var Sl=function(){function r(){this.buttons=[0,1,2]}return r.prototype.attachControl=function(t){var e=this;t=Xe.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 b=d.event,x=b.pointerType==="touch";if(!n.isInVRExclusivePointerMode&&(d.type===Tt.a.POINTERMOVE||e.buttons.indexOf(b.button)!==-1)){var O=b.srcElement||b.target;if(e._altKey=b.altKey,e._ctrlKey=b.ctrlKey,e._metaKey=b.metaKey,e._shiftKey=b.shiftKey,e._buttonsPressed=b.buttons,n.isPointerLock){var B=b.movementX||b.mozMovementX||b.webkitMovementX||b.msMovementX||0,F=b.movementY||b.mozMovementY||b.webkitMovementY||b.msMovementY||0;e.onTouch(null,B,F),e.pointA=null,e.pointB=null}else if(d.type===Tt.a.POINTERDOWN&&O){try{O.setPointerCapture(b.pointerId)}catch{}e.pointA===null?e.pointA={x:b.clientX,y:b.clientY,pointerId:b.pointerId,type:b.pointerType}:e.pointB===null&&(e.pointB={x:b.clientX,y:b.clientY,pointerId:b.pointerId,type:b.pointerType}),e.onButtonDown(b),t||(b.preventDefault(),i&&i.focus())}else if(d.type===Tt.a.POINTERDOUBLETAP)e.onDoubleTap(b.pointerType);else if(d.type===Tt.a.POINTERUP&&O){try{O.releasePointerCapture(b.pointerId)}catch{}x||(e.pointB=null),n._badOS?e.pointA=e.pointB=null:e.pointB&&e.pointA&&e.pointA.pointerId==b.pointerId?(e.pointA=e.pointB,e.pointB=null):e.pointA&&e.pointB&&e.pointB.pointerId==b.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(b),t||b.preventDefault()}else if(d.type===Tt.a.POINTERMOVE){if(t||b.preventDefault(),e.pointA&&e.pointB===null)B=b.clientX-e.pointA.x,F=b.clientY-e.pointA.y,e.onTouch(e.pointA,B,F),e.pointA.x=b.clientX,e.pointA.y=b.clientY;else if(e.pointA&&e.pointB){var z=e.pointA.pointerId===b.pointerId?e.pointA:e.pointB;z.x=b.clientX,z.y=b.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:b.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&&Xe.b.RegisterTopRootEvents(s,[{name:"blur",handler:this._onLostFocus}])},r.prototype.detachControl=function(t){if(this._onLostFocus){var e=this.camera.getScene().getEngine().getHostWindow();e&&Xe.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}(),Xa=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,b=s.y-a.y;this.camera.inertialPanningX+=-p/this.panningSensibility,this.camera.inertialPanningY+=b/this.panningSensibility}}else{this._twoFingerActivityCount++;var x=Math.sqrt(i),O=Math.sqrt(o);this._isPinching||this._twoFingerActivityCount<20&&Math.abs(O-x)>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,b=s.y-a.y,this.camera.inertialPanningX+=-p/this.panningSensibility,this.camera.inertialPanningY+=b/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}(Sl);un.ArcRotateCameraPointersInput=Xa;var Fo=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 Wa),this},t.prototype.addPointers=function(){return this.add(new Xa),this},t.prototype.addKeyboard=function(){return this.add(new Ha),this},t}(Zr);Fo.prototype.addVRDeviceOrientation=function(){return this.add(new Ya),this};var Ya=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=Xe.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):Xe.b.Warn("Permission not granted.")}).catch(function(i){Xe.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=Ya;var Ka=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=Xe.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=qa;var Za=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=Xe.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=Za;var Ja=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}(Sl);un.FollowCameraPointersInput=Ja;var $a=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=Xe.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=ns;var Jr=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 $a),this},t.prototype.addMouse=function(e){return e===void 0&&(e=!0),this._mouseInput||(this._mouseInput=new es(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 ts,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 ns),this},t.prototype.clear=function(){r.prototype.clear.call(this),this._mouseInput=null},t}(Zr);Jr.prototype.addDeviceOrientation=function(){return this._deviceOrientationInput||(this._deviceOrientationInput=new is,this.add(this._deviceOrientationInput)),this};var is=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 R.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=-Xe.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):Xe.b.Warn("Permission not granted.")}).catch(function(a){Xe.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():Xe.b.Warn("Permission not granted.")}).catch(function(i){Xe.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(Xe.b.ToRadians(this._alpha),Xe.b.ToRadians(this._beta),-Xe.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=is;var rs=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=rs;var an,Al=f(112);(function(r){r[r.X=0]="X",r[r.Y=1]="Y",r[r.Z=2]="Z"})(an||(an={}));var os=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 Al.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 Jr(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=Xe.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}(Li);Q.a.AddNodeConstructor("TouchCamera",function(r,t){return function(){return new ss(r,u.e.Zero(),t)}});var ss=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}(Yn);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 R.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(b,x,O){O===void 0&&(O=null),O?(p.setPosition(x),p.onCollide&&p.onCollide(O)):p._previousPosition.copyFrom(p._position);var B=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*B*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 Fo(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 ml,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 gl,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 _l,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=Xe.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}(Li);Q.a.AddNodeConstructor("DeviceOrientationCamera",function(r,t){return function(){return new Bo(r,u.e.Zero(),t)}});var Bo=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}(Yn),Pl=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 Ka),this},t.prototype.addMouse=function(e){return e===void 0&&(e=!0),this.add(new Qa(e)),this},t}(Zr),Uf=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 b;b=d,a._newPosition.copyFrom(b),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 Pl(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=Xe.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}(Li),xl=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 qa),this},t.prototype.addMouseWheel=function(){return this.add(new Za),this},t.prototype.addPointers=function(){return this.add(new Ja),this},t.prototype.addVRDeviceOrientation=function(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this},t}(Zr);Q.a.AddNodeConstructor("FollowCamera",function(r,t){return function(){return new Cl(r,u.e.Zero(),t)}}),Q.a.AddNodeConstructor("ArcFollowCamera",function(r,t){return function(){return new Rl(r,0,0,1,null,t)}});var ii,Cl=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 xl(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=Xe.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,b=a.y+this.heightOffset-this.position.y,x=d-this.position.z,O=p*this.cameraAcceleration*2,B=b*this.cameraAcceleration,F=x*this.cameraAcceleration*2;(O>this.maxCameraSpeed||O<-this.maxCameraSpeed)&&(O=O<1?-this.maxCameraSpeed:this.maxCameraSpeed),(B>this.maxCameraSpeed||B<-this.maxCameraSpeed)&&(B=B<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+B,this.position.z+F),this.setTarget(a)}},t.prototype.attachControl=function(e,n){n=Xe.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}(Li),Rl=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}(Li),cs=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"})(ii||(ii={}));var Rn,Ji,Ni=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"})(Rn||(Rn={})),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 Hn,$i,Ol=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 R.c,a.onButtonUpObservable=new R.c,a.onPadDownObservable=new R.c,a.onPadUpObservable=new R.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,Rn.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,Rn.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,Rn.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,Rn.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,Rn.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,Rn.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,Rn.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,Rn.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,Rn.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,Rn.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"})(Hn||(Hn={})),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 Ml=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 R.c,o.onButtonUpObservable=new R.c,o.onPadDownObservable=new R.c,o.onPadUpObservable=new R.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,Hn.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,Hn.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,Hn.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,Hn.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,Hn.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,Hn.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,Hn.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,Hn.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,Hn.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,Hn.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),Il=function(){function r(t){var e=this;if(this._scene=t,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new R.c,cs.a.IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator.getGamepads||navigator.webkitGetGamepads||navigator.msGetGamepads||navigator.webkitGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new R.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,b,x,O,B,F,z){s===void 0&&(s=h.a.TEXTURE_NEAREST_SAMPLINGMODE),b===void 0&&(b=null),x===void 0&&(x=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 di.a(2),this._currentRenderTextureInd=0,this._scaleRatio=new u.d(1,1),this._texelSize=u.d.Zero(),this.onActivateObservable=new R.c,this.onSizeChangedObservable=new R.c,this.onApplyObservable=new R.c,this.onBeforeRenderObservable=new R.c,this.onAfterRenderObservable=new R.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=x,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=B,F||this.updateEffect(b)}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 di.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,b=t.parent;!b||b.leftCamera!=t&&b.rightCamera!=t||(d/=2);var x,O=this._options.width||d,B=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,B*=z.height)}if((F||this.alwaysForcePOT)&&(this._options.width||(O=a.needPOTTextures?Ue.a.GetExponentOfTwo(O,s,this.scaleMode):O),this._options.height||(B=a.needPOTTextures?Ue.a.GetExponentOfTwo(B,s,this.scaleMode):B)),this.width!==O||this.height!==B){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=C.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}();C.a.RegisteredTypes["BABYLON.PostProcess"]=_t;var kf=` -varying vec2 vUV; -uniform sampler2D textureSampler; -void main(void) -{ -gl_FragColor=texture2D(textureSampler,vUV); -}`;ze.a.ShadersStore.passPixelShader=kf;var Gf=` -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 -}`;ze.a.ShadersStore.passCubePixelShader=Gf;var wi=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);C.a.RegisteredTypes["BABYLON.PassPostProcess"]=wi;var zf=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 b=r.call(this,e,"passCube",null,null,n,i,o,a,s,"#define POSITIVEX",d,void 0,null,p)||this;return b._face=0,b}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 wi("rescale",1,null,h.a.TEXTURE_BILINEAR_SAMPLINGMODE,r,!1,h.a.TEXTURETYPE_UNSIGNED_INT)};var jf=` -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); -}`;ze.a.ShadersStore.anaglyphPixelShader=jf;var ls=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);C.a.RegisteredTypes["BABYLON.AnaglyphPostProcess"]=ls,gt.a._setStereoscopicAnaglyphRigMode=function(r){r._rigCameras[0]._rigPostProcess=new wi(r.name+"_passthru",1,r._rigCameras[0]),r._rigCameras[1]._rigPostProcess=new ls(r.name+"_anaglyph",1,r._rigCameras)},Q.a.AddNodeConstructor("AnaglyphArcRotateCamera",function(r,t,e){return function(){return new Nl(r,0,0,1,u.e.Zero(),e.interaxial_distance,t)}});var Nl=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 wl(r,u.e.Zero(),e.interaxial_distance,t)}});var wl=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}(Yn);Q.a.AddNodeConstructor("AnaglyphGamepadCamera",function(r,t,e){return function(){return new Fl(r,u.e.Zero(),e.interaxial_distance,t)}});var Fl=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}(Uo);Q.a.AddNodeConstructor("AnaglyphUniversalCamera",function(r,t,e){return function(){return new Bl(r,u.e.Zero(),e.interaxial_distance,t)}});var Bl=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}(_r),Kn=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 Kn.a(0,0,t?.5:1,t?1:.5),r._rigCameras[e?0:1].viewport=new Kn.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 Ul(r,0,0,1,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Ul=function(r){function t(e,n,i,o,a,s,d,p){var b=r.call(this,e,n,i,o,a,p)||this;return b.interaxialDistance=s,b.isStereoscopicSideBySide=d,b.setCameraRigMode(d?gt.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:gt.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:s}),b}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 Vl(r,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Vl=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}(Yn);Q.a.AddNodeConstructor("StereoscopicGamepadCamera",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"StereoscopicGamepadCamera"},t}(Uo);Q.a.AddNodeConstructor("StereoscopicFreeCamera",function(r,t,e){return function(){return new Gl(r,u.e.Zero(),e.interaxial_distance,e.isStereoscopicSideBySide,t)}});var Gl=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}(_r);Q.a.AddNodeConstructor("VirtualJoysticksCamera",function(r,t){return function(){return new zl(r,u.e.Zero(),t)}});var zl=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}(Yn),mr=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}(),Hf=` -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); -} -}`;ze.a.ShadersStore.vrDistortionCorrectionPixelShader=Hf;var us=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),Wf=`precision mediump sampler2DArray; -varying vec2 vUV; -uniform sampler2DArray multiviewSampler; -uniform int imageIndex; -void main(void) -{ -gl_FragColor=texture(multiviewSampler,vec3(vUV,imageIndex)); -}`;ze.a.ShadersStore.vrMultiviewToSingleviewPixelShader=Wf;var jl=f(85),hs=f(95),$r=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 Ct.a(this,Ct.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,b,x,O,B,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),b===void 0&&(b=!0),x===void 0&&(x=!1),O===void 0&&(O=!1),B===void 0&&(B=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 R.c,z.onAfterUnbindObservable=new R.c,z.onBeforeRenderObservable=new R.c,z.onAfterRenderObservable=new R.c,z.onClearObservable=new R.c,z.onResizeObservable=new R.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 $r.b(i),z._renderingManager._useSceneAutoClearSetup=!0,O||(z._renderTargetOptions={generateMipMaps:o,type:s,format:B,samplingMode:p,generateDepthBuffer:b,generateStencilBuffer:x},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,b=this.renderList?this.renderList:s.getActiveMeshes().data,x=this.renderList?this.renderList.length:s.getActiveMeshes().length;this.getCustomRenderList&&(p=this.getCustomRenderList(this.is2DArray?o:e,b,x)),p?this._prepareRenderingManager(p,p.length,a,!1):(this._defaultRenderListPrepared||(this._prepareRenderingManager(b,x,a,!this.renderList),this._defaultRenderListPrepared=!0),p=b),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,B=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 Hl=function(r){function t(e,n){n===void 0&&(n=512);var i=r.call(this,"multiview rtt",n,e,!1,!0,Ct.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),Wl=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 Ct.a(this,Ct.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 Hl(this.getScene(),{width:r,height:t})):this._multiviewTexture=new Hl(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 jl.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]),Wl.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}(Yn),Fi=function(r){function t(e){var n=r.call(this,e)||this;return n.onTriggerStateChangedObservable=new R.c,n.onMainButtonStateChangedObservable=new R.c,n.onSecondaryButtonStateChangedObservable=new R.c,n.onPadStateChangedObservable=new R.c,n.onPadValuesChangedObservable=new R.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; -}`);ze.a.ShadersStore.imageProcessingPixelShader=Xf;var zo=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 b=r.call(this,e,"imageProcessing",[],[],n,i,o,a,s,null,d,"postprocess",null,!0)||this;return b._fromLinearSpace=!0,b._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,b._attachImageProcessingConfiguration(p,!0),b.fromLinearSpace=!1):(b._attachImageProcessingConfiguration(null,!0),b.imageProcessingConfiguration.applyByPostProcess=!0),b.onApply=function(x){b.imageProcessingConfiguration.bind(x,b.aspectRatio)},b}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),dt=f(16),Oe=f(4);De.a._GroundMeshParser=function(r,t){return jo.Parse(r,t)};var jo=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 b=r.maxHeight;r.maxHeight=r.minHeight,r.minHeight=b}for(t=0;t<=r.subdivisions;t++)for(e=0;e<=r.subdivisions;e++){var x=new u.e(e*r.width/r.subdivisions-r.width/2,0,(r.subdivisions-t)*r.height/r.subdivisions-r.height/2),O=4*(((x.x+r.width/2)/r.width*(r.bufferWidth-1)|0)+((1-(x.z+r.height/2)/r.height)*(r.bufferHeight-1)|0)*r.bufferWidth),B=r.buffer[O]/255,F=r.buffer[O+1]/255,z=r.buffer[O+2]/255,J=r.buffer[O+3]/255;p&&(B=1-B,F=1-F,z=1-z);var ie=B*s.r+F*s.g+z*s.b;x.y=J>=d?r.minHeight+(r.maxHeight-r.minHeight)*ie:r.minHeight-Gt.a,i.push(x.x,x.y,x.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,Re=i[3*ue+1]>=r.minHeight;ve&&Te&&Re&&(n.push(se),n.push(ce),n.push(ue)),i[3*fe+1]>=r.minHeight&&ve&&Re&&(n.push(fe),n.push(se),n.push(ue))}dt.a.ComputeNormals(i,n,o);var Ae=new dt.a;return Ae.indices=n,Ae.positions=i,Ae.normals=o,Ae.uvs=a,Ae},De.a.CreateGround=function(r,t,e,n,i,o){var a={width:t,height:e,subdivisions:n,updatable:o};return Bi.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 Bi.CreateTiledGround(r,p,s)},De.a.CreateGroundFromHeightMap=function(r,t,e,n,i,o,a,s,d,p,b){var x={width:e,height:n,subdivisions:i,minHeight:o,maxHeight:a,updatable:d,onReady:p,alphaFilter:b};return Bi.CreateGroundFromHeightMap(r,t,x,s)};var Bi=function(){function r(){}return r.CreateGround=function(t,e,n){var i=new jo(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,dt.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 dt.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,b=n.colorFilter||new M.a(.3,.59,.11),x=n.alphaFilter||0,O=n.updatable,B=n.onReady;i=i||te.a.LastCreatedScene;var F=new jo(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),Xe.b.LoadImage(e,function(z){var J=z.width,ie=z.height,se=fs.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;dt.a.CreateGroundFromHeightMap({width:o,height:a,subdivisions:s,minHeight:d,maxHeight:p,colorFilter:b,buffer:ce,bufferWidth:J,bufferHeight:ie,alphaFilter:x}).applyToMesh(F,O),B&&B(F),F._setReady(!0)}},function(){},i.offlineProvider),F},r}();dt.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||dt.a.DEFAULTSIDE,p=s+1,b=0;b<=s;b++)for(var x=b/s,O=b*Math.PI*2/s-Math.PI/2,B=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(x,z);ue=u.e.TransformCoordinates(ue,B),ce=u.e.TransformNormal(ce,B),e.push(ue.x,ue.y,ue.z),n.push(ce.x,ce.y,ce.z),i.push(fe.x,fe.y);var ve=(b+1)%p,Te=(F+1)%p;t.push(b*p+F),t.push(b*p+Te),t.push(ve*p+F),t.push(b*p+Te),t.push(ve*p+Te),t.push(ve*p+F)}dt.a._ComputeSides(d,e,t,n,i,r.frontUVs,r.backUVs);var Re=new dt.a;return Re.indices=t,Re.positions=e,Re.normals=n,Re.uvs=i,Re},De.a.CreateTorus=function(r,t,e,n,i,o,a){var s={diameter:t,thickness:e,tessellation:n,sideOrientation:a,updatable:o};return gr.CreateTorus(r,s,i)};var fn,er,gr=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,dt.a.CreateTorus(e).applyToMesh(i,e.updatable),i},r}(),fi=f(53),ps=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}(),Kl=function(){function r(t,e){var n=this;if(e===void 0&&(e=ps.GetDefaults()),this._options=e,this._canvas=null,this.xrLayer=null,this.onXRLayerInitObservable=new R.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}(),_s=function(){function r(t){this.scene=t,this._sessionEnded=!1,this.baseLayer=null,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new R.c,this.onXRReferenceSpaceChanged=new R.c,this.onXRSessionEnded=new R.c,this.onXRSessionInit=new R.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||ps.GetDefaults(e)).canvasElement=e.getRenderingCanvas()||void 0,new Kl(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 Ct.a(this.scene.getEngine(),Ct.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 ri,Ql=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}(),Yf=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(pr.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}(Ql),ql=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}(Ql),Kf=function(){},Zl=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 R.c,this.onAfterEnteringVRObservable=new R.c,this.onExitingVRObservable=new R.c,this.onControllerMeshLoadedObservable=new R.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 R.c,this.onMeshSelectedWithController=new R.c,this.onNewMeshPicked=new R.c,this.onBeforeCameraTeleport=new R.c,this.onAfterCameraTeleport=new R.c,this.onSelectedMeshUnselected=new R.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===Rn.A&&n._cameraGazer._selectionPointerDown()}),o.onbuttonup(function(d){n._interactionsEnabled&&d===Rn.A&&n._cameraGazer._selectionPointerUp()}));else{var a=o,s=new Yf(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 Fi&&(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 Bo("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 Li&&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?_s.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 ql(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=mr.GetDefault()),e.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new Vo("VRDeviceOrientationVRHelper",this._position,this._scene,!0,e.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new Go("WebVRHelper",this._position,this._scene,e),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new ql(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 nt,this._circleEase.setEasingMode(Ge.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 zo("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===ii.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 bi.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(Ge.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 Yn){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 Yn){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),b=[];b.push({frame:0,value:0}),b.push({frame:d,value:8}),b.push({frame:i,value:0}),p.setKeys(b),this._postProcessMove.animations.push(p);var x=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}),x.setKeys(O),this._postProcessMove.animations.push(x),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,b){return!(s.x>p.x+b)&&!(p.x-b>d.x)&&!(s.y>p.y+b)&&!(p.y-b>d.y)&&!(s.z>p.z+b)&&!(p.z-b>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 vr.a(0,0,0,0),e[t].copyFromPoints(n,i,o));var b=e[t];if(a||b.isFrontFacingTo(this._normalizedVelocity,0)){var x=b.signedDistanceTo(this._basePoint),O=u.e.Dot(b.normal,this._velocity);if(O==0){if(Math.abs(x)>=1)return;p=!0,d=0}else{var B=(1-x)/O;if((d=(-1-x)/O)>B){var F=B;B=d,d=F}if(d>1||B<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(b.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(d,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,i,o,b.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=br(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=br(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=br(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),Re=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*Re,ue=ve*(1-this._baseToVertex.lengthSquared())+Re*Re,(fe=br(se,ce,ue,J)).found){var Ae=(Te*fe.root-Re)/ve;Ae>=0&&Ae<=1&&(J=fe.root,z=!0,this._edge.scaleInPlace(Ae),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),Re=u.e.Dot(this._edge,this._baseToVertex),se=ve*-ie+Te*Te,ce=ve*(2*u.e.Dot(this._velocity,this._baseToVertex))-2*Te*Re,ue=ve*(1-this._baseToVertex.lengthSquared())+Re*Re,(fe=br(se,ce,ue,J)).found&&(Ae=(Te*fe.root-Re)/ve)>=0&&Ae<=1&&(J=fe.root,z=!0,this._edge.scaleInPlace(Ae),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),Re=u.e.Dot(this._edge,this._baseToVertex),se=ve*-ie+Te*Te,ce=ve*(2*u.e.Dot(this._velocity,this._baseToVertex))-2*Te*Re,ue=ve*(1-this._baseToVertex.lengthSquared())+Re*Re,(fe=br(se,ce,ue,J)).found&&(Ae=(Te*fe.root-Re)/ve)>=0&&Ae<=1&&(J=fe.root,z=!0,this._edge.scaleInPlace(Ae),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,b=0;bthis.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}(),iu=function(){function r(t,e,n){n===void 0&&(n=0),this.deviceType=e,this.deviceSlot=n,this.onInputChangedObservable=new R.c,this._deviceInputSystem=t}return r.prototype.getInput=function(t){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,t)},r}(),Zf=function(){function r(t){var e=this;this.onDeviceConnectedObservable=new R.c(function(i){e.getDevices().forEach(function(o){e.onDeviceConnectedObservable.notifyObserver(i,o)})}),this.onDeviceDisconnectedObservable=new R.c;var n=Object.keys(Kt).length/2;this._devices=new Array(n),this._firstDevice=new Array(n),this._deviceInputSystem=nu.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 iu(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 Jf=!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=fs.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),x.activeTexture(x["TEXTURE"+se]),x.bindTexture(x.TEXTURE_2D,ve._webGLTexture),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,fe.mag),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,fe.min),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(ue),B,F,0,x.RGBA,this._getWebGLTextureType(ue),null),x.framebufferTexture2D(x.DRAW_FRAMEBUFFER,Te,x.TEXTURE_2D,ve._webGLTexture,0),e&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(x.TEXTURE_2D,null),ve._framebuffer=O,ve._depthStencilBuffer=ie,ve.baseWidth=B,ve.baseHeight=F,ve.width=B,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 Re=new Ct.a(this,Ct.b.MultiRenderTarget);x.activeTexture(x.TEXTURE0),x.bindTexture(x.TEXTURE_2D,Re._webGLTexture),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,this.webGLVersion<2?x.DEPTH_COMPONENT:x.DEPTH_COMPONENT16,B,F,0,x.DEPTH_COMPONENT,x.UNSIGNED_SHORT,null),x.framebufferTexture2D(x.FRAMEBUFFER,x.DEPTH_ATTACHMENT,x.TEXTURE_2D,Re._webGLTexture,0),Re._framebuffer=O,Re.baseWidth=B,Re.baseHeight=F,Re.width=B,Re.height=F,Re.isReady=!0,Re.samples=1,Re.generateMipMaps=e,Re.samplingMode=x.NEAREST,Re._generateDepthBuffer=n,Re._generateStencilBuffer=i,z.push(Re),this._internalTexturesCache.push(Re)}return x.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"],b=n.createRenderbuffer();if(!b)throw new Error("Unable to create multi sampled framebuffer");n.bindRenderbuffer(n.RENDERBUFFER,b),n.renderbufferStorageMultisample(n.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(d.type),d.width,d.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,p,n.RENDERBUFFER,b),d._MSAAFramebuffer=o,d._MSAARenderBuffer=b,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 to=f(56);Bt.a.prototype._createDepthStencilCubeTexture=function(r,t){var e=new Ct.a(this,Ct.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=to.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,b,x,O){var B=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),b===void 0&&(b=0),x===void 0&&(x=null);var F=this._gl,z=x||new Ct.a(this,Ct.b.Cube);z.isCube=!0,z.url=r,z.generateMipMaps=!n,z._lodGenerationScale=p,z._lodGenerationOffset=b,this._doNotHandleContextLost||(z._extension=s,z._files=e);var J=r;this._transformTextureUrl&&!x&&(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); -}`;ze.a.ShadersStore.rgbdEncodePixelShader=ip;var rp=` -varying vec2 vUV; -uniform sampler2D textureSampler; -#include -void main(void) -{ -gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0); -}`;ze.a.ShadersStore.rgbdDecodePixelShader=rp;var Ei=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")Ye=createImageBitmap(Me).then(function(it){return n._OnImageReadyAsync(it,o,a,d,Fe,xe,Ee,s,b,p,t)});else{var tt=new Image;tt.src=Fe,Ye=new Promise(function(it,lt){tt.onload=function(){n._OnImageReadyAsync(tt,o,a,d,Fe,xe,Ee,s,b,p,t).then(function(){return it()}).catch(function(Ke){lt(Ke)})},tt.onerror=function(Ke){lt(Ke)}})}ue.push(Ye)},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=x+1;var se=e>0?this._sourceCode.substring(0,e):"",ce=x+1=0},r.prototype._extractBetweenMarkers=function(t,e,n,i){for(var o=i,a=0,s="";o0?this._sourceCode.substring(0,b):"",fe=O+1"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(){}),e._shaderProcessor=new su.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 lu;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 lu;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 b=p.getBuffer();b&&this._native.recordVertexBuffer(e,b.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 op},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 Ss(n);d.processCode(),n=d.code;var p=new Ss(i);p.processCode(),i=p.code,n=Bt.a._ConcatenateShader(n,o),i=Bt.a._ConcatenateShader(i,o);var b=this._native.createProgram(n,i);return this.onAfterShaderCompilationObservable.notifyObservers(this),b},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,Re=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=Ei.GetEnvInfo(ce);if(z.width=ue.width,z.height=ue.width,Ei.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=Ei.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 Xe.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 Ll.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 uu(this,Ct.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 Oe.b.UNSIGNED_BYTE:return this._native.ATTRIB_TYPE_UINT8;case Oe.b.SHORT:return this._native.ATTRIB_TYPE_INT16;case Oe.b.FLOAT:return this._native.ATTRIB_TYPE_FLOAT;default:throw new Error("Unsupported attribute type: "+e+".")}},t}(Ue.a),sp=f(74),Wo=function(){function r(){}return r.COPY=1,r.CUT=2,r.PASTE=3,r}(),cp=function(){function r(t,e){this.type=t,this.event=e}return r.GetTypeFromCharacter=function(t){switch(t){case 67:return Wo.COPY;case 86:return Wo.PASTE;case 88:return Wo.CUT;default:return-1}},r}(),As=f(83),Ai=f(69);(function(r){r[r.Clean=0]="Clean",r[r.Stop=1]="Stop",r[r.Sync=2]="Sync",r[r.NoSync=3]="NoSync"})(Si||(Si={}));var Ut=function(){function r(){}return Object.defineProperty(r,"ForceFullSceneLoadingForIncremental",{get:function(){return Ai.a.ForceFullSceneLoadingForIncremental},set:function(t){Ai.a.ForceFullSceneLoadingForIncremental=t},enumerable:!1,configurable:!0}),Object.defineProperty(r,"ShowLoadingScreen",{get:function(){return Ai.a.ShowLoadingScreen},set:function(t){Ai.a.ShowLoadingScreen=t},enumerable:!1,configurable:!0}),Object.defineProperty(r,"loggingLevel",{get:function(){return Ai.a.loggingLevel},set:function(t){Ai.a.loggingLevel=t},enumerable:!1,configurable:!0}),Object.defineProperty(r,"CleanBoneMatrixWeights",{get:function(){return Ai.a.CleanBoneMatrixWeights},set:function(t){Ai.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),b=s?r._GetPluginForExtension(s):p?r._GetPluginForDirectLoad(t.name):r._GetPluginForFilename(t.name);if(!(d=b.plugin.createPlugin!==void 0?b.plugin.createPlugin():b.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 x=d.directLoad(e,p);x.then?x.then(function(Ae){n(d,Ae)}).catch(function(Ae){o("Error in directLoad of _loadData: "+Ae,Ae)}):n(d,x)}else n(d,p);return d}var O=b.isBinary,B=function(Ae,Ee){e.isDisposed?o("Scene has been disposed"):n(d,Ae,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 Ae=function(Se,Le){B(Se,Le?Le.responseURL:void 0)},Ee=function(Se){o(Se.message,Se)};F=d.requestFile?d.requestFile(e,t.url,Ae,i,O,Ee):e._requestFile(t.url,Ae,i,!0,O,Ee)}},se=t.file||As.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(Re)/F.snapDistance),Re<0&&(Fe*=-1),Re%=F.snapDistance,Ae.scaleToRef(F.snapDistance*Fe,Ae),Me=!0):Ae.scaleInPlace(0)),u.a.ScalingToRef(1+Ae.x,1+Ae.y,1+Ae.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),Me&&(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=(x=(b=o?.uniformScaleGizmo)===null||b===void 0?void 0:b.dragBehavior)===null||x===void 0?void 0:x.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};(B=F._parent)===null||B===void 0||B.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 Me=F._isHovered||F._dragging?F._hoverMaterial:F._coloredMaterial;Se.gizmoMeshes.forEach(function(Fe){Fe.material=Me,Fe.color&&(Fe.color=Me.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=Tr.a.CreateBox("yPosMesh",{size:.4*(1+(n-1)/4)},this.gizmoLayer.utilityLayerScene),a=fi.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}(Bn.a),Un=f(45),cn=f(40),du=function(r){function t(e,n){e===void 0&&(e=M.a.Gray()),n===void 0&&(n=On.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 R.c,i.onScaleBoxDragObservable=new R.c,i.onScaleBoxDragEndObservable=new R.c,i.onRotationSphereDragObservable=new R.c,i.onRotationSphereDragEndObservable=new R.c,i.scalePivot=null,i._existingMeshScale=new u.e,i._dragMesh=null,i.pointerDragBehavior=new vi.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=Un.a.CreateSphere("",{diameter:1},n.utilityLayerScene);ie.rotationQuaternion=new u.b,ie.material=s.coloredMaterial,(x=new vi.a({})).moveAttached=!1,x.updateDragPlane=!1,ie.addBehavior(x);var se=new u.e(1,0,0),ce=0;x.onDragStartObservable.add(function(){se.copyFrom(ie.forward),ce=0}),x.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");jn.a._RemoveAndStorePivotPoint(i.attachedMesh);var ve=se,Te=ue.dragPlaneNormal.scale(u.e.Dot(ue.dragPlaneNormal,ve)),Re=ve.subtract(Te).normalizeToNew(),Ae=u.e.Dot(Re,ue.delta)<0?Math.abs(ue.delta.length()):-Math.abs(ue.delta.length());Ae=Ae/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+=Ae,Math.abs(ce)<=2*Math.PI&&(J>=8?u.b.RotationYawPitchRollToRef(0,0,Ae,i._tmpQuaternion):J>=4?u.b.RotationYawPitchRollToRef(Ae,0,0,i._tmpQuaternion):u.b.RotationYawPitchRollToRef(0,Ae,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(),jn.a._RestorePivotPoint(i.attachedMesh)}i._updateDummy()}),x.onDragStartObservable.add(function(){i.onDragStartObservable.notifyObservers({}),i._selectNode(ie)}),x.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 b=0;b<3;b++)for(var x,O=function(){var J=(p===1?1:0)+(b===1?1:0)+(F===1?1:0);if(J===1||J===3)return"continue";var ie=Tr.a.CreateBox("",{size:1},n.utilityLayerScene);ie.material=B.coloredMaterial,ie.metadata=J===2;var se=new u.e(p-1,b-1,F-1).normalize();(x=new vi.a({dragAxis:se})).updateDragPlane=!1,x.moveAttached=!1,ie.addBehavior(x),x.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");jn.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),jn.a._RestorePivotPoint(i.attachedMesh)}i._updateDummy()}),x.onDragStartObservable.add(function(){i.onDragStartObservable.notifyObservers({}),i._selectNode(ie)}),x.onDragEndObservable.add(function(){i.onScaleBoxDragEndObservable.notifyObservers({}),i._selectNode(null),i._updateDummy()}),B._scaleBoxesParent.addChild(ie)},B=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){jn.a._RemoveAndStorePivotPoint(e);var i=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(i),jn.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){jn.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),jn.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=Tr.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}(Bn.a),Qo=function(r){function t(e,n,i,o,a,s,d){var p;n===void 0&&(n=M.a.Gray()),i===void 0&&(i=On.a.DefaultUtilityLayer),o===void 0&&(o=32),a===void 0&&(a=null),d===void 0&&(d=1);var b=r.call(this,i)||this;b._pointerObserver=null,b.snapDistance=0,b.onSnapObservable=new R.c,b._isEnabled=!0,b._parent=null,b._dragging=!1,b._parent=a,b._coloredMaterial=new Ft.a("",i.utilityLayerScene),b._coloredMaterial.diffuseColor=n,b._coloredMaterial.specularColor=n.subtract(new M.a(.1,.1,.1)),b._hoverMaterial=new Ft.a("",i.utilityLayerScene),b._hoverMaterial.diffuseColor=M.a.Yellow(),b._disableMaterial=new Ft.a("",i.utilityLayerScene),b._disableMaterial.diffuseColor=M.a.Gray(),b._disableMaterial.alpha=.4,b._gizmoMesh=new De.a("",i.utilityLayerScene);var x=b._createGizmoMesh(b._gizmoMesh,d,o),O=x.rotationMesh,B=x.collider,F=[];b._rotationCircle=b.setupRotationCircle(F,b._gizmoMesh),b._gizmoMesh.lookAt(b._rootMesh.position.add(e)),b._rootMesh.addChild(b._gizmoMesh),b._gizmoMesh.scaling.scaleInPlace(1/3),b.dragBehavior=new vi.a({dragPlaneNormal:e}),b.dragBehavior.moveAttached=!1,b.dragBehavior.maxDragAngle=9*Math.PI/20,b.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,b._rootMesh.addBehavior(b.dragBehavior);var z=0,J=new u.e,ie=new u.e,se=new u.a,ce=new u.e,ue=new u.e;b.dragBehavior.onDragStartObservable.add(function(Se){if(b.attachedNode){J.copyFrom(Se.dragPlanePoint);var Le=new u.e(0,0,1),xe=b._rotationCircle.getDirection(Le);xe.normalize(),b._gizmoMesh.removeChild(b._rotationCircle),J.copyFrom(Se.dragPlanePoint),ie=Se.dragPlanePoint;var Ne=b._rotationCircle.getAbsolutePosition().clone(),Me=b._rotationCircle.getAbsolutePosition().clone().addInPlace(xe),Fe=Se.dragPlanePoint,Ye=u.e.GetAngleBetweenVectors(Me.subtract(Ne),Fe.subtract(Ne),b._rotationCircle.up);b._rotationCircle.addRotation(0,Ye,0),b._dragging=!0}}),b.dragBehavior.onDragEndObservable.add(function(){z=0,b.updateRotationCircle(b._rotationCircle,F,z,ie),b._gizmoMesh.addChild(b._rotationCircle),b._dragging=!1});var fe={snapDistance:0},ve=0,Te=new u.a,Re=new u.b;b.dragBehavior.onDragObservable.add(function(Se){if(b.attachedNode){var Le=new u.e(1,1,1),xe=new u.b(0,0,0,1),Ne=new u.e(0,0,0);b.attachedNode.getWorldMatrix().decompose(Le,xe,Ne);var Me=Se.dragPlanePoint.subtract(Ne).normalize(),Fe=J.subtract(Ne).normalize(),Ye=u.e.Cross(Me,Fe),tt=u.e.Dot(Me,Fe),it=Math.atan2(Ye.length(),tt);ce.copyFrom(e),ue.copyFrom(e),b.updateGizmoRotationToMatchAttachedMesh&&(xe.toRotationMatrix(se),ue=u.e.TransformCoordinates(ce,se));var lt=!1;if(i.utilityLayerScene.activeCamera){var Ke=i.utilityLayerScene.activeCamera.position.subtract(Ne);u.e.Dot(Ke,ue)>0&&(ce.scaleInPlace(-1),ue.scaleInPlace(-1),lt=!0)}u.e.Dot(ue,Ye)>0&&(it=-it);var ot=!1;if(b.snapDistance!=0)if(ve+=it,Math.abs(ve)>b.snapDistance){var rt=Math.floor(Math.abs(ve)/b.snapDistance);ve<0&&(rt*=-1),ve%=b.snapDistance,it=b.snapDistance*rt,ot=!0}else it=0;z+=lt?-it:it,b.updateRotationCircle(b._rotationCircle,F,z,ie);var qe=Math.sin(it/2);if(Re.set(ce.x*qe,ce.y*qe,ce.z*qe,Math.cos(it/2)),Te.determinant()>0){var ht=new u.e;Re.toEulerAnglesToRef(ht),u.b.RotationYawPitchRollToRef(ht.y,-ht.x,-ht.z,Re)}b.updateGizmoRotationToMatchAttachedMesh?xe.multiplyToRef(Re,xe):Re.multiplyToRef(xe,xe),b.attachedNode.getWorldMatrix().copyFrom(u.a.Compose(Le,xe,Ne)),J.copyFrom(Se.dragPlanePoint),ot&&(fe.snapDistance=it,b.onSnapObservable.notifyObservers(fe)),b._matrixChanged()}});var Ae=i._getSharedGizmoLight();Ae.includedOnlyMeshes=Ae.includedOnlyMeshes.concat(b._rootMesh.getChildMeshes(!1));var Ee={colliderMeshes:[B],gizmoMeshes:[O],material:b._coloredMaterial,hoverMaterial:b._hoverMaterial,disableMaterial:b._disableMaterial,active:!1};return(p=b._parent)===null||p===void 0||p.addToAxisCache(b._gizmoMesh,Ee),b._pointerObserver=i.utilityLayerScene.onPointerObservable.add(function(Se){var Le;if(!b._customMeshSet&&(b._isHovered=Ee.colliderMeshes.indexOf((Le=Se?.pickInfo)===null||Le===void 0?void 0:Le.pickedMesh)!=-1,!b._parent)){var xe=b._isHovered||b._dragging?b._hoverMaterial:b._coloredMaterial;Ee.gizmoMeshes.forEach(function(Ne){Ne.material=xe,Ne.color&&(Ne.color=xe.diffuseColor)})}}),b}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,x=n>0?a:-1*a;s[d].set(t._CircleConstants.radius*Math.sin(b)*Math.cos(x),0,t._CircleConstants.radius*Math.cos(b)*Math.cos(x))}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}(Bn.a),fu=function(r){function t(e,n,i,o,a){e===void 0&&(e=On.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 R.c,s.onDragEndObservable=new R.c,s._observables=[],s._gizmoAxisCache=new Map,s.xGizmo=new Qo(new u.e(1,0,0),M.a.Red().scale(.5),e,n,s,i,o),s.yGizmo=new Qo(new u.e(0,1,0),M.a.Green().scale(.5),e,n,s,i,o),s.zGizmo=new Qo(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):Bn.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}(Bn.a),Er=f(46),Rs=f(84),qo=function(r){function t(e,n,i,o){var a;n===void 0&&(n=M.a.Gray()),i===void 0&&(i=On.a.DefaultUtilityLayer),o===void 0&&(o=null);var s=r.call(this,i)||this;s._pointerObserver=null,s.snapDistance=0,s.onSnapObservable=new R.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,b={snapDistance:0};s.dragBehavior=new vi.a({dragPlaneNormal:e}),s.dragBehavior.moveAttached=!1,s._rootMesh.addBehavior(s.dragBehavior),s.dragBehavior.onDragObservable.add(function(B){if(s.attachedNode){if(s.snapDistance==0)s.attachedNode.getWorldMatrix().addTranslationFromFloats(B.delta.x,B.delta.y,B.delta.z);else if(d+=B.dragDistance,Math.abs(d)>s.snapDistance){var F=Math.floor(Math.abs(d)/s.snapDistance);d%=s.snapDistance,B.delta.normalizeToRef(p),p.scaleInPlace(s.snapDistance*F),s.attachedNode.getWorldMatrix().addTranslationFromFloats(p.x,p.y,p.z),b.snapDistance=s.snapDistance*F,s.onSnapObservable.notifyObservers(b)}s._matrixChanged()}}),s.dragBehavior.onDragStartObservable.add(function(){s._dragging=!0}),s.dragBehavior.onDragEndObservable.add(function(){s._dragging=!1});var x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.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(B){var F;if(!s._customMeshSet&&(s._isHovered=O.colliderMeshes.indexOf((F=B?.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 Er.a("plane",e),o=Rs.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}(Bn.a),pu=function(r){function t(e,n,i){e===void 0&&(e=On.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 R.c,o.onDragEndObservable=new R.c,o._planarGizmoEnabled=!1,o.xGizmo=new Ko.a(new u.e(1,0,0),M.a.Red().scale(.5),e,o,n),o.yGizmo=new Ko.a(new u.e(0,1,0),M.a.Green().scale(.5),e,o,n),o.zGizmo=new Ko.a(new u.e(0,0,1),M.a.Blue().scale(.5),e,o,n),o.xPlaneGizmo=new qo(new u.e(1,0,0),M.a.Red().scale(.5),o.gizmoLayer,o),o.yPlaneGizmo=new qo(new u.e(0,1,0),M.a.Green().scale(.5),o.gizmoLayer,o),o.zPlaneGizmo=new qo(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):Bn.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}(Bn.a);dt.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,b=r.sizeX||p||1,x=r.sizeY||p||1,O=r.sizeZ||p||1,B=r.custom||t[d],F=B.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||dt.a.DEFAULTSIDE,ce=new Array,ue=new Array,fe=new Array,ve=new Array,Te=new Array,Re=0,Ae=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}(),Pi=f(48),Zo=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}(Pi.a);Q.a.AddNodeConstructor("Light_Type_1",function(r,t){return function(){return new Os(r,u.e.Zero(),t)}});var Os=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 Pi.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 B=this._orthoRight-this._orthoLeft,F=this._orthoTop-this._orthoBottom;u.a.OrthoOffCenterLHToRef(this._orthoLeft-B*this.shadowOrthoScale,this._orthoRight+B*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}(Zo);De.a.CreateHemisphere=function(r,t,e,n){var i={segments:t,diameter:e};return Jo.CreateHemisphere(r,i,n)};var Jo=function(){function r(){}return r.CreateHemisphere=function(t,e,n){e.diameter||(e.diameter=1),e.segments||(e.segments=16);var i=Un.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 Ms(r,u.e.Zero(),u.e.Zero(),0,0,t)}});var Ms=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 Pi.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}(Zo),dp=function(r){function t(e){e===void 0&&(e=On.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 R.c,n._light=null,n.attachedMesh=new Dt.a("",n.gizmoLayer.utilityLayerScene),n._attachedMeshParent=new Er.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 ko.a?this._lightMesh=t._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=e instanceof Os?t._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Ms?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=Jo.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=Un.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);Un.a.CreateSphere(n.name,{segments:10,diameter:1},e).parent=n;var i=Jo.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,Un.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}(Bn.a),Is=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}(),pp=function(r){function t(e){e===void 0&&(e=On.a.DefaultUtilityLayer);var n=r.call(this,e)||this;return n._pointerObserver=null,n.onClickedObservable=new R.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,Tr.a.CreateBox(n.name,{width:1,height:.8,depth:.5},e).parent=i;var o=fi.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=fi.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=fi.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}(Bn.a);ze.a.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";var _p=`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); -}`;ze.a.IncludesShadersStore.packingFunctions=_p;var mp=`#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`;ze.a.IncludesShadersStore.kernelBlurFragment=mp;var gp=`#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`;ze.a.IncludesShadersStore.kernelBlurFragment2=gp;var vp=` -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 -}`;ze.a.ShadersStore.kernelBlurPixelShader=vp,ze.a.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";var bp=` -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); -}`;ze.a.ShadersStore.kernelBlurVertexShader=bp;var _n=function(r){function t(e,n,i,o,a,s,d,p,b,x,O){s===void 0&&(s=we.a.BILINEAR_SAMPLINGMODE),b===void 0&&(b=h.a.TEXTURETYPE_UNSIGNED_INT),x===void 0&&(x=""),O===void 0&&(O=!1);var B=r.call(this,e,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],o,a,s,d,p,null,b,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return B.blockCompilation=O,B._packedFloat=!1,B._staticDefines="",B._staticDefines=x,B.direction=n,B.onApplyObservable.add(function(F){B._outputTexture?F.setFloat2("delta",1/B._outputTexture.width*B.direction.x,1/B._outputTexture.height*B.direction.y):F.setFloat2("delta",1/B.width*B.direction.x,1/B.height*B.direction.y)}),B.kernel=i,B}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);C.a.RegisteredTypes["BABYLON.BlurPostProcess"]=_n;var Ds=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 vr.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 Ds(r,t,e,n)};var Qn=f(34),oi=function(r){function t(e,n,i,o,a,s,d,p,b,x,O,B,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),b===void 0&&(b=!1),x===void 0&&(x=null),O===void 0&&(O=!1),B===void 0&&(B=.8),F===void 0&&(F=0);var ie=r.call(this,n)||this;if(ie.onLoadObservable=new R.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=x,ie._loaderOptions=z,!e&&!a)return ie;var se=e.lastIndexOf("."),ce=x||(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=b,b&&(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; -} -`;ze.a.ShadersStore.backgroundPixelShader=Ep;var Sp=`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`;ze.a.IncludesShadersStore.backgroundVertexDeclaration=Sp,f(78),f(79),f(117),f(137),f(80),f(81),f(111),f(157),f(138);var Ap=`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 -} -`;ze.a.ShadersStore.backgroundVertexShader=Ap;var Sr=f(67),Pp=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}($o.a),oo=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 di.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 Pp);var a=this.getScene(),s=n._materialDefines;if(this._isReadyForSubMesh(n))return!0;var d=a.getEngine();if(et.a.PrepareDefinesForLights(a,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,et.a.PrepareDefinesForMultiview(a,s),s._areTexturesDirty){if(s._needUVs=!1,a.texturesEnabled){if(a.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&ut.a.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;et.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&&ut.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(et.a.PrepareDefinesForMisc(e,a,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),et.a.PrepareDefinesForFrameBoundValues(a,d,s,i,null,n.getRenderingMesh().hasThinInstances),et.a.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&(a.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Oe.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 b=new Sr.a;s.FOG&&b.addFallback(0,"FOG"),s.POINTSIZE&&b.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&b.addFallback(0,"MULTIVIEW"),et.a.HandleFallbacksForShadows(s,b,this._maxSimultaneousLights);var x=[Oe.b.PositionKind];s.NORMAL&&x.push(Oe.b.NormalKind),s.UV1&&x.push(Oe.b.UVKind),s.UV2&&x.push(Oe.b.UV2Kind),et.a.PrepareAttributesForBones(x,e,s,b),et.a.PrepareAttributesForInstances(x,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"],B=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],F=["Material","Scene"];vn.a&&(vn.a.PrepareUniforms(O,s),vn.a.PrepareSamplers(B,s)),et.a.PrepareUniformsAndSamplersList({uniformsNames:O,uniformBuffersNames:F,samplers:B,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});var z=s.toString();n.setEffect(a.getEngine().createEffect("background",{attributes:x,uniformsNames:O,uniformBuffersNames:F,samplers:B,defines:z,fallbacks:b,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),et.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&&ut.a.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),et.a.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),p&&ut.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&&ut.a.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),p&&ut.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)))),et.a.BindClipPlane(this._activeEffect,o),et.a.BindEyePosition(s,o)}!d&&this.isFrozen||(o.lightsEnabled&&et.a.BindLights(o,n,this._activeEffect,a,this._maxSimultaneousLights,!1),this.bindView(s),et.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}(ea.a);C.a.RegisteredTypes["BABYLON.BackgroundMaterial"]=oo;var Ls=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 R.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 Wn.a)this._scene.environmentTexture=this._options.environmentTexture;else{var t=oi.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 oo("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 Wn.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 Ds("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,we.a.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new vr.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}(),Pr=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&&ut.a.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())},r.prototype.prepareDefines=function(t,e,n){this._isEnabled?(t.ANISOTROPIC=this._isEnabled,this._isEnabled&&!e.isVerticesDataPresent(Oe.b.TangentKind)&&(t._needUVs=!0,t.MAINUV1=!0),t._areTexturesDirty&&n.texturesEnabled&&(this._texture&&ut.a.AnisotropicTextureEnabled?et.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&&ut.a.AnisotropicTextureEnabled&&(t.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),et.a.BindTextureMatrix(this._texture,t,"anisotropy")),t.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),e.texturesEnabled&&this._texture&&ut.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}(),Cp=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}(),ao=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&&ut.a.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&ut.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&&ut.a.SheenTextureEnabled?et.a.PrepareDefinesForMergedUV(this._texture,t,"SHEEN_TEXTURE"):t.SHEEN_TEXTURE=!1,this._textureRoughness&&ut.a.SheenTextureEnabled?et.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,b,x,O,B=i._materialDefines,F=B.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;t.useUbo&&n&&t.isSync||(F&&ut.a.SheenTextureEnabled?(t.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),et.a.BindTextureMatrix(this._texture,t,"sheen")):(this._texture||this._textureRoughness)&&ut.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,(b=(p=this._textureRoughness)===null||p===void 0?void 0:p.coordinatesIndex)!==null&&b!==void 0?b:0,(O=(x=this._textureRoughness)===null||x===void 0?void 0:x.level)!==null&&O!==void 0?O:0),this._texture&&et.a.BindTextureMatrix(this._texture,t,"sheen"),!this._textureRoughness||F||B.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||et.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&&ut.a.SheenTextureEnabled&&t.setTexture("sheenSampler",this._texture),this._textureRoughness&&!F&&!B.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ut.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}(),so=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&&ut.a.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;var n=this._getRefractionTexture(e);if(n&&ut.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&&ut.a.ThicknessTextureEnabled&&et.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&&ut.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&&ut.a.ThicknessTextureEnabled&&(t.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),et.a.BindTextureMatrix(this._thicknessTexture,t,"thickness")),t.updateFloat2("vThicknessParam",this.minimumThickness,this.maximumThickness-this.minimumThickness),s&&ut.a.RefractionTextureEnabled){t.updateMatrix("refractionMatrix",s.getReflectionTextureMatrix());var d=1;s.isCube||s.depth&&(d=s.depth);var p=s.getSize().width,b=this.volumeIndexOfRefraction;t.updateFloat4("vRefractionInfos",s.level,1/b,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&&ut.a.ThicknessTextureEnabled&&t.setTexture("thicknessSampler",this._thicknessTexture),s&&ut.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){ut.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!!(ut.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}(),Ns=f(105),Ht=f(25),Rp=(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`);ze.a.IncludesShadersStore.pbrFragmentDeclaration=Rp;var Op=`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; -};`;ze.a.IncludesShadersStore.pbrUboDeclaration=Op;var Mp=`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`;ze.a.IncludesShadersStore.pbrFragmentExtraDeclaration=Mp;var Ip=`#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`;ze.a.IncludesShadersStore.pbrFragmentSamplersDeclaration=Ip,f(116),ze.a.IncludesShadersStore.subSurfaceScatteringFunctions=`bool testLightingForSSS(float diffusionProfile) -{ -return diffusionProfile<1.; -}`;var Dp=` - - - - - - - - - - - - - - - - - - - - - - - - - - - - -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); -}`;ze.a.IncludesShadersStore.importanceSampling=Dp;var Lp=` -#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`;ze.a.IncludesShadersStore.pbrHelperFunctions=Lp;var Np=`#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`;ze.a.IncludesShadersStore.harmonicsFunctions=Np;var wp=` -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; -}`;ze.a.IncludesShadersStore.pbrDirectLightingSetupFunctions=wp;var Fp=`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 -}`;ze.a.IncludesShadersStore.pbrDirectLightingFalloffFunctions=Fp;var Bp=` -#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 -`;ze.a.IncludesShadersStore.pbrBRDFFunctions=Bp;var Up=`#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`;ze.a.IncludesShadersStore.hdrFilteringFunctions=Up;var Vp=`#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 -`;ze.a.IncludesShadersStore.pbrDirectLightingFunctions=Vp;var kp=`#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`;ze.a.IncludesShadersStore.pbrIBLFunctions=kp,f(132),f(133);var Gp=`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; -} -`;ze.a.IncludesShadersStore.pbrBlockReflectivity=zp;var jp=`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; -} -`;ze.a.IncludesShadersStore.pbrBlockAmbientOcclusion=jp;var Hp=`#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 -`;ze.a.IncludesShadersStore.pbrBlockAnisotropic=Wp;var Xp=`#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 -`;ze.a.IncludesShadersStore.pbrBlockReflection=Xp;var Yp=`#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 -`;ze.a.IncludesShadersStore.pbrBlockSheen=Yp;var Kp=`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 -`;ze.a.IncludesShadersStore.pbrBlockClearcoat=Kp;var Qp=`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 -`;ze.a.IncludesShadersStore.pbrBlockSubSurface=Qp;var qp=`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 -`;ze.a.IncludesShadersStore.pbrBlockNormalGeometric=qp,f(134);var Zp=`#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 -`;ze.a.IncludesShadersStore.pbrBlockNormalFinal=Zp,f(162);var Jp=`#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 -`;ze.a.IncludesShadersStore.pbrBlockLightmapInit=Jp;var $p=`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 -`;ze.a.IncludesShadersStore.pbrBlockGeometryInfo=$p;var e_=`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 -`;ze.a.IncludesShadersStore.pbrBlockReflectance0=e_;var t_=`#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 -`;ze.a.IncludesShadersStore.pbrBlockReflectance=t_;var n_=`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 -`;ze.a.IncludesShadersStore.pbrBlockDirectLighting=n_;var i_=` - - - -#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 -`;ze.a.IncludesShadersStore.pbrBlockFinalLitComponents=i_;var r_=` -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; -`;ze.a.IncludesShadersStore.pbrBlockFinalUnlitComponents=r_;var o_=`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); -`;ze.a.IncludesShadersStore.pbrBlockFinalColorComposition=o_,f(155);var a_=`#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 -`;ze.a.IncludesShadersStore.pbrBlockImageProcessing=a_;var s_=`#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`;ze.a.IncludesShadersStore.pbrDebug=s_;var c_=`#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 -} -`;ze.a.ShadersStore.pbrPixelShader=c_;var l_=`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 -`;ze.a.IncludesShadersStore.pbrVertexDeclaration=l_,f(163),f(164),f(93),f(94),f(100),f(165),f(156),f(158);var u_=`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 -}`;ze.a.ShadersStore.pbrVertexShader=u_;var na=f(92),xr={effect:null,subMesh:null},ws=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}($o.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 di.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 Ar(i._markAllSubMeshesAsTexturesDirty.bind(i)),i.anisotropy=new Pr(i._markAllSubMeshesAsTexturesDirty.bind(i)),i.brdf=new Cp(i._markAllSubMeshesAsMiscDirty.bind(i)),i.sheen=new ao(i._markAllSubMeshesAsTexturesDirty.bind(i)),i.detailMap=new na.a(i._markAllSubMeshesAsTexturesDirty.bind(i)),i._rebuildInParallel=!1,i._attachImageProcessingConfiguration(null),i.getRenderTargetTextures=function(){return i._renderTargets.reset(),ut.a.ReflectionTextureEnabled&&i._reflectionTexture&&i._reflectionTexture.isRenderTarget&&i._renderTargets.push(i._reflectionTexture),i.subSurface.fillRenderTargetTextures(i._renderTargets),i._renderTargets},i._environmentBRDFTexture=ta.GetEnvironmentBRDFTexture(n),i.subSurface=new so(i._markAllSubMeshesAsTexturesDirty.bind(i),i._markScenePrePassDirty.bind(i),n),i.prePassConfiguration=new Ns.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!!(ut.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 ws);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&&ut.a.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&ut.a.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&ut.a.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;var d=this._getReflectionTexture();if(d&&ut.a.ReflectionTextureEnabled&&(!d.isReadyOrNotBlocking()||d.irradianceTexture&&!d.irradianceTexture.isReadyOrNotBlocking())||this._lightmapTexture&&ut.a.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&ut.a.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(ut.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&&ut.a.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&ut.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(Oe.b.NormalKind)||(e.createNormals(!0),l.a.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));var p=n.effect,b=o._areLightsDisposed,x=this._prepareEffect(e,o,this.onCompiled,this.onError,i,null,n.getRenderingMesh().hasThinInstances);if(x)if(this._onEffectCreatedObservable&&(xr.effect=x,xr.subMesh=n,this._onEffectCreatedObservable.notifyObservers(xr)),this.allowShaderHotSwapping&&p&&!x.isReady()){if(x=p,this._rebuildInParallel=!0,o.markAsUnprocessed(),b)return o._areLightsDisposed=!0,!1}else this._rebuildInParallel=!1,a.resetCachedMaterial(),n.setEffect(x,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(),b=new Sr.a,x=0;n.USESPHERICALINVERTEX&&b.addFallback(x++,"USESPHERICALINVERTEX"),n.FOG&&b.addFallback(x,"FOG"),n.SPECULARAA&&b.addFallback(x,"SPECULARAA"),n.POINTSIZE&&b.addFallback(x,"POINTSIZE"),n.LOGARITHMICDEPTH&&b.addFallback(x,"LOGARITHMICDEPTH"),n.PARALLAX&&b.addFallback(x,"PARALLAX"),n.PARALLAXOCCLUSION&&b.addFallback(x++,"PARALLAXOCCLUSION"),x=Pr.AddFallbacks(n,b,x),x=Pr.AddFallbacks(n,b,x),x=so.AddFallbacks(n,b,x),x=ao.AddFallbacks(n,b,x),n.ENVIRONMENTBRDF&&b.addFallback(x++,"ENVIRONMENTBRDF"),n.TANGENT&&b.addFallback(x++,"TANGENT"),n.BUMP&&b.addFallback(x++,"BUMP"),x=et.a.HandleFallbacksForShadows(n,b,this._maxSimultaneousLights,x++),n.SPECULARTERM&&b.addFallback(x++,"SPECULARTERM"),n.USESPHERICALFROMREFLECTIONMAP&&b.addFallback(x++,"USESPHERICALFROMREFLECTIONMAP"),n.USEIRRADIANCEMAP&&b.addFallback(x++,"USEIRRADIANCEMAP"),n.LIGHTMAP&&b.addFallback(x++,"LIGHTMAP"),n.NORMAL&&b.addFallback(x++,"NORMAL"),n.AMBIENT&&b.addFallback(x++,"AMBIENT"),n.EMISSIVE&&b.addFallback(x++,"EMISSIVE"),n.VERTEXCOLOR&&b.addFallback(x++,"VERTEXCOLOR"),n.MORPHTARGETS&&b.addFallback(x++,"MORPHTARGETS"),n.MULTIVIEW&&b.addFallback(0,"MULTIVIEW");var O=[Oe.b.PositionKind];n.NORMAL&&O.push(Oe.b.NormalKind),n.TANGENT&&O.push(Oe.b.TangentKind),n.UV1&&O.push(Oe.b.UVKind),n.UV2&&O.push(Oe.b.UV2Kind),n.VERTEXCOLOR&&O.push(Oe.b.ColorKind),et.a.PrepareAttributesForBones(O,e,n,b),et.a.PrepareAttributesForInstances(O,n),et.a.PrepareAttributesForMorphTargets(O,e,n);var B="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"];na.a.AddUniforms(F),na.a.AddSamplers(z),so.AddUniforms(F),so.AddSamplers(z),Ar.AddUniforms(F),Ar.AddSamplers(z),Pr.AddUniforms(F),Pr.AddSamplers(z),ao.AddUniforms(F),ao.AddSamplers(z),Ns.a.AddUniforms(F),Ns.a.AddSamplers(F),vn.a&&(vn.a.PrepareUniforms(F,n),vn.a.PrepareSamplers(z,n)),et.a.PrepareUniformsAndSamplersList({uniformsNames:F,uniformBuffersNames:J,samplers:z,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});var ie={};this.customShaderNameResolve&&(B=this.customShaderNameResolve(B,F,J,z,n,O,ie));var se=n.toString();return p.createEffect(B,{attributes:O,uniformsNames:F,uniformBuffersNames:J,samplers:z,defines:se,fallbacks:b,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(et.a.PrepareDefinesForLights(s,e,n,!0,this._maxSimultaneousLights,this._disableLighting),n._needNormals=!0,et.a.PrepareDefinesForMultiview(s,n),et.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&&ut.a.DiffuseTextureEnabled?(et.a.PrepareDefinesForMergedUV(this._albedoTexture,n,"ALBEDO"),n.GAMMAALBEDO=this._albedoTexture.gammaSpace):n.ALBEDO=!1,this._ambientTexture&&ut.a.AmbientTextureEnabled?(et.a.PrepareDefinesForMergedUV(this._ambientTexture,n,"AMBIENT"),n.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):n.AMBIENT=!1,this._opacityTexture&&ut.a.OpacityTextureEnabled?(et.a.PrepareDefinesForMergedUV(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):n.OPACITY=!1;var p=this._getReflectionTexture();if(p&&ut.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&&ut.a.LightmapTextureEnabled?(et.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&&ut.a.EmissiveTextureEnabled?et.a.PrepareDefinesForMergedUV(this._emissiveTexture,n,"EMISSIVE"):n.EMISSIVE=!1,ut.a.SpecularTextureEnabled?(this._metallicTexture?(et.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?(et.a.PrepareDefinesForMergedUV(this._reflectivityTexture,n,"REFLECTIVITY"),n.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,n.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):n.REFLECTIVITY=!1,this._metallicReflectanceTexture?et.a.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,n,"METALLIC_REFLECTANCE"):n.METALLIC_REFLECTANCE=!1,this._microSurfaceTexture?et.a.PrepareDefinesForMergedUV(this._microSurfaceTexture,n,"MICROSURFACEMAP"):n.MICROSURFACEMAP=!1):(n.REFLECTIVITY=!1,n.MICROSURFACEMAP=!1),s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&ut.a.BumpTextureEnabled&&!this._disableBumpMap?(et.a.PrepareDefinesForMergedUV(this._bumpTexture,n,"BUMP"),this._useParallax&&this._albedoTexture&&ut.a.DiffuseTextureEnabled?(n.PARALLAX=!0,n.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):n.PARALLAX=!1,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):n.BUMP=!1,this._environmentBRDFTexture&&ut.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&&(et.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(Oe.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),et.a.PrepareDefinesForFrameBoundValues(s,d,n,!!i,o,a),et.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 ws,d=this._prepareEffect(e,s,void 0,void 0,a.useInstances,a.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(xr.effect=d,xr.subMesh=null,this._onEffectCreatedObservable.notifyObservers(xr)),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),Ar.PrepareUniformBuffer(e),Pr.PrepareUniformBuffer(e),ao.PrepareUniformBuffer(e),so.PrepareUniformBuffer(e),na.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);et.a.BindBonesParameters(n,this._activeEffect,this.prePassConfiguration);var p=null,b=this._uniformBuffer;if(d){var x=o.getEngine();if(b.bindToEffect(s,"Material"),this.bindViewProjection(s),p=this._getReflectionTexture(),!b.useUbo||!this.isFrozen||!b.isSync){if(o.texturesEnabled){if(this._albedoTexture&&ut.a.DiffuseTextureEnabled&&(b.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),et.a.BindTextureMatrix(this._albedoTexture,b,"albedo")),this._ambientTexture&&ut.a.AmbientTextureEnabled&&(b.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),et.a.BindTextureMatrix(this._ambientTexture,b,"ambient")),this._opacityTexture&&ut.a.OpacityTextureEnabled&&(b.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),et.a.BindTextureMatrix(this._opacityTexture,b,"opacity")),p&&ut.a.ReflectionTextureEnabled){if(b.updateMatrix("reflectionMatrix",p.getReflectionTextureMatrix()),b.updateFloat2("vReflectionInfos",p.level,0),p.boundingBoxSize){var O=p;b.updateVector3("vReflectionPosition",O.boundingBoxPosition),b.updateVector3("vReflectionSize",O.boundingBoxSize)}if(this.realTimeFiltering){var B=p.getSize().width;b.updateFloat2("vReflectionFilteringInfo",B,$.a.Log2(B))}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)}b.updateFloat3("vReflectionMicrosurfaceInfos",p.getSize().width,p.lodGenerationScale,p.lodGenerationOffset)}this._emissiveTexture&&ut.a.EmissiveTextureEnabled&&(b.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),et.a.BindTextureMatrix(this._emissiveTexture,b,"emissive")),this._lightmapTexture&&ut.a.LightmapTextureEnabled&&(b.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),et.a.BindTextureMatrix(this._lightmapTexture,b,"lightmap")),ut.a.SpecularTextureEnabled&&(this._metallicTexture?(b.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),et.a.BindTextureMatrix(this._metallicTexture,b,"reflectivity")):this._reflectivityTexture&&(b.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),et.a.BindTextureMatrix(this._reflectivityTexture,b,"reflectivity")),this._metallicReflectanceTexture&&(b.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),et.a.BindTextureMatrix(this._metallicReflectanceTexture,b,"metallicReflectance")),this._microSurfaceTexture&&(b.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),et.a.BindTextureMatrix(this._microSurfaceTexture,b,"microSurfaceSampler"))),this._bumpTexture&&x.getCaps().standardDerivatives&&ut.a.BumpTextureEnabled&&!this._disableBumpMap&&(b.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),et.a.BindTextureMatrix(this._bumpTexture,b,"bump"),o._mirroredCameraPosition?b.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):b.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&b.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,b.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;b.updateColor4("vMetallicReflectanceFactors",M.c.Color3[0],se)}else b.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);b.updateColor3("vEmissiveColor",ut.a.EmissiveTextureEnabled?this._emissiveColor:M.a.BlackReadOnly),b.updateColor3("vReflectionColor",this._reflectionColor),!a.SS_REFRACTION&&this.subSurface.linkRefractionWithTransparency?b.updateColor4("vAlbedoColor",this._albedoColor,1):b.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,b.updateVector4("vLightingIntensity",this._lightingInfos)}b.updateFloat("visibility",n.visibility),o.texturesEnabled&&(this._albedoTexture&&ut.a.DiffuseTextureEnabled&&b.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&ut.a.AmbientTextureEnabled&&b.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ut.a.OpacityTextureEnabled&&b.setTexture("opacitySampler",this._opacityTexture),p&&ut.a.ReflectionTextureEnabled&&(a.LODBASEDMICROSFURACE?b.setTexture("reflectionSampler",p):(b.setTexture("reflectionSampler",p._lodTextureMid||p),b.setTexture("reflectionSamplerLow",p._lodTextureLow||p),b.setTexture("reflectionSamplerHigh",p._lodTextureHigh||p)),a.USEIRRADIANCEMAP&&b.setTexture("irradianceSampler",p.irradianceTexture)),a.ENVIRONMENTBRDF&&b.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&ut.a.EmissiveTextureEnabled&&b.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ut.a.LightmapTextureEnabled&&b.setTexture("lightmapSampler",this._lightmapTexture),ut.a.SpecularTextureEnabled&&(this._metallicTexture?b.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&b.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&b.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._microSurfaceTexture&&b.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&x.getCaps().standardDerivatives&&ut.a.BumpTextureEnabled&&!this._disableBumpMap&&b.setTexture("bumpSampler",this._bumpTexture)),this.detailMap.bindForSubMesh(b,o,this.isFrozen),this.subSurface.bindForSubMesh(b,o,x,this.isFrozen,a.LODBASEDMICROSFURACE,this.realTimeFiltering),this.clearCoat.bindForSubMesh(b,o,x,this._disableBumpMap,this.isFrozen,this._invertNormalMapX,this._invertNormalMapY,i),this.anisotropy.bindForSubMesh(b,o,this.isFrozen),this.sheen.bindForSubMesh(b,o,this.isFrozen,i),et.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&&et.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),et.a.BindFogParameters(o,n,this._activeEffect,!0),a.NUM_MORPH_INFLUENCERS&&et.a.BindMorphTargetParameters(n,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),et.a.BindLogDepth(a,this._activeEffect,o)),b.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,b,x,O,B,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(),(b=this._reflectivityTexture)===null||b===void 0||b.dispose(),(x=this._bumpTexture)===null||x===void 0||x.dispose(),(O=this._lightmapTexture)===null||O===void 0||O.dispose(),(B=this._metallicReflectanceTexture)===null||B===void 0||B.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}(ea.a),co=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=ta.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);C.a.RegisteredTypes["BABYLON.PBRMaterial"]=co;function ia(r){return r.charCodeAt(0)+(r.charCodeAt(1)<<8)+(r.charCodeAt(2)<<16)+(r.charCodeAt(3)<<24)}var gu=ia("DXT1"),vu=ia("DXT3"),bu=ia("DXT5"),Fs=ia("DX10"),ki=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===Fs?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 Fs: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===gu||o===vu||o===bu,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,b=0;b>8)},r._GetRGBArrayBuffer=function(t,e,n,i,o,a,s,d){for(var p=new Uint8Array(i),b=new Uint8Array(o,n),x=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]);Re&&(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=Ho.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(b){if(b){var x=b.texture;if(d?b.info.sphericalPolynomial&&(x._sphericalPolynomial=b.info.sphericalPolynomial):x._sphericalPolynomial=new no,x._source=Ct.b.CubePrefiltered,p.getCaps().textureLOD)i&&i(x);else{var O=p._gl,B=b.width;if(B){for(var F=[],z=0;z<3;z++){var J=1-z/2,ie=n,se=$.a.Log2(B)*e+n,ce=ie+(se-ie)*J,ue=Math.round(Math.min(Math.max(ce,0),se)),fe=new Ct.a(p,Ct.b.Temp);if(fe.type=x.type,fe.format=x.format,fe.width=Math.pow(2,Math.max($.a.Log2(B)-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),b.isDDS){var ve=b.info,Te=b.data;p._unpackFlipY(ve.isCompressed),ki.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 Re=new Wn.a(t);Re.isCube=!0,Re._texture=fe,fe.isReady=!0,F.push(Re)}x._lodTextureHigh=F[2],x._lodTextureMid=F[1],x._lodTextureLow=F[0],i&&i(x)}}}else i&&i(null)},o,a,s,d,e,n)};var yu=function(){function r(){this.supportCascades=!0}return r.prototype.canLoad=function(t){return Qn.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),ki.UploadDDSLevels(s,e,b,a,d,6,-1,p),a.isFourCC||a.mipmapCount!==1||s.generateMipMapsForCubemap(e)}else{var x=t;a=ki.GetDDSInfo(x),e.width=a.width,e.height=a.height,n&&(a.sphericalPolynomial=new no),d=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&e.generateMipMaps,s._unpackFlipY(a.isCompressed),ki.UploadDDSLevels(s,e,x,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=ki.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(){ki.UploadDDSLevels(e.getEngine(),e,t,i,o,1)})},r}();Ue.a._TextureLoaders.push(new yu);var Tu=function(){function r(){this.supportCascades=!1}return r.prototype.canLoad=function(t){return Qn.a.EndsWith(t,".env")},r.prototype.loadCubeData=function(t,e,n,i,o){if(!Array.isArray(t)){var a=Ei.GetEnvInfo(t);a?(e.width=a.width,e.height=a.width,Ei.UploadEnvSpherical(e,a),Ei.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 Tu);var ra=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}},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}(),Bs=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 h_(){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(ra.IsValid(t)){e._invertVScale=!e.invertY;var o=new ra(t,1);n(o.pixelWidth,o.pixelHeight,e.generateMipMaps,!0,function(){o.uploadLevels(e,e.generateMipMaps)},o.isInvalid)}else Us.IsValid(t)?new Us(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 Eu);var Su=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 R.c,o.onAfterCameraTeleport=new R.c,o.onTrackingStateChanged=new R.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 Kn.a(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Kn.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 b=s.transform.position,x=s.transform.orientation;if(p.position.set(b.x,b.y,b.z),p.rotationQuaternion.set(x.x,x.y,x.z,x.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),B=e._xrSessionManager.session.renderState.baseLayer.framebufferWidth,F=e._xrSessionManager.session.renderState.baseLayer.framebufferHeight;p.viewport.width=O.width/B,p.viewport.height=O.height/F,p.viewport.x=O.x/B,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}(Yn),ai=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}(),qn=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],b=r.ConstructFeature(s,d,this._xrSessionManager,n);if(!b)throw new Error("feature not found - "+s);p&&this.disableFeature(s);var x=b();if(x.dependsOn&&!x.dependsOn.every(function(O){return!!a._features[O]}))throw new Error("Dependant features missing. Make sure the following features are enabled - "+x.dependsOn.join(", "));if(x.isCompatible())return this._features[s]={featureImplementation:x,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 Xe.b.Warn("Feature "+s+" not compatible with the current environment/browser and was not enabled."),x},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}(),Au=function(){function r(t){var e=this;this.scene=t,this._nonVRCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this.onInitialXRPoseSetObservable=new R.c,this.onStateChangedObservable=new R.c,this.state=fn.NOT_IN_XR,this.sessionManager=new _s(t),this.camera=new Su("",t,this.sessionManager),this.featuresManager=new qn(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 R.c,this.onButtonStateChangedObservable=new R.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}(),Rr=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,b=d.gamepadIndices.button,x=[];d.gamepadIndices.xAxis!==void 0&&d.gamepadIndices.yAxis!==void 0&&x.push(d.gamepadIndices.xAxis,d.gamepadIndices.yAxis),a.components[s]=new Cr(s,p,b,x)}},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new R.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}(),Vs=function(r){function t(e,n,i){var o=r.call(this,e,d_[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}(Rr),d_={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"}},Pu=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=Un.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}),b=!0,n._options.disablePointerUpOnTouchOut&&n._scene.simulatePointerUp(i.pick,{pointerId:i.id}),d.isVisible=!1;else{var x=1-p/o;d.scaling.set(x,x,x)}else b=!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&&b&&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 b=p.changes.pressed.current;i.pick?(n._options.enablePointerSelectionOnAllControllers||e.uniqueId===n._attachedController)&&(b?(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)):!b||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=ai.POINTER_SELECTION,t.Version=1,t}(si);qn.AddWebXRFeature(lo.Name,function(r,t){return function(){return new lo(r,t)}},lo.Version,!0);var Gi,Ru=function(){function r(t,e,n){this.element=t,this.sessionMode=e,this.referenceSpaceType=n}return r.prototype.update=function(t){},r}(),p_=function(){},Ou=function(){function r(t,e){var n=this;if(this.scene=t,this.options=e,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new R.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:"&&Xe.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 Ru(d,i,o)),this._buttons[this._buttons.length-1].update=function(b){this.element.style.display=b===null||b===this?"":"none",d.className="babylonVRicon"+(b===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 b,x,O;return Object(c.e)(this,function(B){switch(B.label){case 0:return e.state!=fn.IN_XR?[3,2]:[4,e.exitXRAsync()];case 1:return B.sent(),o._updateButtons(null),[3,6];case 2:if(e.state!=fn.NOT_IN_XR)return[3,6];if(!n.renderTarget)return[3,6];B.label=3;case 3:return B.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 B.sent(),o._updateButtons(o._buttons[p]),[3,6];case 5:return b=B.sent(),o._updateButtons(null),x=o._buttons[p].element,O=x.title,x.title="Error entering XR session : "+O,x.classList.add("xr-error"),n.onError&&n.onError(b),[3,6];case 6:return[2]}})})}):Xe.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 ks(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"})(Gi||(Gi={}));var __=function(){function r(t){var e,n,i=this;this.onEachCountObservable=new R.c,this.onTimerAbortedObservable=new R.c,this.onTimerEndedObservable=new R.c,this.onStateChangedObservable=new R.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(Gi.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===Gi.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(Gi.STARTED)},r.prototype.stop=function(){this._state===Gi.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(Gi.ENDED),e?this.onTimerAbortedObservable.notifyObservers(t):this.onTimerEndedObservable.notifyObservers(t)},r}(),uo=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,ks({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(b){if(b.y<=.7&&a.teleportationState.backwards&&(a.teleportationState.backwards=!1),b.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 x=i._xrSessionManager.scene.pickWithRay(i._tmpRay,function(B){return i._floorMeshes.indexOf(B)!==-1});x&&x.pickedPoint&&(i._options.xrInput.xrCamera.position.x=x.pickedPoint.x,i._options.xrInput.xrCamera.position.z=x.pickedPoint.z)}if(b.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),b.x){if(a.teleportationState.forward)i._currentTeleportationControllerId===a.xrController.uniqueId&&(i.rotationEnabled?setTimeout(function(){a.teleportationState.currentRotation=Math.atan2(b.x,b.y*(i._xrSessionManager.scene.useRightHandedSystem?1:-1))}):a.teleportationState.currentRotation=0);else if(!a.teleportationState.rotating&&Math.abs(b.x)>.7){a.teleportationState.rotating=!0;var O=i.rotationAngle*(b.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;b.x===0&&b.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,ks({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&&b?b&&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 R.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 Xe.b.SetCorsBehavior(e.currentSrc,e),e;var n=document.createElement("video");return typeof e=="string"?(Xe.b.SetCorsBehavior(e,n),n.src=e):(Xe.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),v_=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 Iu((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=Vi.MODE_MONOSCOPIC,t.MODE_TOPBOTTOM=Vi.MODE_TOPBOTTOM,t.MODE_SIDEBYSIDE=Vi.MODE_SIDEBYSIDE,t}(Vi),Xn=f(55),b_=function(){function r(t){this.engine=t,this._captureGPUFrameTime=!1,this._gpuFrameTime=new Xn.a,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new Xn.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}(),y_=function(){function r(t){var e=this;this.scene=t,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new Xn.a,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new Xn.a,this._captureFrameTime=!1,this._frameTime=new Xn.a,this._captureRenderTime=!1,this._renderTime=new Xn.a,this._captureInterFrameTime=!1,this._interFrameTime=new Xn.a,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new Xn.a,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new Xn.a,this._capturePhysicsTime=!1,this._physicsTime=new Xn.a,this._captureAnimationsTime=!1,this._animationsTime=new Xn.a,this._captureCameraRenderTime=!1,this._cameraRenderTime=new Xn.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&&(Xe.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&&(Xe.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(){Xe.b.StartPerformanceCounter("Active meshes evaluation"),e._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(function(){Xe.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(){Xe.b.StartPerformanceCounter("Render targets rendering"),e._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(function(){Xe.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(){Xe.b.StartPerformanceCounter("Particles"),e._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(function(){Xe.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(){Xe.b.StartPerformanceCounter("Sprites"),e._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(function(){Xe.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(){Xe.b.StartPerformanceCounter("Physics"),e._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(function(){Xe.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(),Xe.b.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(function(){e._renderTime.endMonitoring(!1),Xe.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(),Xe.b.StartPerformanceCounter("Rendering camera "+n.name)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(function(n){e._cameraRenderTime.endMonitoring(!1),Xe.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}(),T_=`#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 -}`;ze.a.ShadersStore.glowMapGenerationVertexShader=E_;var ho=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 R.c,this.onBeforeRenderMainTextureObservable=new R.c,this.onBeforeComposeObservable=new R.c,this.onBeforeRenderMeshToEffect=new R.c,this.onAfterRenderMeshToEffect=new R.c,this.onAfterComposeObservable=new R.c,this.onSizeChangedObservable=new R.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 Oe.b(this._engine,t,Oe.b.PositionKind,!1,!1,2);this._vertexBuffers[Oe.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(Oe.b.MatricesIndicesExtraKind),a.push(Oe.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),et.a.PrepareAttributesForMorphTargetsInfluencers(a,s,ie)),e&&(o.push("#define INSTANCES"),et.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 Xe.b.Instantiate(t.customType).Parse(t,e,n)},r._SceneComponentInitialization=function(t){throw An.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}();U.a.AddParser(at.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}(),x_=` -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; -}`;ze.a.ShadersStore.layerPixelShader=x_;var C_=` -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); -}`;ze.a.ShadersStore.layerVertexShader=C_;var R_=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 R.c,this.onBeforeRenderObservable=new R.c,this.onAfterRenderObservable=new R.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(at.a.NAME_LAYER);a||(a=new Nu(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 Oe.b(s,d,Oe.b.PositionKind,!1,!1,2);this._vertexBuffers[Oe.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[Oe.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",[Oe.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[Oe.b.PositionKind];t&&(t.dispose(),this._vertexBuffers[Oe.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}(),wu=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}(),O_=` -varying vec2 vUV; -uniform sampler2D textureSampler; - -uniform vec4 color; -void main(void) { -vec4 baseColor=texture2D(textureSampler,vUV); -gl_FragColor=baseColor*color; -}`;ze.a.ShadersStore.lensFlarePixelShader=O_;var M_=` -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); -}`;ze.a.ShadersStore.lensFlareVertexShader=M_;var zs=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[Oe.b.PositionKind]=new Oe.b(i,o,Oe.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",[Oe.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,b=d-this._positionY;n.enableEffect(this._effect),n.setState(!1),n.setDepthBuffer(!1),n.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var x=0;x0);for(var n=0,i=e;n0)}},r}();zs._SceneComponentInitialization=function(r){var t=r._getComponent(at.a.NAME_LENSFLARESYSTEM);t||(t=new Fu(r),r._addComponent(t))};var I_=` - - - - -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); -} -`;ze.a.IncludesShadersStore.bayerDitherFunctions=I_;var D_=`#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 -`;ze.a.IncludesShadersStore.shadowMapFragmentDeclaration=D_;var L_=` 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;`;ze.a.IncludesShadersStore.shadowMapFragment=L_;var N_=`#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 -}`;ze.a.ShadersStore.shadowMapPixelShader=N_;var w_=`#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 -`;ze.a.IncludesShadersStore.shadowMapVertexDeclaration=w_;var F_=` -#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 -`;ze.a.IncludesShadersStore.shadowMapVertexNormalBias=F_;var B_=`#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 -`;ze.a.IncludesShadersStore.shadowMapVertexMetric=B_;var U_=` -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 -}`;ze.a.ShadersStore.shadowMapVertexShader=U_;var V_=` -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))); -}`;ze.a.ShadersStore.depthBoxBlurPixelShader=V_;var k_=`#if SM_SOFTTRANSPARENTSHADOW == 1 -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; -#endif -`;ze.a.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=k_;var Bu=new u.a,Uu=new u.a,kn=function(){function r(t,e,n){this.onBeforeShadowMapRenderObservable=new R.c,this.onAfterShadowMapRenderObservable=new R.c,this.onBeforeShadowMapRenderMeshObservable=new R.c,this.onAfterShadowMapRenderMeshObservable=new R.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=$r.b.MIN_RENDERINGGROUPS;o<$r.b.MAX_RENDERINGGROUPS;o++)this._shadowMap.setRenderingAutoClearDepthStencil(o,!1)}},r.prototype._initializeBlurRTTAndPostProcesses=function(){var t=this,e=this._scene.getEngine(),n=this._mapSize/this.blurScale;this.useKernelBlur&&this.blurScale===1||(this._shadowMap2=new sn(this._light.name+"_shadowMap2",n,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=we.a.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=we.a.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(we.a.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new _n(this._light.name+"KernelBlurX",new u.d(1,0),this.blurKernel,1,null,we.a.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=n,this._kernelBlurXPostprocess.height=n,this._kernelBlurXPostprocess.onApplyObservable.add(function(i){i.setTexture("textureSampler",t._shadowMap)}),this._kernelBlurYPostprocess=new _n(this._light.name+"KernelBlurY",new u.d(0,1),this.blurKernel,1,null,we.a.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===h.a.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new _t(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,we.a.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add(function(i){i.setFloat2("screenSize",n,n),i.setTexture("textureSampler",t._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},r.prototype._renderForShadowMap=function(t,e,n,i){var o,a=this._scene.getEngine(),s=a.getColorWrite();if(i.length){for(a.setColorWrite(!1),o=0;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(Oe.b.NormalKind)?"1":"0")),n.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Pi.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=[Oe.b.PositionKind],d=t.getMesh();if(this.normalBias&&d.isVerticesDataPresent(Oe.b.NormalKind)&&(s.push(Oe.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(Oe.b.UVKind)&&(s.push(Oe.b.UVKind),a.push("#define UV1")),d.isVerticesDataPresent(Oe.b.UV2Kind)&&p.coordinatesIndex===1&&(s.push(Oe.b.UV2Kind),a.push("#define UV2"))}}var b=new Sr.a;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){s.push(Oe.b.MatricesIndicesKind),s.push(Oe.b.MatricesWeightsKind),d.numBoneInfluencers>4&&(s.push(Oe.b.MatricesIndicesExtraKind),s.push(Oe.b.MatricesWeightsExtraKind));var x=d.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&b.addCPUSkinningFallback(0,d),x.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(x.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");var O=d.morphTargetManager,B=0;O&&O.numInfluencers>0&&(a.push("#define MORPHTARGETS"),B=O.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+B),et.a.PrepareAttributesForMorphTargetsInfluencers(s,d,B));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"),et.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 -}`;ze.a.ShadersStore.depthPixelShader=G_;var z_=` -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 -} -`;ze.a.ShadersStore.depthVertexShader=z_;var aa=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 b=p.getRenderingMesh(),x=p.getEffectiveMesh(),O=o._scene,B=O.getEngine(),F=p.getMaterial();if(x._internalAbstractMeshDataInfo._isActiveIntermediate=!1,F&&p.verticesCount!==0&&p._renderId!==O.getRenderId()){B.setState(F.backFaceCulling,0,!1,O.useRightHandedSystem);var z=b._getInstancesRenderList(p._id,!!p.getReplacementMesh());if(!z.mustReturn){var J=B.getCaps().instancedArrays&&(z.visibleInstances[p._id]!==null&&z.visibleInstances[p._id]!==void 0||b.hasThinInstances),ie=o._camera||O.activeCamera;if(o.isReady(p,J)&&ie){if(p._renderId=O.getRenderId(),B.enableEffect(o._effect),b._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()))}b.useBones&&b.computeBonesUsingShaders&&b.skeleton&&o._effect.setMatrices("mBones",b.skeleton.getTransformMatrices(b)),et.a.BindMorphTargetParameters(b,o._effect),b._processRendering(x,p,o._effect,F.fillMode,z,J,function(ce,ue){return o._effect.setMatrix("world",ue)})}}}};this._depthMap.customRenderFunction=function(p,b,x,O){var B;if(O.length){for(a.setColorWrite(!1),B=0;B4&&(o.push(Oe.b.MatricesIndicesExtraKind),o.push(Oe.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),et.a.PrepareAttributesForMorphTargetsInfluencers(o,a,d)),e&&(i.push("#define INSTANCES"),et.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 An.a.WarnImport("DepthRendererSceneComponent")},r}(),j_=`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 -`;ze.a.ShadersStore.minmaxReduxPixelShader=j_;var Vu=function(){function r(t){this.onAfterReductionPerformed=new R.c,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=t,this._postProcessManager=new hs.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,B){return function(F){F.setTexture("sourceTexture",o._sourceTexture),F.setFloatArray2("texSize",new Float32Array([O,B]))}}(d,p),this._reductionSteps.push(s);for(var b=1;d>1||p>1;){d=Math.max(Math.round(d/2),1),p=Math.max(Math.round(p/2),1);var x=new _t("Reduction phase "+b,"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);x.autoClear=!1,x.forceFullscreenViewport=i,x.onApply=function(O,B){return function(F){O==1||B==1?F.setIntArray2("texSize",new Int32Array([O,B])):F.setFloatArray2("texSize",new Float32Array([O,B]))}}(d,p),this._reductionSteps.push(x),b++,d==1&&p==1&&x.onAfterRenderObservable.add(function(O,B,F){var z=new Float32Array(4*O*B),J={min:0,max:0};return function(){a.getEngine()._readTexturePixels(F.inputTexture,O,B,-1,0,z),J.min=z[0],J.max=z[1],o.onAfterReductionPerformed.notifyObservers(J)}}(d,p,x))}}},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,b=d/s,x=0;xMath.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 b=Math.round(d*i);b<0?b=0:b>=i&&(b=i-1);var x=i-b-1;return{r:e[x*n*3+3*p+0],g:e[x*n*3+3*p+1],b:e[x*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}(),Wu=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 Xs.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,b=e.dataPosition,x=0,O=0,B=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[b++],i=t[b++],o=t[b++],a=t[b++],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(x=0,B=0;B<4;B++)for(O=(B+1)*p;x128){if((s=n-128)==0||s>O-x)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)z[x++]=i}else{if((s=n)==0||s>O-x)throw"HDR Bad Format, bad scanline data (non-run)";if(z[x++]=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); -}`;ze.a.ShadersStore.hdrFilteringPixelShader=X_;var Ku=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 Ku(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=Wu.GetCubeMapTextureData(a,e._size);if(e._generateHarmonics){var d=Ho.ConvertCubeMapToSphericalPolynomial(s);e.sphericalPolynomial=d}for(var p=[],b=null,x=0;x<6;x++){if(!n.getCaps().textureFloat){var O=new ArrayBuffer(e._size*e._size*3);b=new Uint8Array(O)}var B=s[t._facesMapping[x]];if(e.gammaSpace||b){for(var F=0;F255){var ce=255/se;z*=ce,J*=ce,ie*=ce}b[3*F+0]=z,b[3*F+1]=J,b[3*F+2]=ie}}b?p.push(b):p.push(B)}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}(Wn.a);C.a.RegisteredTypes["BABYLON.HDRCubeTexture"]=sa;var Qu=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 R.c,this._onDataLayoutChanged=new R.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(b){return!!b.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,b=t,x=this.bodies,O=0;O!==x.length;O++){var B=x[O];B.type!==e.Body.STATIC&&B.sleepState!==e.Body.SLEEPING?(B.position.vsub(B.previousPosition,b),b.scale(p,b),B.position.vadd(b,B.interpolatedPosition)):(B.interpolatedPosition.set(B.position.x,B.position.y,B.position.z),B.interpolatedQuaternion.set(B.quaternion.x,B.quaternion.y,B.quaternion.z,B.quaternion.w))}}}},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}();Ir.DefaultPluginFactory=function(){return new Ks};var qu=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 Ys}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,Ir.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 b=a.toEulerAngles(),x=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 B=d.object.position.clone();n.posShape.push(B.x),n.posShape.push(B.y),n.posShape.push(B.z),n.rotShape.push(57.29577951308232*b.x,57.29577951308232*b.y,57.29577951308232*b.z)}switch(d.object.rotationQuaternion.copyFrom(a),d.type){case xt.a.ParticleImpostor:l.a.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case xt.a.SphereImpostor:var F=x.x,z=x.y,J=x.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 xt.a.CylinderImpostor:var se=o(x.x)/2,ce=o(x.y);n.type.push("cylinder"),n.size.push(se),n.size.push(ce),n.size.push(ce);break;case xt.a.PlaneImpostor:case xt.a.BoxImpostor:default:se=o(x.x),ce=o(x.y);var ue=o(x.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}(),la=f(97),Zu=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 Ys,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,b=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(Oe.b.PositionKind);s||(s=[]),n.computeWorldMatrix(!1);for(var d=a.length/3,p=0;p0){if(t.type!=xt.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 xt.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 b=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(b,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(a.x/2,a.y/2,a.z/2))}break;case xt.a.CapsuleImpostor:i=new this.bjsAMMO.btCapsuleShape(a.x/2,a.y/2);break;case xt.a.CylinderImpostor:this._tmpAmmoVectorA.setValue(a.x/2,a.y/2,a.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case xt.a.PlaneImpostor:case xt.a.BoxImpostor:this._tmpAmmoVectorA.setValue(a.x/2,a.y/2,a.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case xt.a.MeshImpostor:if(t.getParam("mass")==0){var x=new this.bjsAMMO.btTriangleMesh;t._pluginData.toDispose.push(x);var O=this._addMeshVerts(x,o,o);i=O==0?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(x);break}case xt.a.ConvexHullImpostor:var B=new this.bjsAMMO.btConvexHullShape;(O=this._addHullVerts(B,o,o))==0?(t._pluginData.toDispose.push(B),i=new this.bjsAMMO.btCompoundShape):i=B;break;case xt.a.NoImpostor:i=new this.bjsAMMO.btSphereShape(a.x/2);break;case xt.a.CustomImpostor:i=this._createCustom(t);break;case xt.a.SoftbodyImpostor:i=this._createSoftbody(t);break;case xt.a.ClothImpostor:i=this._createCloth(t);break;case xt.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===xt.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}();U.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},U.a.prototype.addReflectionProbe=function(r){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(r)};var Ju=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 Xe.b.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},th=function(r,t,e,n,i){i===void 0&&(i=!1);var o=new xn(r),a="importScene has failed JSON parse";try{var s=JSON.parse(t);a="";var d,p,b=Ut.loggingLevel===Ut.DETAILED_LOGGING;if(s.environmentTexture!==void 0&&s.environmentTexture!==null){var x=s.isPBR===void 0||s.isPBR;if(s.environmentTextureType&&s.environmentTextureType==="BABYLON.HDRCubeTexture"){var O=s.environmentTextureSize?s.environmentTextureSize:128,B=new sa((s.environmentTexture.match(/https?:\/\//g)?"":e)+s.environmentTexture,r,O,!0,!x);s.environmentTextureRotationY&&(B.rotationY=s.environmentTextureRotationY),r.environmentTexture=B}else if(Qn.a.EndsWith(s.environmentTexture,".env")){var F=new oi((s.environmentTexture.match(/https?:\/\//g)?"":e)+s.environmentTexture,r);s.environmentTextureRotationY&&(F.rotationY=s.environmentTextureRotationY),r.environmentTexture=F}else{var z=oi.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,x,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 Gn=0;Gn-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,b=null,x=s.split(` -`),O=0,B=0,F=0,z=0,J=0,ie=0;ie0&&(ie+1)%4==0)p[ie]=255;else{var Te=b[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}(Wn.a);C.a.RegisteredTypes["BABYLON.ColorGradingTexture"]=ah;var sh=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?Xe.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=Xs.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,b,x,O,B,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:b=0,O=1,z=i.width,x=0,B=1,F=i.height;break;case r._ORIGIN_BL:b=0,O=1,z=i.width,x=i.height-1,B=-1,F=-1;break;case r._ORIGIN_UR:b=i.width-1,O=-1,z=-1,x=0,B=1,F=i.height;break;case r._ORIGIN_BR:b=i.width-1,O=-1,z=-1,x=i.height-1,B=-1,F=-1}var Te=r["_getImageData"+(d?"Grey":"")+i.pixel_size+"bits"](i,p,o,x,B,F,b,O,z);t.getEngine()._uploadDataToTextureDirectly(t,Te)}}},r._getImageData8bits=function(t,e,n,i,o,a,s,d,p){var b,x,O,B=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(x=s;x!==p;x+=d,ie++)b=B[ie],se[4*(x+z*O)+3]=255,se[4*(x+z*O)+2]=F[3*b+0],se[4*(x+z*O)+1]=F[3*b+1],se[4*(x+z*O)+0]=F[3*b+2];return se},r._getImageData16bits=function(t,e,n,i,o,a,s,d,p){var b,x,O,B=n,F=t.width,z=t.height,J=0,ie=new Uint8Array(F*z*4);for(O=i;O!==a;O+=o)for(x=s;x!==p;x+=d,J+=2){var se=255*((31744&(b=B[J+0]+(B[J+1]<<8)))>>10)/31|0,ce=255*((992&b)>>5)/31|0,ue=255*(31&b)/31|0;ie[4*(x+F*O)+0]=se,ie[4*(x+F*O)+1]=ce,ie[4*(x+F*O)+2]=ue,ie[4*(x+F*O)+3]=32768&b?0:255}return ie},r._getImageData24bits=function(t,e,n,i,o,a,s,d,p){var b,x,O=n,B=t.width,F=t.height,z=0,J=new Uint8Array(B*F*4);for(x=i;x!==a;x+=o)for(b=s;b!==p;b+=d,z+=3)J[4*(b+B*x)+3]=255,J[4*(b+B*x)+2]=O[z+0],J[4*(b+B*x)+1]=O[z+1],J[4*(b+B*x)+0]=O[z+2];return J},r._getImageData32bits=function(t,e,n,i,o,a,s,d,p){var b,x,O=n,B=t.width,F=t.height,z=0,J=new Uint8Array(B*F*4);for(x=i;x!==a;x+=o)for(b=s;b!==p;b+=d,z+=4)J[4*(b+B*x)+2]=O[z+0],J[4*(b+B*x)+1]=O[z+1],J[4*(b+B*x)+0]=O[z+2],J[4*(b+B*x)+3]=O[z+3];return J},r._getImageDataGrey8bits=function(t,e,n,i,o,a,s,d,p){var b,x,O,B=n,F=t.width,z=t.height,J=0,ie=new Uint8Array(F*z*4);for(O=i;O!==a;O+=o)for(x=s;x!==p;x+=d,J++)b=B[J],ie[4*(x+F*O)+0]=b,ie[4*(x+F*O)+1]=b,ie[4*(x+F*O)+2]=b,ie[4*(x+F*O)+3]=255;return ie},r._getImageDataGrey16bits=function(t,e,n,i,o,a,s,d,p){var b,x,O=n,B=t.width,F=t.height,z=0,J=new Uint8Array(B*F*4);for(x=i;x!==a;x+=o)for(b=s;b!==p;b+=d,z+=2)J[4*(b+B*x)+0]=O[z+0],J[4*(b+B*x)+1]=O[z+0],J[4*(b+B*x)+2]=O[z+0],J[4*(b+B*x)+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}(),ch=function(){function r(){this.supportCascades=!1}return r.prototype.canLoad=function(t){return Qn.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=da.GetTGAHeader(i);n(o.width,o.height,e.generateMipMaps,!1,function(){da.UploadContent(e,i)})},r}();Ue.a._TextureLoaders.push(new ch);var fo,Z_=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"})(fo||(fo={}));var po=function(){function r(){}return r.GetInternalFormatFromBasisFormat=function(t){if(t===fo.cTFETC1)return 36196;if(t===fo.cTFBC1)return 33776;if(t===fo.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):Xe.b.LoadFileAsync(r.WasmModuleURL).then(function(n){var i=URL.createObjectURL(new Blob(["("+J_+")()"],{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(b){b.data.action==="transcode"&&b.data.id===s&&(n._Worker.removeEventListener("message",d),b.data.success?o(b.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 Ct.a(i,Ct.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)&&(Xe.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[Ae>>4&3],se[Ee++]=ie[Ae>>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),b=function(fe){for(var ve=fe.getHasAlpha(),Te=fe.getNumImages(),Re=[],Ae=0;Ae1&&e.generateMipMaps;po.LoadTextureFromTranscodeResult(e,d),e.getEngine()._setCubeMapTextureParams(e,p),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),i&&i()}).catch(function(d){Xe.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}};po.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(){po.LoadTextureFromTranscodeResult(e,a)})}).catch(function(a){Xe.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 lh);var qs=function(r){function t(e,n,i,o,a){var s=this,d=!(!a||!a.generateMipMaps)&&a.generateMipMaps,p=!(!a||!a.generateDepthTexture)&&a.generateDepthTexture,b=!a||a.doNotChangeAspectRatio===void 0||a.doNotChangeAspectRatio;if((s=r.call(this,e,n,o,d,b)||this).isSupported){var x=[],O=[];s._initTypes(i,x,O,a);var B=!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:B,generateStencilBuffer:F,generateDepthTexture:p,types:x,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),Zs=function(r,t,e){this.id=r,this.scale=t,this.offset=e},$_=function(){function r(t,e,n,i){var o,a,s,d,p,b,x,O,B,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:Oe.b.UVKind,this.options.uvsOut=(s=this.options.uvsOut)!==null&&s!==void 0?s:Oe.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=(b=this.options.updateInputMeshes)===null||b===void 0||b,this.options.disposeSources=(x=this.options.disposeSources)===null||x===void 0||x,this._expecting=0,this.options.fillBlanks=(O=this.options.fillBlanks)===null||O===void 0||O,this.options.fillBlanks===!0&&(this.options.customFillColor=(B=this.options.customFillColor)!==null&&B!==void 0?B:"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}(),em=` -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); -}`;ze.a.ShadersStore.proceduralVertexShader=em;var _o=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 b=r.call(this,null,o,!s)||this;b.isEnabled=!0,b.autoClear=!0,b.onGeneratedObservable=new R.c,b.onBeforeGenerationObservable=new R.c,b.nodeMaterialSource=null,b._textures={},b._currentRefreshId=-1,b._frameId=-1,b._refreshRate=1,b._vertexBuffers={},b._uniforms=new Array,b._samplers=new Array,b._floats={},b._ints={},b._floatsArrays={},b._colors3={},b._colors4={},b._vectors2={},b._vectors3={},b._matrices={},b._fallbackTextureUsed=!1,b._cachedDefines="",b._contentUpdateId=-1;var x=(o=b.getScene()||te.a.LastCreatedScene)._getComponent(at.a.NAME_PROCEDURALTEXTURE);x||(x=new uh(o),o._addComponent(x)),o.proceduralTextures.push(b),b._fullEngine=o.getEngine(),b.name=e,b.isRenderTarget=!0,b._size=n,b._generateMipMaps=s,b.setFragment(i),b._fallbackTexture=a,d?(b._texture=b._fullEngine.createRenderTargetCubeTexture(n,{generateMipMaps:s,generateDepthBuffer:!1,generateStencilBuffer:!1,type:p}),b.setFloat("face",0)):b._texture=b._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),b._vertexBuffers[Oe.b.PositionKind]=new Oe.b(b._fullEngine,O,Oe.b.PositionKind,!1,!1,2),b._createIndexBuffer(),b}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[Oe.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,[Oe.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[Oe.b.PositionKind];i&&(i.dispose(),this._vertexBuffers[Oe.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);C.a.RegisteredTypes["BABYLON.ProceduralTexture"]=_o;var tm=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===Ce.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}(),sm=f(152),pt=function(){function r(t,e,n,i){e===void 0&&(e=Ce.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=sm.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)==0&&(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 fa(t,this,Tn.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 fa(t,this,Tn.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===Ce.Vertex&&t.target!==Ce.VertexAndFragment;if(o&&((t.target&t._buildTarget)==0||(t.target&n.target)==0||this.target!==Ce.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=ze.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]=ze.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&Ce.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&Ce.Fragment)!=0&&this._addFragmentOutputNode(e),this},t.prototype.removeOutputNode=function(e){return e.target===null||((e.target&Ce.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&Ce.Fragment)!=0&&this._removeFragmentOutputNode(e)),this},t.prototype._addVertexOutputNode=function(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=Ce.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=Ce.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===Mn.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 dh,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=Ce.Vertex,this._fragmentCompilationState=new dh,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=Ce.Fragment,this._sharedData=new cm,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);C.a.RegisteredTypes["BABYLON.BonesBlock"]=mh;var gh=function(r){function t(e){var n=r.call(this,e,Ce.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);C.a.RegisteredTypes["BABYLON.InstancesBlock"]=gh;var vh=function(r){function t(e){var n=r.call(this,e,Ce.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&&et.a.PrepareDefinesForMorphTargets(e,i)},t.prototype.bind=function(e,n,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&et.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,b=this.positionOutput,x=this.normalOutput,O=this.tangentOutput,B=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;et.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?et.a.BindLight(this.light,this._lightId,o,e,!0):et.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===Ce.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);C.a.RegisteredTypes["BABYLON.LightBlock"]=Rh;var Oh=function(r){function t(e,n){n===void 0&&(n=!1);var i=r.call(this,e,n?Ce.Fragment:Ce.VertexAndFragment)||this;return i.convertToGammaSpace=!1,i.convertToLinearSpace=!1,i._fragmentOnly=n,i.registerInput("uv",le.Vector2,!1,Ce.VertexAndFragment),i.registerOutput("rgba",le.Color4,Ce.Neutral),i.registerOutput("rgb",le.Color3,Ce.Neutral),i.registerOutput("r",le.Float,Ce.Neutral),i.registerOutput("g",le.Float,Ce.Neutral),i.registerOutput("b",le.Float,Ce.Neutral),i.registerOutput("a",le.Float,Ce.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 Ce.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return Ce.VertexAndFragment;for(var e=this.uv.connectedPoint;e;){if(e.target===Ce.Fragment)return Ce.Fragment;if(e.target===Ce.Vertex)return Ce.VertexAndFragment;if(e.target===Ce.Neutral||e.target===Ce.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&&ut.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};et.a.PrepareDefinesForLight(a,e,this.light,this._lightId,i,!0,s),s.needRebuild&&i.rebuild()}else et.a.PrepareDefinesForLights(a,e,i,!0,n.maxSimultaneousLights),i._needNormals=!0,et.a.PrepareDefinesForMultiview(a,i)}},t.prototype.updateUniformsAndSamples=function(e,n,i,o){for(var a=0;a=0;et.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?et.a.BindLight(this.light,this._lightId,s,e,!0):et.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 b=(a=(o=this.indexOfRefraction.connectInputBlock)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:1.5,x=Math.pow((b-1)/(b+1),2);this._metallicReflectanceColor.scaleToRef(x*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,b,x,O,B,F,z,J,ie,se,ce,ue,fe,ve,Te,Re,Ae,Ee,Se,Le,xe,Ne,Me,Fe,Ye,tt,it,lt,Ke,ot,rt,qe,ht;r.prototype._buildBlock.call(this,e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=ta.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!==Ce.Fragment)return this._injectVertexCode(e),this;e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);var Je="//"+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",Je,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",Je,{repeatKey:"maxSimultaneousLights"}),e._emitFunctionFromInclude("helperFunctions",Je),e._emitFunctionFromInclude("importanceSampling",Je),e._emitFunctionFromInclude("pbrHelperFunctions",Je),e._emitFunctionFromInclude("imageProcessingFunctions",Je),e._emitFunctionFromInclude("shadowsFragmentFunctions",Je,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",Je,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",Je),e._emitFunctionFromInclude("pbrBRDFFunctions",Je,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i=Ve?._defineSkyboxName)!==null&&i!==void 0?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",Je),e._emitFunctionFromInclude("pbrDirectLightingFunctions",Je,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",Je),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",Je),e._emitFunctionFromInclude("pbrBlockReflectivity",Je),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",Je),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",Je),e._emitFunctionFromInclude("pbrBlockAnisotropic",Je),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",Je,{replaceStrings:[{search:/vPositionW/g,replace:yt+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",Je),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",Je),e.compilationString+=`#ifdef UNLIT - vec3 diffuseBase = vec3(1., 1., 1.); - #else\r -`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",Je,{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",Je,{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:(b=Ve?._defineProjectionName)!==null&&b!==void 0?b:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(x=Ve?._defineSkyboxName)!==null&&x!==void 0?x:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(O=Ve?._defineLODReflectionAlpha)!==null&&O!==void 0?O:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(B=Ve?._defineLinearSpecularReflection)!==null&&B!==void 0?B:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(F=Ve?._vReflectionFilteringInfoName)!==null&&F!==void 0?F:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",Je,{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",Je,{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+=ya.GetCode(e,vt,Ve,yt,Jt,Yt,this.worldNormal.associatedVariableName),Jt&&(Yt=(Te=vt?.worldTangent.isConnected)!==null&&Te!==void 0&&Te),e._emitFunctionFromInclude("pbrBlockClearcoat",Je,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(Re=Ve?._define3DName)!==null&&Re!==void 0?Re:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(Ae=Ve?._defineOppositeZ)!==null&&Ae!==void 0?Ae:"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",Je,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(Ne=Ve?._defineSkyboxName)!==null&&Ne!==void 0?Ne:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(Me=Ve?._define3DName)!==null&&Me!==void 0?Me:"REFLECTIONMAP_3D"}]});var Et=this.subsurface.isConnected?(Fe=this.subsurface.connectedPoint)===null||Fe===void 0?void 0:Fe.ownerBlock:null,Mt=this.subsurface.isConnected?(tt=((Ye=this.subsurface.connectedPoint)===null||Ye===void 0?void 0:Ye.ownerBlock).refraction.connectedPoint)===null||tt===void 0?void 0:tt.ownerBlock:null;Mt&&(Mt.viewConnectionPoint=this.view,Mt.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Ta.GetCode(e,Et,Ve,yt),e._emitFunctionFromInclude("pbrBlockSubSurface",Je,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(it=Ve?._define3DName)!==null&&it!==void 0?it:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(lt=Ve?._defineOppositeZ)!==null&<!==void 0?lt:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(Ke=Ve?._defineProjectionName)!==null&&Ke!==void 0?Ke:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(ot=Mt?._define3DName)!==null&&ot!==void 0?ot:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(rt=Mt?._defineLODRefractionAlpha)!==null&&rt!==void 0?rt:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(qe=Mt?._defineLinearSpecularRefraction)!==null&&qe!==void 0?qe:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(ht=Mt?._defineOppositeZ)!==null&&ht!==void 0?ht:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",Je),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",Je,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",Je,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",Je),e.compilationString+=`#endif\r -`;var $t=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",Dn=pn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();Dn.indexOf(".")===-1&&(Dn+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",Je,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:$t+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:Dn}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",Je,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",Je,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",Je,{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 Gn=0,$n=this._outputs;Gn<$n.length;Gn++){var Ln=$n[Gn];if(Ln.hasEndpoints){var qt=um[Ln.name];if(qt){var ui=qt[0],xi=qt[1];xi&&(e.compilationString+="#if "+xi+`\r -`),e.compilationString+=this._declareOutput(Ln,e)+" = "+ui+`;\r -`,xi&&(e.compilationString+=`#else\r -`,e.compilationString+=this._declareOutput(Ln,e)+` = vec3(0.);\r -`,e.compilationString+=`#endif\r -`)}else console.error("There's no remapping for the "+Ln.name+" end point! No code generated")}}return this},t.prototype._dumpPropertiesCode=function(){var e="";return e+=this._codeVariableName+".lightFalloff = "+this.lightFalloff+`;\r -`,e+=this._codeVariableName+".useAlphaTest = "+this.useAlphaTest+`;\r -`,e+=this._codeVariableName+".alphaTestCutoff = "+this.alphaTestCutoff+`;\r -`,e+=this._codeVariableName+".useAlphaBlending = "+this.useAlphaBlending+`;\r -`,e+=this._codeVariableName+".useRadianceOverAlpha = "+this.useRadianceOverAlpha+`;\r -`,e+=this._codeVariableName+".useSpecularOverAlpha = "+this.useSpecularOverAlpha+`;\r -`,e+=this._codeVariableName+".enableSpecularAntiAliasing = "+this.enableSpecularAntiAliasing+`;\r -`,e+=this._codeVariableName+".realTimeFiltering = "+this.realTimeFiltering+`;\r -`,e+=this._codeVariableName+".realTimeFilteringQuality = "+this.realTimeFilteringQuality+`;\r -`,e+=this._codeVariableName+".useEnergyConservation = "+this.useEnergyConservation+`;\r -`,e+=this._codeVariableName+".useRadianceOcclusion = "+this.useRadianceOcclusion+`;\r -`,e+=this._codeVariableName+".useHorizonOcclusion = "+this.useHorizonOcclusion+`;\r -`,e+=this._codeVariableName+".unlit = "+this.unlit+`;\r -`,e+=this._codeVariableName+".forceNormalForward = "+this.forceNormalForward+`;\r -`,e+=this._codeVariableName+".debugMode = "+this.debugMode+`;\r -`,e+=this._codeVariableName+".debugLimit = "+this.debugLimit+`;\r -`,e+=this._codeVariableName+".debugFactor = "+this.debugFactor+`;\r -`},t.prototype.serialize=function(){var e=r.prototype.serialize.call(this);return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e},t.prototype._deserialize=function(e,n,i){var o,a;r.prototype._deserialize.call(this,e,n,i),e.lightId&&(this.light=n.getLightByID(e.lightId)),this.lightFalloff=(o=e.lightFalloff)!==null&&o!==void 0?o:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=(a=e.realTimeFilteringQuality)!==null&&a!==void 0?a:h.a.TEXTURE_FILTERING_QUALITY_LOW,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor},Object(c.c)([Vt("Direct lights",Lt.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"directIntensity",void 0),Object(c.c)([Vt("Environment lights",Lt.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"environmentIntensity",void 0),Object(c.c)([Vt("Specular highlights",Lt.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"specularIntensity",void 0),Object(c.c)([Vt("Light falloff",Lt.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:pn.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:pn.LIGHTFALLOFF_GLTF},{label:"Standard",value:pn.LIGHTFALLOFF_STANDARD}]})],t.prototype,"lightFalloff",void 0),Object(c.c)([Vt("Alpha Testing",Lt.Boolean,"OPACITY")],t.prototype,"useAlphaTest",void 0),Object(c.c)([Vt("Alpha CutOff",Lt.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"alphaTestCutoff",void 0),Object(c.c)([Vt("Alpha blending",Lt.Boolean,"OPACITY")],t.prototype,"useAlphaBlending",void 0),Object(c.c)([Vt("Radiance over alpha",Lt.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"useRadianceOverAlpha",void 0),Object(c.c)([Vt("Specular over alpha",Lt.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"useSpecularOverAlpha",void 0),Object(c.c)([Vt("Specular anti-aliasing",Lt.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"enableSpecularAntiAliasing",void 0),Object(c.c)([Vt("Realtime filtering",Lt.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"realTimeFiltering",void 0),Object(c.c)([Vt("Realtime filtering quality",Lt.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:h.a.TEXTURE_FILTERING_QUALITY_LOW},{label:"Medium",value:h.a.TEXTURE_FILTERING_QUALITY_MEDIUM},{label:"High",value:h.a.TEXTURE_FILTERING_QUALITY_HIGH}]})],t.prototype,"realTimeFilteringQuality",void 0),Object(c.c)([Vt("Energy Conservation",Lt.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useEnergyConservation",void 0),Object(c.c)([Vt("Radiance occlusion",Lt.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useRadianceOcclusion",void 0),Object(c.c)([Vt("Horizon occlusion",Lt.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useHorizonOcclusion",void 0),Object(c.c)([Vt("Unlit",Lt.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"unlit",void 0),Object(c.c)([Vt("Force normal forward",Lt.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"forceNormalForward",void 0),Object(c.c)([Vt("Debug mode",Lt.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],t.prototype,"debugMode",void 0),Object(c.c)([Vt("Split position",Lt.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],t.prototype,"debugLimit",void 0),Object(c.c)([Vt("Output factor",Lt.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],t.prototype,"debugFactor",void 0),t}(pt);C.a.RegisteredTypes["BABYLON.PBRMetallicRoughnessBlock"]=dd;var fd=function(r){function t(e){var n=r.call(this,e,Ce.Neutral)||this;return n.registerInput("left",le.AutoDetect),n.registerInput("right",le.AutoDetect),n.registerOutput("output",le.BasedOnInput),n._outputs[0]._typeConnectionSource=n._inputs[0],n._linkConnectionTypes(0,1),n}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"ModBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){r.prototype._buildBlock.call(this,e);var n=this._outputs[0];return e.compilationString+=this._declareOutput(n,e)+" = mod("+this.left.associatedVariableName+", "+this.right.associatedVariableName+`);\r -`,this},t}(pt);C.a.RegisteredTypes["BABYLON.ModBlock"]=fd;var hm=function(){function r(){}return r.prototype.optimize=function(t,e){},r}(),dm=f(120),fm=function(){function r(){this.mm=new Map}return r.prototype.get=function(t,e){var n=this.mm.get(t);if(n!==void 0)return n.get(e)},r.prototype.set=function(t,e,n){var i=this.mm.get(t);i===void 0&&this.mm.set(t,i=new Map),i.set(e,n)},r}(),pm=function(){function r(t,e,n){var i=this;this._baseMaterial=t,this._scene=e,this._options=n,this._subMeshToEffect=new Map,this._subMeshToDepthEffect=new fm,this._meshes=new Map;var o=t.getClassName()==="NodeMaterial"?"u_":"";if(o){this._matriceNames={world:o+"World",view:o+"View",projection:o+"Projection",viewProjection:o+"ViewProjection",worldView:o+"WorldxView",worldViewProjection:o+"WorldxViewxProjection"};for(var a=t.getInputBlocks(),s=0;s("+this._options.remappedVariables.join(",")+")":ze.a.IncludesShadersStore.shadowMapVertexNormalBias,x=this._options&&this._options.remappedVariables?"#include("+this._options.remappedVariables.join(",")+")":ze.a.IncludesShadersStore.shadowMapVertexMetric,O=this._options&&this._options.remappedVariables?"#include("+this._options.remappedVariables.join(",")+")":ze.a.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow,B=ze.a.IncludesShadersStore.shadowMapFragment;d=(d=(d=(d=d.replace(/void\s+?main/g,ze.a.IncludesShadersStore.shadowMapVertexDeclaration+`\r -void main`)).replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,b)).indexOf("#define SHADOWDEPTH_METRIC")!==-1?d.replace(/#define SHADOWDEPTH_METRIC/g,x):d.replace(/}\s*$/g,x+`\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,ze.a.IncludesShadersStore.shadowMapFragmentDeclaration+`\r -void main`),z?p=p.replace(/#define SHADOWDEPTH_FRAGMENT/g,B):J+=B+`\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}(),pd=f(101);function bc(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 b=3*a.num_faces(),x=4*b,O=r._malloc(x);try{d.GetTrianglesUInt32Array(a,x,O);var B=new Uint32Array(b);B.set(new Uint32Array(r.HEAPF32.buffer,O,b)),n(B)}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,Re=r._malloc(Te);try{d.GetAttributeDataArrayForAllPoints(a,ce,r.DT_FLOAT32,Te,Re);var Ae=new Float32Array(r.HEAPF32.buffer,Re,ve);if(se==="color"&&ue===3){for(var Ee=new Float32Array(4*fe),Se=0,Le=0;Ser.EPSILON?1:0;d|=b,p.push(b)}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 x,O=[],B=[];for(a=0;a=3&&(x=new yc(O,t.shared)).plane&&i.push(x),B.length>=3&&(x=new yc(B,t.shared)).plane&&o.push(x)}},r.EPSILON=1e-5,r}(),yc=function(){function r(t,e){this.vertices=t,this.shared=e,this.plane=vm.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}(),Jn=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||dt.a.DEFAULTSIDE;t.push(0,0,0),i.push(.5,.5);for(var p=2*Math.PI*s,b=s===1?p/a:p/(a-1),x=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}(),Sm=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 x=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(b=0;ba.elements.length-1?a.elements[0]:a.elements[x+1],t.push(B.x,0,B.y),t.push(B.x,-s,B.y),t.push(O.x,0,O.y),t.push(O.x,-s,O.y);var F=new u.e(B.x,0,B.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(b/o.width,0),n.push(b/o.width,1),b+=z.length(),n.push(b/o.width,0),n.push(b/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}();dt.a.CreatePolygon=function(r,t,e,n,i,o,a){for(var s=e||new Array(3),d=n,p=[],b=a||!1,x=0;x<3;x++)s[x]===void 0&&(s[x]=new u.f(0,0,1,1)),d&&d[x]===void 0&&(d[x]=new M.b(1,1,1,1));var O=r.getVerticesData(Oe.b.PositionKind),B=r.getVerticesData(Oe.b.NormalKind),F=r.getVerticesData(Oe.b.UVKind),z=r.getIndices(),J=O.length/9,ie=0,se=0,ce=0,ue=0,fe=[0];if(b)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,b=e.clip||0,x=e.updatable,O=De.a._GetDefaultSideOrientation(e.sideOrientation),B=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-b;ie++){for(ue=[],B!=De.a.CAP_START&&B!=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||x>0){switch(J=-O,ie=-B,se=O,ce=B,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-=x/=2,ce+=x;break;case De.a.BOTTOM:ce+=x,z=-x/2;break;case De.a.TOP:ie-=x,z=x/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=[],Re=[],Ae=[],Ee=0,Se=0;Se0||x>0){var xe,Ne,Me,Fe,Ye=x>0&&(o===De.a.CENTER||o===De.a.TOP),tt=x>0&&(o===De.a.CENTER||o===De.a.BOTTOM),it=d>0&&(i===De.a.CENTER||i===De.a.RIGHT),lt=d>0&&(i===De.a.CENTER||i===De.a.LEFT),Ke=[];if(Ye&&it&&(ue.push(J+F,ie+z,0),ue.push(-O+F,ie+z,0),ue.push(-O+F,ie+x+z,0),ue.push(J+F,ie+x+z,0),Ae.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,Ke=[xe=1-d/e,Ne=1-x/n,Me=1,Ne,Me,Fe=1,xe,Fe],t===De.a.ROTATE_ROW&&(Ke=[1-xe,1-Ne,1-Me,1-Ne,1-Me,1-Fe,1-xe,1-Fe]),t===De.a.FLIP_ROW&&(Ke=[1-xe,Ne,1-Me,Ne,1-Me,Fe,1-xe,Fe]),t===De.a.FLIP_N_ROTATE_ROW&&(Ke=[xe,1-Ne,Me,1-Ne,Me,1-Fe,xe,1-Fe]),Te=Te.concat(Ke),Re.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)),Ye&<&&(ue.push(O+F,ie+z,0),ue.push(se+F,ie+z,0),ue.push(se+F,ie+x+z,0),ue.push(O+F,ie+x+z,0),Ae.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,Ke=[xe=0,Ne=1-x/n,Me=d/e,Ne,Me,Fe=1,xe,Fe],(t===De.a.ROTATE_ROW||t===De.a.ROTATE_TILE&&s%2==0)&&(Ke=[1-xe,1-Ne,1-Me,1-Ne,1-Me,1-Fe,1-xe,1-Fe]),(t===De.a.FLIP_ROW||t===De.a.FLIP_TILE&&s%2==0)&&(Ke=[1-xe,Ne,1-Me,Ne,1-Me,Fe,1-xe,Fe]),(t===De.a.FLIP_N_ROTATE_ROW||t===De.a.FLIP_N_ROTATE_TILE&&s%2==0)&&(Ke=[xe,1-Ne,Me,1-Ne,Me,1-Fe,xe,1-Fe]),Te=Te.concat(Ke),Re.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)),tt&&it&&(ue.push(J+F,B+z,0),ue.push(-O+F,B+z,0),ue.push(-O+F,ce+z,0),ue.push(J+F,ce+z,0),Ae.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,Ke=[xe=1-d/e,Ne=0,Me=1,Ne,Me,Fe=x/n,xe,Fe],(t===De.a.ROTATE_ROW&&b%2==1||t===De.a.ROTATE_TILE&&b%1==0)&&(Ke=[1-xe,1-Ne,1-Me,1-Ne,1-Me,1-Fe,1-xe,1-Fe]),(t===De.a.FLIP_ROW&&b%2==1||t===De.a.FLIP_TILE&&b%2==0)&&(Ke=[1-xe,Ne,1-Me,Ne,1-Me,Fe,1-xe,Fe]),(t===De.a.FLIP_N_ROTATE_ROW&&b%2==1||t===De.a.FLIP_N_ROTATE_TILE&&b%2==0)&&(Ke=[xe,1-Ne,Me,1-Ne,Me,1-Fe,xe,1-Fe]),Te=Te.concat(Ke),Re.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)),tt&<&&(ue.push(O+F,B+z,0),ue.push(se+F,B+z,0),ue.push(se+F,ce+z,0),ue.push(O+F,ce+z,0),Ae.push(Ee,Ee+1,Ee+3,Ee+1,Ee+2,Ee+3),Ee+=4,Ke=[xe=0,Ne=0,Me=d/e,Ne,Me,Fe=x/n,xe,Fe],(t===De.a.ROTATE_ROW&&b%2==1||t===De.a.ROTATE_TILE&&(b+s)%2==1)&&(Ke=[1-xe,1-Ne,1-Me,1-Ne,1-Me,1-Fe,1-xe,1-Fe]),(t===De.a.FLIP_ROW&&b%2==1||t===De.a.FLIP_TILE&&(b+s)%2==1)&&(Ke=[1-xe,Ne,1-Me,Ne,1-Me,Fe,1-xe,Fe]),(t===De.a.FLIP_N_ROTATE_ROW&&b%2==1||t===De.a.FLIP_N_ROTATE_TILE&&(b+s)%2==1)&&(Ke=[xe,1-Ne,Me,1-Ne,Me,1-Fe,xe,1-Fe]),Te=Te.concat(Ke),Re.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)),Ye){var ot=[];for(xe=0,Ne=1-x/n,Me=1,Fe=1,ot[0]=[xe,Ne,Me,Ne,Me,Fe,xe,Fe],ot[1]=[xe,Ne,Me,Ne,Me,Fe,xe,Fe],t!==De.a.ROTATE_TILE&&t!==De.a.ROTATE_ROW||(ot[1]=[1-xe,1-Ne,1-Me,1-Ne,1-Me,1-Fe,1-xe,1-Fe]),t!==De.a.FLIP_TILE&&t!==De.a.FLIP_ROW||(ot[1]=[1-xe,Ne,1-Me,Ne,1-Me,Fe,1-xe,Fe]),t!==De.a.FLIP_N_ROTATE_TILE&&t!==De.a.FLIP_N_ROTATE_ROW||(ot[1]=[xe,1-Ne,Me,1-Ne,Me,1-Fe,xe,1-Fe]),Le=0;Le1)?1:e.arc||1;var B,F,z=function(ce,ue,fe,ve,Te,Re,Ae,Ee){for(var Se,Le,xe,Ne,Me=ue.getTangents(),Fe=ue.getNormals(),Ye=ue.getDistances(),tt=2*Math.PI/Te*Ee,it=Re||function(){return ve},lt=u.c.Matrix[0],Ke=Ae===De.a.NO_CAP||Ae===De.a.CAP_END?0:2,ot=0;ot3?0:p,e.arc);var se=Eo.a.CreateRibbon(t,{pathArray:F,closePath:!0,closeArray:!1,updatable:x,sideOrientation:O,invertUV:b,frontUVs:e.frontUVs,backUVs:e.backUVs},n);return se._creationDataStorage.pathArray=F,se._creationDataStorage.path3D=B,se._creationDataStorage.tessellation=s,se._creationDataStorage.cap=p,se._creationDataStorage.arc=e.arc,se._creationDataStorage.radius=a,se},r}();dt.a.CreateIcoSphere=function(r){var t,e=r.sideOrientation||dt.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,b=[-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],x=[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],B=[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=x[3*ve+t];ue[t].copyFromFloats(b[3*O[Te]],b[3*O[Te]+1],b[3*O[Te]+2]),ue[t].normalize().scaleInPlace(n),fe[t].copyFromFloats(B[2*Te]*(138/1024)+60/1024+F[ve]*(-40/1024),B[2*Te+1]*(239/1024)+26/1024+F[ve]*(20/1024))}for(var Re=function(Le,xe,Ne,Me){var Fe,Ye=u.e.Lerp(ue[0],ue[2],xe/o),tt=u.e.Lerp(ue[1],ue[2],xe/o),it=o===xe?ue[2]:u.e.Lerp(Ye,tt,Le/(o-xe));if(it.normalize(),i){var lt=u.e.Lerp(ue[0],ue[2],Me/o),Ke=u.e.Lerp(ue[1],ue[2],Me/o);Fe=u.e.Lerp(lt,Ke,Ne/(o-Me))}else Fe=new u.e(it.x,it.y,it.z);Fe.x/=a,Fe.y/=s,Fe.z/=d,Fe.normalize();var ot=u.d.Lerp(fe[0],fe[2],xe/o),rt=u.d.Lerp(fe[1],fe[2],xe/o),qe=o===xe?fe[2]:u.d.Lerp(ot,rt,Le/(o-xe));J.push(it.x*a,it.y*s,it.z*d),ie.push(Fe.x,Fe.y,Fe.z),se.push(qe.x,qe.y),z.push(ce),ce++},Ae=0;Ae0)?1:0)+((lt=u.e.Dot(xe[tt+1].position,Ne)-Me>0)?1:0)+((Ke=u.e.Dot(xe[tt+2].position,Ne)-Me>0)?1:0)){case 0:Ye.push(xe[tt]),Ye.push(xe[tt+1]),Ye.push(xe[tt+2]);break;case 1:if(it&&(ot=xe[tt+1],rt=xe[tt+2],qe=Fe(xe[tt],ot),ht=Fe(xe[tt],rt)),lt){ot=xe[tt],rt=xe[tt+2],qe=Fe(xe[tt+1],ot),ht=Fe(xe[tt+1],rt),Ye.push(qe),Ye.push(rt.clone()),Ye.push(ot.clone()),Ye.push(rt.clone()),Ye.push(qe.clone()),Ye.push(ht);break}Ke&&(ot=xe[tt],rt=xe[tt+1],qe=Fe(xe[tt+2],ot),ht=Fe(xe[tt+2],rt)),ot&&rt&&qe&&ht&&(Ye.push(ot.clone()),Ye.push(rt.clone()),Ye.push(qe),Ye.push(ht),Ye.push(qe.clone()),Ye.push(rt.clone()));break;case 2:it||(rt=Fe(ot=xe[tt].clone(),xe[tt+1]),qe=Fe(ot,xe[tt+2]),Ye.push(ot),Ye.push(rt),Ye.push(qe)),lt||(rt=Fe(ot=xe[tt+1].clone(),xe[tt+2]),qe=Fe(ot,xe[tt]),Ye.push(ot),Ye.push(rt),Ye.push(qe)),Ke||(rt=Fe(ot=xe[tt+2].clone(),xe[tt]),qe=Fe(ot,xe[tt+1]),Ye.push(ot),Ye.push(rt),Ye.push(qe))}}return Ye},Re=0;ReO||z.deleted||z.isDirty)){for(var J=0;J<3;++J)if(z.error[J]>0,function(b){if(o){var x=b+s.verticesStart,O=u.e.FromArray(o,3*x),B=function(F){if(n){for(var z=0;z0&&this._reconstructedMesh.setVerticesData(Oe.b.NormalKind,s),d.length>0&&this._reconstructedMesh.setVerticesData(Oe.b.UVKind,d),p.length>0&&this._reconstructedMesh.setVerticesData(Oe.b.ColorKind,p);var ue=this._mesh.subMeshes[t];t>0&&(this._reconstructedMesh.subMeshes=[],ie.forEach(function(fe){yo.a.AddToMesh(fe.materialIndex,fe.verticesStart,fe.verticesCount,fe.indexStart,fe.indexCount,fe.getMesh())}),yo.a.AddToMesh(ue.materialIndex,J,B,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 B=u.e.Cross(x,O).normalize();if(i[a]=!1,u.e.Dot(B,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 Oe.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 Oe.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=da.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}(),Rc=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}(),xd=function(r,t){this.gradient=r,this.color=t},Oc=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}(),In=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}(),Cd=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"})(Fr||(Fr={}));var Po=function(){function r(t){if(this.particleSystem=t,this.type=Fr.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!t.emitter||!t.emitter.dispose){var e=C.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(C.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 An.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}(),Dm=` -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; -}`;ze.a.ShadersStore.particlesPixelShader=Dm;var Lm=` -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 -}`;ze.a.ShadersStore.particlesVertexShader=Lm;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 R.c,d.onStoppedObservable=new R.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 b=d._particles.pop();b!==p&&b.copyTo(p),d._stockParticles.push(b)},d._createParticle=function(){var p;if(d._stockParticles.length!==0?(p=d._stockParticles.pop())._reset():p=new Cd(d),d._subEmitters&&d._subEmitters.length>0){var b=d._subEmitters[Math.floor(Math.random()*d._subEmitters.length)];p._attachedSubEmitters=[],b.forEach(function(x){if(x.type===Fr.ATTACHED){var O=x.clone();p._attachedSubEmitters.push(O),O.particleSystem.start()}})}return p},d._emitFromParticle=function(p){if(d._subEmitters&&d._subEmitters.length!==0){var b=Math.floor(Math.random()*d._subEmitters.length);d._subEmitters[b].forEach(function(x){if(x.type===Fr.END){var O=x.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 Nr,d.updateFunction=function(p){var b=null,x=null;d.noiseTexture&&(b=d.noiseTexture.getSize(),x=d.noiseTexture.getContent());for(var O,B=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?In.GetCurrentGradient(se,d._colorGradients,function(Ae,Ee,Se){Ae!==O._currentColorGradient&&(O._currentColor1.copyFrom(O._currentColor2),Ee.getColorToRef(O._currentColor2),O._currentColorGradient=Ae),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&&In.GetCurrentGradient(se,d._angularSpeedGradients,function(Ae,Ee,Se){Ae!==O._currentAngularSpeedGradient&&(O._currentAngularSpeed1=O._currentAngularSpeed2,O._currentAngularSpeed2=Ee.getFactor(),O._currentAngularSpeedGradient=Ae),O.angularSpeed=$.a.Lerp(O._currentAngularSpeed1,O._currentAngularSpeed2,Se)}),O.angle+=O.angularSpeed*z;var ce=z;if(d._velocityGradients&&d._velocityGradients.length>0&&In.GetCurrentGradient(se,d._velocityGradients,function(Ae,Ee,Se){Ae!==O._currentVelocityGradient&&(O._currentVelocity1=O._currentVelocity2,O._currentVelocity2=Ee.getFactor(),O._currentVelocityGradient=Ae),ce*=$.a.Lerp(O._currentVelocity1,O._currentVelocity2,Se)}),O.direction.scaleToRef(ce,d._scaledDirection),d._limitVelocityGradients&&d._limitVelocityGradients.length>0&&In.GetCurrentGradient(se,d._limitVelocityGradients,function(Ae,Ee,Se){Ae!==O._currentLimitVelocityGradient&&(O._currentLimitVelocity1=O._currentLimitVelocity2,O._currentLimitVelocity2=Ee.getFactor(),O._currentLimitVelocityGradient=Ae);var Le=$.a.Lerp(O._currentLimitVelocity1,O._currentLimitVelocity2,Se);O.direction.length()>Le&&O.direction.scaleInPlace(d.limitVelocityDamping)}),d._dragGradients&&d._dragGradients.length>0&&In.GetCurrentGradient(se,d._dragGradients,function(Ae,Ee,Se){Ae!==O._currentDragGradient&&(O._currentDrag1=O._currentDrag2,O._currentDrag2=Ee.getFactor(),O._currentDragGradient=Ae);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),x&&b&&O._randomNoiseCoordinates1){var ue=d._fetchR(O._randomNoiseCoordinates1.x,O._randomNoiseCoordinates1.y,b.width,b.height,x),fe=d._fetchR(O._randomNoiseCoordinates1.z,O._randomNoiseCoordinates2.x,b.width,b.height,x),ve=d._fetchR(O._randomNoiseCoordinates2.y,O._randomNoiseCoordinates2.z,b.width,b.height,x),Te=u.c.Vector3[0],Re=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,Re),O.direction.addInPlace(Re)}if(d.gravity.scaleToRef(z,d._scaledGravity),O.direction.addInPlace(d._scaledGravity),d._sizeGradients&&d._sizeGradients.length>0&&In.GetCurrentGradient(se,d._sizeGradients,function(Ae,Ee,Se){Ae!==O._currentSizeGradient&&(O._currentSize1=O._currentSize2,O._currentSize2=Ee.getFactor(),O._currentSizeGradient=Ae),O.size=$.a.Lerp(O._currentSize1,O._currentSize2,Se)}),d._useRampGradients&&(d._colorRemapGradients&&d._colorRemapGradients.length>0&&In.GetCurrentGradient(se,d._colorRemapGradients,function(Ae,Ee,Se){var Le=$.a.Lerp(Ae.factor1,Ee.factor1,Se),xe=$.a.Lerp(Ae.factor2,Ee.factor2,Se);O.remapData.x=Le,O.remapData.y=xe-Le}),d._alphaRemapGradients&&d._alphaRemapGradients.length>0&&In.GetCurrentGradient(se,d._alphaRemapGradients,function(Ae,Ee,Se){var Le=$.a.Lerp(Ae.factor1,Ee.factor1,Se),xe=$.a.Lerp(Ae.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(Ae){Ae.particleSystem.disposeOnStop=!0,Ae.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 xd(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 Rc(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 x=$.a.Clamp(p._actualFrame/p.targetStopDuration);In.GetCurrentGradient(x,p._lifeTimeGradients,function(F,z){var J=F,ie=z,se=J.getFactor(),ce=ie.getFactor(),ue=(x-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 B=p._actualFrame/p.targetStopDuration;In.GetCurrentGradient(B,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,b=0;b-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;In.GetCurrentGradient(s,this._emitRateGradients,function(x,O,B){x!==i._currentEmitRateGradient&&(i._currentEmitRate1=i._currentEmitRate2,i._currentEmitRate2=O.getFactor(),i._currentEmitRateGradient=x),a=$.a.Lerp(i._currentEmitRate1,i._currentEmitRate2,B)})}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,b)}var x=new t(s,e.capacity,n,d,e.isAnimationSheetEnabled);if(x.customShader=p,e.id&&(x.id=e.id),e.subEmitters){x.subEmitters=[];for(var O=0,B=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 -} -}`;ze.a.ShadersStore.gpuUpdateParticlesVertexShader=Nm;var wm=`#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`;ze.a.IncludesShadersStore.clipPlaneFragmentDeclaration2=wm;var Fm=`#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 -} -`;ze.a.ShadersStore.gpuRenderParticlesPixelShader=Fm;var Bm=`#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`;ze.a.IncludesShadersStore.clipPlaneVertexDeclaration2=Bm;var Um=`#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 -}`;ze.a.ShadersStore.gpuRenderParticlesVertexShader=Um;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 R.c,s.onStoppedObservable=new R.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 Nr;for(var b=Math.min(s._engine.getCaps().maxTextureSize,d.randomTextureSize),x=[],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 R.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 Rc(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 Oc(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 wr&&(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 wr&&(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 wr&&(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 wr,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 b=this._getEffect();this._engine.enableEffect(b);var x=((n=this._scene)===null||n===void 0?void 0:n.getViewMatrix())||u.a.IdentityReadOnly;if(b.setMatrix("view",x),b.setMatrix("projection",(i=this.defaultProjectionMatrix)!==null&&i!==void 0?i:this._scene.getProjectionMatrix()),b.setTexture("diffuseSampler",this.particleTexture),b.setVector2("translationPivot",this.translationPivot),b.setVector3("worldOffset",this.worldOffset),this.isLocal&&b.setMatrix("emitterWM",s),this._colorGradientsTexture?b.setTexture("colorGradientSampler",this._colorGradientsTexture):b.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var O=this.particleTexture.getBaseSize();b.setFloat3("sheetInfos",this.spriteCellWidth/O.width,this.spriteCellHeight/O.height,O.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){var B=this._scene.activeCamera;b.setVector3("eyePosition",B.globalPosition)}var F=b.defines;if(this._scene&&(this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4||this._scene.clipPlane5||this._scene.clipPlane6)&&et.a.BindClipPlane(b,this._scene),F.indexOf("#define BILLBOARDMODE_ALL")>=0){var z=x.clone();z.invert(),b.setMatrix("invView",z)}switch(this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(b),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(b),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}(vo),Sa=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=Un.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,Oe.b.UVKind),this._colors32.length>0&&n.set(this._colors32,Oe.b.ColorKind),n.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){for(var i=0,o=0;oB?B:i,n=Math.round(B/i),o=0):n=n>B?B:n;for(var F=[],z=[],J=[],ie=[],se=[],ce=u.e.Zero(),ue=n;OB-(n=ue+Math.floor((1+o)*Math.random()))&&(n=B-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],Re=3*Te;if(F.push(a[Re],a[Re+1],a[Re+2]),z.push(b[Re],b[Re+1],b[Re+2]),d){var Ae=2*Te;ie.push(d[Ae],d[Ae+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),Me=Xe.b.Slice(J),Fe=Xe.b.Slice(se),Ye=Xe.b.Slice(z);for(ce.copyFromFloats(0,0,0),Se=0;Se65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){var ot=fe.materialIndex!==null?fe.materialIndex:0;this.depthSortedParticles.push(new Rd(B,e,o.length,ot))}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 tt=this.mesh._boundingInfo;tt&&(se.copyFrom(tt.minimum),ce.copyFrom(tt.maximum))}var it=(Le=this.particles[t]._pos)/3|0;Ne=4*it,Fe=2*it;for(var lt=t;lt<=e;lt++){var Ke=this.particles[lt];this.updateParticle(Ke);var ot=Ke._model._shape,rt=Ke._model._shapeUV,qe=Ke._rotationMatrix,ht=Ke.position,Ve=Ke.rotation,Je=Ke.scaling,yt=Ke._globalPosition;if(this._depthSort&&this._depthSortParticles){var Wt=this.depthSortedParticles[lt];Wt.idx=Ke.idx,Wt.ind=Ke._ind,Wt.indicesLength=Ke._model._indicesLength,Wt.sqDistance=u.e.DistanceSquared(Ke.position,ue)}if(!Ke.alive||Ke._stillInvisible&&!Ke.isVisible)Le+=3*(Ye=ot.length),Ne+=4*Ye,Fe+=2*Ye;else{if(Ke.isVisible){Ke._stillInvisible=!1;var Nt=F[12];if(Ke.pivot.multiplyToRef(Je,Nt),this.billboard&&(Ve.x=0,Ve.y=0),(this._computeParticleRotation||this.billboard)&&Ke.getRotationMatrix(i),Ke.parentId!==null){var Qt=this.getParticleById(Ke.parentId);if(Qt){var vt=Qt._rotationMatrix,Jt=Qt._globalPosition,Xt=ht.x*vt[1]+ht.y*vt[4]+ht.z*vt[7],zt=ht.x*vt[0]+ht.y*vt[3]+ht.z*vt[6],Yt=ht.x*vt[2]+ht.y*vt[5]+ht.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;qe[0]=Et[0]*vt[0]+Et[1]*vt[3]+Et[2]*vt[6],qe[1]=Et[0]*vt[1]+Et[1]*vt[4]+Et[2]*vt[7],qe[2]=Et[0]*vt[2]+Et[1]*vt[5]+Et[2]*vt[8],qe[3]=Et[4]*vt[0]+Et[5]*vt[3]+Et[6]*vt[6],qe[4]=Et[4]*vt[1]+Et[5]*vt[4]+Et[6]*vt[7],qe[5]=Et[4]*vt[2]+Et[5]*vt[5]+Et[6]*vt[8],qe[6]=Et[8]*vt[0]+Et[9]*vt[3]+Et[10]*vt[6],qe[7]=Et[8]*vt[1]+Et[9]*vt[4]+Et[10]*vt[7],qe[8]=Et[8]*vt[2]+Et[9]*vt[5]+Et[10]*vt[8]}}else Ke.parentId=null}else yt.x=ht.x,yt.y=ht.y,yt.z=ht.z,(this._computeParticleRotation||this.billboard)&&(Et=i.m,qe[0]=Et[0],qe[1]=Et[1],qe[2]=Et[2],qe[3]=Et[4],qe[4]=Et[5],qe[5]=Et[6],qe[6]=Et[8],qe[7]=Et[9],qe[8]=Et[10]);var Mt=F[11];for(Ke.translateFromPivot?Mt.setAll(0):Mt.copyFrom(Nt),Ye=0;Ye0)for(var e=0;e0&&t.set(this._uvs32,Oe.b.UVKind);var e=0;this._colors32.length>0&&(e=1,t.set(this._colors32,Oe.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 Md(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],b=s[3],x=o[s[0]],O=o[d],B=o[p],F=o[b];return new M.b(x/255,O/255,B/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(Oe.b.PositionKind),b=t.getIndices(),x=t.getVerticesData(Oe.b.UVKind),O=t.getVerticesData(Oe.b.ColorKind),B=u.e.Zero();t.computeWorldMatrix();var F=t.getWorldMatrix();if(!F.isIdentity())for(var z=0;z1&&(Ki=1),(Qi=Kr.b+Xr)<0&&(Qi=0),Qi>1&&(Qi=1),M.a.HSVtoRGBToRef(Yr,Ki,Qi,ur),jt.set(ur.r,ur.g,ur.b,1)):jt=qt.set(Math.random(),Math.random(),Math.random(),1),Nn.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){Wn.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,b,x,O,B,F,z,J,ie,se,ce,ue,fe=new Array,ve=u.e.Zero(),Te=u.e.Zero(),Re=u.e.Zero(),Ae=u.e.Zero(),Ee=u.e.Zero(),Se=u.e.Zero(),Le=new Array,xe=0,Ne=n.length/3,Me=0;Me0&&(fe=fe.map(function(lt){return lt+tt})),Me=0;Me3)&&(a=En.Random);var s=t.getVerticesData(Oe.b.PositionKind),d=t.getIndices();this._groups.push(this._groupCounter);var p=new Aa(this._groupCounter,null);switch(p._groupDensity=this._calculateDensity(e,s,d),a===En.Color?p._textureNb=i||0:i=i||new M.b(1,1,1,1),a){case En.Color:this._colorFromTexture(t,p,!1);break;case En.UV:this._setPointsColorOrUV(t,p,!1,!1,!1);break;case En.Random:this._setPointsColorOrUV(t,p,!1);break;case En.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||En.Random;(isNaN(a)||a<0||a>3)&&(a=En.Random);var s=t.getVerticesData(Oe.b.PositionKind),d=t.getIndices();this._groups.push(this._groupCounter);var p=new Aa(this._groupCounter,null);switch(p._groupDensity=this._calculateDensity(e,s,d),a===En.Color?p._textureNb=i||0:i=i||new M.b(1,1,1,1),a){case En.Color:this._colorFromTexture(t,p,!0);break;case En.UV:this._setPointsColorOrUV(t,p,!0,!1,!1);break;case En.Random:this._setPointsColorOrUV(t,p,!0);break;case En.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,b=p[5].copyFromFloats(1,0,0),x=p[6].copyFromFloats(0,1,0),O=p[7].copyFromFloats(0,0,1),B=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&&(B.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,Re=fe._globalPosition;if(this._computeParticleRotation&&fe.getRotationMatrix(i),fe.parentId!==null){var Ae=this.particles[fe.parentId],Ee=Ae._rotationMatrix,Se=Ae._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(Re.x=Se.x+xe,Re.y=Se.y+Le,Re.z=Se.z+Ne,this._computeParticleRotation){var Me=i.m;ve[0]=Me[0]*Ee[0]+Me[1]*Ee[3]+Me[2]*Ee[6],ve[1]=Me[0]*Ee[1]+Me[1]*Ee[4]+Me[2]*Ee[7],ve[2]=Me[0]*Ee[2]+Me[1]*Ee[5]+Me[2]*Ee[8],ve[3]=Me[4]*Ee[0]+Me[5]*Ee[3]+Me[6]*Ee[6],ve[4]=Me[4]*Ee[1]+Me[5]*Ee[4]+Me[6]*Ee[7],ve[5]=Me[4]*Ee[2]+Me[5]*Ee[5]+Me[6]*Ee[8],ve[6]=Me[8]*Ee[0]+Me[9]*Ee[3]+Me[10]*Ee[6],ve[7]=Me[8]*Ee[1]+Me[9]*Ee[4]+Me[10]*Ee[7],ve[8]=Me[8]*Ee[2]+Me[9]*Ee[5]+Me[10]*Ee[8]}}else Re.x=0,Re.y=0,Re.z=0,this._computeParticleRotation&&(Me=i.m,ve[0]=Me[0],ve[1]=Me[1],ve[2]=Me[2],ve[3]=Me[4],ve[4]=Me[5],ve[5]=Me[6],ve[6]=Me[8],ve[7]=Me[9],ve[8]=Me[10]);var Fe=p[11];fe.translateFromPivot?Fe.setAll(0):Fe.copyFrom(fe.pivot);var Ye=p[0];Ye.copyFrom(fe.position);var tt=Ye.x-fe.pivot.x,it=Ye.y-fe.pivot.y,lt=Ye.z-fe.pivot.z,Ke=tt*ve[0]+it*ve[3]+lt*ve[6],ot=tt*ve[1]+it*ve[4]+lt*ve[7],rt=tt*ve[2]+it*ve[5]+lt*ve[8];Ke+=Fe.x,ot+=Fe.y,rt+=Fe.z;var qe=s[ie]=Re.x+b.x*Ke+x.x*ot+O.x*rt,ht=s[ie+1]=Re.y+b.y*Ke+x.y*ot+O.y*rt,Ve=s[ie+2]=Re.z+b.z*Ke+x.z*ot+O.z*rt;if(this._computeBoundingBox&&(B.minimizeInPlaceFromFloats(qe,ht,Ve),F.maximizeInPlaceFromFloats(qe,ht,Ve)),this._computeParticleColor&&fe.color){var Je=fe.color,yt=this._colors32;yt[se]=Je.r,yt[se+1]=Je.g,yt[se+2]=Je.b,yt[se+3]=Je.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(Oe.b.ColorKind,a,!1,!1),this._computeParticleTexture&&o.updateVerticesData(Oe.b.UVKind,d,!1,!1),o.updateVerticesData(Oe.b.PositionKind,s,!1,!1)),this._computeBoundingBox&&(o._boundingInfo?o._boundingInfo.reConstruct(B,F,o._worldMatrix):o._boundingInfo=new Ui.a(B,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 Ui.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(at.a.NAME_PHYSICSENGINE);e||(e=new Id(this),this._addComponent(e));try{return this._physicsEngine=new Ir(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,Br,Id=function(){function r(t){var e=this;this.name=at.a.NAME_PHYSICSENGINE,this.scene=t,this.scene.onBeforePhysicsObservable=new R.c,this.scene.onAfterPhysicsObservable=new R.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}(),zm=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 Ur).radius=e,e.strength=n||e.strength,e.falloff=i||e.falloff);var a=new Dd(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 Ur).radius=e,e.strength=n||e.strength,e.falloff=i||e.falloff);var a=new Dd(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 Ur).radius=e,e.strength=n||e.strength,e.falloff=i||e.falloff);var o=new jm(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 Dc).radius=e,e.strength=n||e.strength,e.height=i||e.height,e.updraftMode=o||e.updraftMode);var a=new Hm(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 Lc).radius=e,e.strength=n||e.strength,e.height=i||e.height);var o=new Wm(this._scene,t,e);return o.dispose(!1),o},r}(),Dd=function(){function r(t,e){this._scene=t,this._options=e,this._dataFetched=!1,this._options=Object(c.a)(Object(c.a)({},new Ur),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=Un.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}(),jm=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 Ur),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}(),Hm=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 Dc),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===Br.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===Br.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=fi.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}(),Wm=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 Lc),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,b=d.y*this._options.updraftForceMultiplier,x=d.z*this._options.centripetalForceMultiplier;else{var O=u.e.Cross(n,e).normalize();p=(O.x+d.x)*this._options.centrifugalForceMultiplier,b=this._originTop.y*this._options.updraftForceMultiplier,x=(O.z+d.z)*this._options.centrifugalForceMultiplier}var B=new u.e(p,b,x);return{force:B=B.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=fi.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}(),Ur=function(){this.radius=5,this.strength=10,this.falloff=xo.Constant,this.sphere={segments:32,diameter:1}},Dc=function(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=Br.Center},Lc=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"}(Br||(Br={}));var Xm=` -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); -}`;ze.a.ShadersStore.blackAndWhitePixelShader=Xm;var Ld=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);C.a.RegisteredTypes["BABYLON.BlackAndWhitePostProcess"]=Ld;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; -}`;ze.a.ShadersStore.extractHighlightsPixelShader=Ym;var Nc=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 b=r.call(this,e,"extractHighlights",["threshold","exposure"],null,n,i,o,a,s,null,d,void 0,null,p)||this;return b.threshold=.9,b._exposure=1,b._inputPostProcess=null,b.onApplyObservable.add(function(x){b._inputPostProcess&&x.setTextureFromPostProcess("textureSampler",b._inputPostProcess),x.setFloat("threshold",Math.pow(b.threshold,Gt.b)),x.setFloat("exposure",b._exposure)}),b}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);C.a.RegisteredTypes["BABYLON.ExtractHighlightsPostProcess"]=Nc;var Km=`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); -} -`;ze.a.ShadersStore.bloomMergePixelShader=Km;var wc=function(r){function t(e,n,i,o,a,s,d,p,b,x,O){x===void 0&&(x=h.a.TEXTURETYPE_UNSIGNED_INT),O===void 0&&(O=!1);var B=r.call(this,e,"bloomMerge",["bloomWeight"],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2","bloomBlur"],a,s,d,p,b,null,x,void 0,null,!0)||this;return B.weight=1,B.weight=o,B.onApplyObservable.add(function(F){F.setTextureFromPostProcess("textureSampler",n),F.setTextureFromPostProcessOutput("bloomBlur",i),F.setFloat("bloomWeight",B.weight)}),O||B.updateEffect(),B}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);C.a.RegisteredTypes["BABYLON.BloomMergePostProcess"]=wc;var Fc=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 Nc("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 wc("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 -} -`;ze.a.ShadersStore.depthOfFieldMergePixelShader=$m;var ar,eg=function(){},Fd=function(r){function t(e,n,i,o,a,s,d,p,b,x,O){x===void 0&&(x=h.a.TEXTURETYPE_UNSIGNED_INT),O===void 0&&(O=!1);var B=r.call(this,e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],a,s,d,p,b,null,x,void 0,null,!0)||this;return B.blurSteps=o,B.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||B.updateEffect(),B}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 Vc=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 Uc("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 b=p/Math.pow(2,d-1),x=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);C.a.RegisteredTypes["BABYLON.FxaaPostProcess"]=Co;var og=`#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); -}`;ze.a.ShadersStore.grainPixelShader=og;var kc=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 b=r.call(this,e,"grain",["intensity","animatedSeed"],[],n,i,o,a,s,null,d,void 0,null,p)||this;return b.intensity=30,b.animated=!1,b.onApplyObservable.add(function(x){x.setFloat("intensity",b.intensity),x.setFloat("animatedSeed",b.animated?Math.random()+1:1)}),b}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);C.a.RegisteredTypes["BABYLON.GrainPostProcess"]=kc;var ag=` -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); -}`;ze.a.ShadersStore.highlightsPixelShader=ag;var sg=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);ze.a.IncludesShadersStore.mrtFragmentDeclaration=`#if __VERSION__>=200 -layout(location=0) out vec4 glFragData[{X}]; -#endif -`;var cg=`#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 -}`;ze.a.ShadersStore.geometryPixelShader=cg;var lg=`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 -} -`;ze.a.ShadersStore.geometryVertexShader=lg;var li=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=[Oe.b.PositionKind,Oe.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 co&&n.reflectivityTexture&&(i.push("#define HAS_REFLECTIVITY"),s=!0)),s&&(i.push("#define NEED_UV"),a.isVerticesDataPresent(Oe.b.UVKind)&&(o.push(Oe.b.UVKind),i.push("#define UV1")),a.isVerticesDataPresent(Oe.b.UV2Kind)&&(o.push(Oe.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(Oe.b.MatricesIndicesKind),o.push(Oe.b.MatricesWeightsKind),a.numBoneInfluencers>4&&(o.push(Oe.b.MatricesIndicesExtraKind),o.push(Oe.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),et.a.PrepareAttributesForMorphTargetsInfluencers(o,a,p)),e&&(i.push("#define INSTANCES"),et.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 b=i.join(` -`);return this._cachedDefines!==b&&(this._cachedDefines=b,this._effect=this._scene.getEngine().createEffect("geometry",o,["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","morphTargetInfluences","bumpMatrix","reflectivityMatrix","vTangentSpaceParams","vBumpInfos"],["diffuseSampler","bumpSampler","reflectivitySampler"],b,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 qs("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(),b=o.getMaterial();if(b){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 x=a.skeleton.getTransformMatrices(a);t._previousBonesTransformationMatrices[a.uniqueId]=t._copyBonesTransformationMatrices(x,new Float32Array(x.length))}var O=a._getInstancesRenderList(o._id,!!o.getReplacementMesh());if(!O.mustReturn){var B=p.getCaps().instancedArrays&&(O.visibleInstances[o._id]!==null||a.hasThinInstances),F=s.getWorldMatrix();if(t.isReady(o,B)){if(p.enableEffect(t._effect),a._bind(o,t._effect,b.fillMode),t._effect.setMatrix("viewProjection",d.getTransformMatrix()),t._effect.setMatrix("view",d.getViewMatrix()),b){var z,J=s._instanceDataStorage;if(J.isFrozen||!b.backFaceCulling&&b.overrideMaterialSideOrientation===null)z=J.sideOrientation;else{var ie=s._getWorldMatrixDeterminant();(z=b.overrideMaterialSideOrientation)==null&&(z=b.sideOrientation),ie<0&&(z=z===Ht.a.ClockWiseSideOrientation?Ht.a.CounterClockWiseSideOrientation:Ht.a.ClockWiseSideOrientation)}if(b._preBind(t._effect,z),b.needAlphaTesting()){var se=b.getAlphaTestTexture();se&&(t._effect.setTexture("diffuseSampler",se),t._effect.setMatrix("diffuseMatrix",se.getTextureMatrix()))}b.bumpTexture&&d.getEngine().getCaps().standardDerivatives&&Ft.a.BumpTextureEnabled&&(t._effect.setFloat3("vBumpInfos",b.bumpTexture.coordinatesIndex,1/b.bumpTexture.level,b.parallaxScaleBias),t._effect.setMatrix("bumpMatrix",b.bumpTexture.getTextureMatrix()),t._effect.setTexture("bumpSampler",b.bumpTexture),t._effect.setFloat2("vTangentSpaceParams",b.invertNormalMapX?-1:1,b.invertNormalMapY?-1:1)),t._enableReflectivity&&(b instanceof Ft.a&&b.specularTexture?(t._effect.setMatrix("reflectivityMatrix",b.specularTexture.getTextureMatrix()),t._effect.setTexture("reflectivitySampler",b.specularTexture)):b instanceof co&&b.reflectivityTexture&&(t._effect.setMatrix("reflectivityMatrix",b.reflectivityTexture.getTextureMatrix()),t._effect.setTexture("reflectivitySampler",b.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])),et.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,b.fillMode,O,B,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 -} -`;ze.a.ShadersStore.motionBlurPixelShader=hg;var Gc=function(r){function t(e,n,i,o,a,s,d,p,b,x){p===void 0&&(p=h.a.TEXTURETYPE_UNSIGNED_INT),b===void 0&&(b=!1),x===void 0&&(x=!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,b)||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=x,O._forceGeometryBuffer?(O._geometryBufferRenderer=n.enableGeometryBufferRenderer(),O._geometryBufferRenderer&&(O._geometryBufferRenderer.enableVelocity=!0)):(O._prePassRenderer=n.enablePrePassRenderer(),O._prePassRenderer&&(O._prePassRenderer.markAsDirty(),O._prePassEffectConfiguration=new ug)),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(li.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(li.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);C.a.RegisteredTypes["BABYLON.MotionBlurPostProcess"]=Gc;var dg=` -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); -}`;ze.a.ShadersStore.refractionPixelShader=dg;var kd=function(r){function t(e,n,i,o,a,s,d,p,b,x){var O=r.call(this,e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],s,d,p,b,x)||this;return O._ownRefractionTexture=!0,O.color=i,O.depth=o,O.colorLevel=a,O.refractionTextureUrl=n,O.onActivateObservable.add(function(B){O._refTexture=O._refTexture||new we.a(n,B.getScene())}),O.onApplyObservable.add(function(B){B.setColor3("baseColor",O.color),B.setFloat("depth",O.depth),B.setFloat("colorLevel",O.colorLevel),B.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);C.a.RegisteredTypes["BABYLON.RefractionPostProcess"]=kd;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.); -}`;ze.a.ShadersStore.sharpenPixelShader=fg;var zc=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 b=r.call(this,e,"sharpen",["sharpnessAmounts","screenSize"],null,n,i,o,a,s,null,d,void 0,null,p)||this;return b.colorAmount=1,b.edgeAmount=.3,b.onApply=function(x){x.setFloat2("screenSize",b.width,b.height),x.setFloat2("sharpnessAmounts",b.edgeAmount,b.colorAmount)},b}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);C.a.RegisteredTypes["BABYLON.SharpenPostProcess"]=zc;var Vr=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(Xe.b.MakeArray(e||this._cameras))},r.prototype._disableEffect=function(t,e){var n=this._renderEffects[t];n&&n._disable(Xe.b.MakeArray(e||this._cameras))},r.prototype._attachCameras=function(t,e){var n=Xe.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}(),Gd=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(at.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER);r||(r=new zd(this),this._addComponent(r)),this._postProcessRenderPipelineManager=new Gd}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});var zd=function(){function r(t){this.name=at.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=t}return r.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(at.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}(),jd=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 R.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 zc("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 Vc(s._scene,null,s._depthOfFieldBlurLevel,s._defaultPipelineTextureType,!0),s.bloom=new Fc(s._scene,s._bloomScale,s._bloomWeight,s.bloomKernel,s._defaultPipelineTextureType,!0),s.chromaticAberration=new Bc("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 kc("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 Fc(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 zo("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 Co("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; - -}`;ze.a.ShadersStore.lensHighlightsPixelShader=pg;var _g=` - - - - -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; -} -} -`;ze.a.ShadersStore.depthOfFieldPixelShader=_g;var mg=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 bi.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}(Vr),gg=function(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[h.a.PREPASS_DEPTHNORMAL_TEXTURE_TYPE]},vg=` -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);C.a.RegisteredTypes["BABYLON.ScreenSpaceReflectionPostProcess"]=jc;var Ag=`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 -`;ze.a.ShadersStore.standardPixelShader=Ag;var Wd=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 jc("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 Co("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,b=-2;b<2;b++)for(var x=-2;x<2;x++)o[s]=(b+.5)*(1/d),o[s+1]=(x+.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 b=d.width/s.getRenderWidth();d.kernel=a[o]*b}),p.onActivateObservable.add(function(){var b=p.height/s.getRenderHeight();p.kernel=a.horizontalBlur?64*b:a[o]*b}),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(x){var O=1/i.luminancePostProcess.width,B=1/i.luminancePostProcess.height;a[0]=-.5*O,a[1]=.5*B,a[2]=.5*O,a[3]=.5*B,a[4]=-.5*O,a[5]=-.5*B,a[6]=.5*O,a[7]=-.5*B,x.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 b=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(function(x,O){var B=new Array(18);x.onApply=function(F){if(b){for(var z=0,J=-1;J<2;J++)for(var ie=-1;ie<2;ie++)B[z]=J/b.width,B[z+1]=ie/b.height,z+=2;F.setArray2("dsOffsets",B),F.setFloat("halfDestPixelSize",.5/b.width),b=O===i.luminanceDownSamplePostProcesses.length-1?i.luminancePostProcess:x}},O===i.luminanceDownSamplePostProcesses.length-1&&(x.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 x},!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 b=(d-s)/1e3;i._hdrCurrentLuminancea-i.hdrIncreaseRate*b?a-=i.hdrIncreaseRate*b: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),b=i._scene.activeCamera.getViewMatrix().getRow(2),x=u.e.Dot(p.toVector3(),new u.e(1,0,0))+u.e.Dot(b.toVector3(),new u.e(0,0,1));x*=4;var O=u.a.FromValues(.5*Math.cos(x),-Math.sin(x),0,0,Math.sin(x),.5*Math.cos(x),0,0,0,0,1,0,0,0,0,1),B=s.multiply(O).multiply(a);d.setMatrix("lensStarMatrix",B),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 Gc("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(),b=u.d.Zero();this.motionBlurPostProcess.onApply=function(x){(p=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(d),x.setMatrix("inverseViewProjection",d),x.setMatrix("prevViewProjection",s),s=p,b.x=i.motionBlurPostProcess.width,b.y=i.motionBlurPostProcess.height,x.setVector2("screenSize",b),a=e.getEngine().getFps()/60,x.setFloat("motionScale",a),x.setFloat("motionStrength",i.motionStrength),x.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); -} -`;ze.a.ShadersStore.stereoscopicInterlacePixelShader=Pg;var xg=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(b){b.setTextureFromPostProcess("camASampler",p._passedProcess),b.setFloat2("stepSize",p._stepSize.x,p._stepSize.y)}),p}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"StereoscopicInterlacePostProcessI"},t}(_t),Cg=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),Rg=` -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); -}`;ze.a.ShadersStore.tonemapPixelShader=Rg;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 Og=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 b="#define ";return p._operator===sr.Hable?b+="HABLE_TONEMAPPING":p._operator===sr.Reinhard?b+="REINHARD_TONEMAPPING":p._operator===sr.HejiDawson?b+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":p._operator===sr.Photographic&&(b+="PHOTOGRAPHIC_TONEMAPPING"),p.updateEffect(b),p.onApply=function(x){x.setFloat("_ExposureAdjustment",p.exposureAdjustment)},p}return Object(c.d)(t,r),t.prototype.getClassName=function(){return"TonemapPostProcess"},t}(_t),Mg=`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 -} -`;ze.a.ShadersStore.volumetricLightScatteringPassVertexShader=Ig;var Dg=`#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); -} -`;ze.a.ShadersStore.volumetricLightScatteringPassPixelShader=Dg;var Xd=function(r){function t(e,n,i,o,a,s,d,p,b){a===void 0&&(a=100),s===void 0&&(s=we.a.BILINEAR_SAMPLINGMODE);var x=r.call(this,e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,i,s,d,p,"#define NUM_SAMPLES "+a)||this;return x._screenCoordinates=u.d.Zero(),x.customMeshPosition=u.e.Zero(),x.useCustomMeshPosition=!1,x.invert=!0,x.excludedMeshes=new Array,x.exposure=.3,x.decay=.96815,x.weight=.58767,x.density=.926,d=(b=i===null?b:i.getScene()).getEngine(),x._viewPort=new Kn.a(0,0,1,1).toGlobal(d.getRenderWidth(),d.getRenderHeight()),x.mesh=o!==null?o:t.CreateDefaultMesh("VolumetricLightScatteringMesh",b),x._createPass(b,n.passRatio||n),x.onActivate=function(O){x.isSupported||x.dispose(O),x.onActivate=null},x.onApplyObservable.add(function(O){x._updateMeshScreenCoordinates(b),O.setTexture("lightScatteringSampler",x._volumetricLightScatteringRTT),O.setFloat("exposure",x.exposure),O.setFloat("decay",x.decay),O.setFloat("weight",x.weight),O.setFloat("density",x.density),O.setVector2("meshPositionOnScreen",x._screenCoordinates)}),x}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=[Oe.b.PositionKind],s=e.getMaterial();s&&(s.needAlphaTesting()&&o.push("#define ALPHATEST"),i.isVerticesDataPresent(Oe.b.UVKind)&&(a.push(Oe.b.UVKind),o.push("#define UV1")),i.isVerticesDataPresent(Oe.b.UV2Kind)&&(a.push(Oe.b.UV2Kind),o.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(a.push(Oe.b.MatricesIndicesKind),a.push(Oe.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"),et.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(b){var x=b.getRenderingMesh(),O=b.getEffectiveMesh();if(!i._meshExcluded(x)){O._internalAbstractMeshDataInfo._isActiveIntermediate=!1;var B=b.getMaterial();if(B){var F=x.getScene(),z=F.getEngine();z.setState(B.backFaceCulling);var J=x._getInstancesRenderList(b._id,!!b.getReplacementMesh());if(!J.mustReturn){var ie=z.getCaps().instancedArrays&&(J.visibleInstances[b._id]!==null||x.hasThinInstances);if(i._isReady(b,ie)){var se=i._volumetricLightScatteringPass;if(x===i.mesh&&(se=b.effect?b.effect:B.getEffect()),z.enableEffect(se),x._bind(b,se,B.fillMode),x===i.mesh)B.bind(O.getWorldMatrix(),x);else{if(i._volumetricLightScatteringPass.setMatrix("viewProjection",F.getTransformMatrix()),B&&B.needAlphaTesting()){var ce=B.getAlphaTestTexture();i._volumetricLightScatteringPass.setTexture("diffuseSampler",ce),ce&&i._volumetricLightScatteringPass.setMatrix("diffuseMatrix",ce.getTextureMatrix())}x.useBones&&x.computeBonesUsingShaders&&x.skeleton&&i._volumetricLightScatteringPass.setMatrices("mBones",x.skeleton.getTransformMatrices(x))}x._processRendering(O,b,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(b,x,O,B){var F,z=e.getEngine();if(B.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);C.a.RegisteredTypes["BABYLON.ScreenSpaceCurvaturePostProcess"]=Yd,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 Kd(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 Kd=function(){function r(t){this.name=at.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 R.c,this.onAfterBoxRenderingObservable=new R.c,this.onResourcesReadyObservable=new R.c,this.enabled=!0,this.renderList=new di.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(at.a.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(at.a.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(at.a.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(at.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 ha.a("colorShader",this.scene,"color",{attributes:[Oe.b.PositionKind],uniforms:["world","viewProjection","color"]}),this._colorShader.reservedDataStore={hidden:!0};var t=this.scene.getEngine(),e=dt.a.CreateBox({size:1});this._vertexBuffers[Oe.b.PositionKind]=new Oe.b(t,e.positions,Oe.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[Oe.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; -}`;ze.a.ShadersStore.lineVertexShader=Ng,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 Hc(this,r,t,!0,e),this},Object.defineProperty(Dt.a.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),To.b.prototype.enableEdgesRendering=function(r,t){return r===void 0&&(r=.95),t===void 0&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new qd(this,r,t),this},To.a.prototype.enableEdgesRendering=function(r,t){return r===void 0&&(r=.95),t===void 0&&(t=!1),To.b.prototype.enableEdgesRendering.apply(this,arguments),this};var wg=function(){this.edges=new Array,this.edgesConnectedCount=0},Hc=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 di.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 ha.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[Oe.b.PositionKind];t&&t._rebuild(),(t=this._buffers[Oe.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[Oe.b.PositionKind];t&&(t.dispose(),this._buffers[Oe.b.PositionKind]=null),(t=this._buffers[Oe.b.NormalKind])&&(t.dispose(),this._buffers[Oe.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(Ae,Ee){return Ae[1]Ee[1]?1:0}):t[s].sort(function(Ae,Ee){return Ae[1]>Ee[1]?-1:Ae[1]=a+1;--x)o(t[x%3],p,x!==a+2?i[n[e+(x+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[b-1]);for(var B=b<=O,F=B?b:O,z=B?O:b,J=B?b-1:O-1,ie=B?0:1,se=b+O-2,ce=0,ue=0,fe=B?d:p,ve=B?p:d,Te=0;se-- >0;){ie?n.push(fe[ce],ve[ue]):n.push(ve[ue],fe[ce]);var Re=void 0;(Te+=F)>=z&&ceYe){var Et=Fe;Fe=Ye,Ye=Et}($t=zt[Mt=Fe+"_"+Ye])?$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 qs("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 zo("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; -}`;ze.a.ShadersStore.outlinePixelShader=kg;var Gg=` -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 -} -`;ze.a.ShadersStore.outlineVertexShader=Gg,_e.a.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new ef(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 ef=function(){function r(t){this.name=at.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(at.a.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(at.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,b=t.getRenderingMesh(),x=p||b,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:b.outlineWidth),this._effect.setColor4("color",n?b.overlayColor:b.outlineColor,n?b.overlayAlpha:O.alpha),this._effect.setMatrix("viewProjection",o.getTransformMatrix()),this._effect.setMatrix("world",x.getWorldMatrix()),b.useBones&&b.computeBonesUsingShaders&&b.skeleton&&this._effect.setMatrices("mBones",b.skeleton.getTransformMatrices(b)),et.a.BindMorphTargetParameters(b,this._effect),b._bind(t,this._effect,O.fillMode),O&&O.needAlphaTesting()){var B=O.getAlphaTestTexture();B&&(this._effect.setTexture("diffuseSampler",B),this._effect.setMatrix("diffuseMatrix",B.getTextureMatrix()))}a.setZOffset(-this.zOffset),b._processRendering(x,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=[Oe.b.PositionKind,Oe.b.NormalKind],o=t.getMesh(),a=t.getMaterial();a&&(a.needAlphaTesting()&&(n.push("#define ALPHATEST"),o.isVerticesDataPresent(Oe.b.UVKind)&&(i.push(Oe.b.UVKind),n.push("#define UV1")),o.isVerticesDataPresent(Oe.b.UV2Kind)&&(i.push(Oe.b.UV2Kind),n.push("#define UV2"))),a.useLogarithmicDepth&&n.push("#define LOGARITHMICDEPTH")),o.useBones&&o.computeBonesUsingShaders?(i.push(Oe.b.MatricesIndicesKind),i.push(Oe.b.MatricesWeightsKind),o.numBoneInfluencers>4&&(i.push(Oe.b.MatricesIndicesExtraKind),i.push(Oe.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),et.a.PrepareAttributesForMorphTargetsInfluencers(i,o,d)),e&&(n.push("#define INSTANCES"),et.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}(),zg=f(148),tf=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 R.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}();ze.a.IncludesShadersStore.imageProcessingCompatibility=`#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); -#endif`;var jg=`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 -}`;ze.a.ShadersStore.spritesPixelShader=jg;var Hg=` -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 -}`;ze.a.ShadersStore.spritesVertexShader=Hg;var Wg=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-b*p)*this.cellWidth/o.width,e._yOffset=b*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}(),rf=function(){function r(t,e,n,i,o,a,s,d,p){var b=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 R.c,this.disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=function(O,B){O.cellRef||(O.cellIndex=0);var F=O.cellIndex;typeof F=="number"&&isFinite(F)&&Math.floor(F)===F&&(O.cellRef=b._spriteMap[O.cellIndex]),O._xOffset=b._cellData[O.cellRef].frame.x/B.width,O._yOffset=b._cellData[O.cellRef].frame.y/B.height,O._xSize=b._cellData[O.cellRef].frame.w,O._ySize=b._cellData[O.cellRef].frame.h},o||(o=Ue.a.LastCreatedScene),o._getComponent(at.a.NAME_SPRITE)||o._addComponent(new nf(o)),this._fromPacked=d,this._scene=o;var x=this._scene.getEngine();if(this._spriteRenderer=new Wg(x,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 x=t.substring(0,b-1)+".json",O=new XMLHttpRequest;O.open("GET",x,!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 B=JSON.parse(O.response),F=Reflect.ownKeys(B.frames);n._spriteMap=F,n._packedAndReady=!0,n._cellData=B.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,b=t.angle,x=d*Math.cos(b)-p*Math.sin(b)+.5,O=d*Math.sin(b)+p*Math.cos(b)+.5,B=t._xOffset*a.width+x*t._xSize|0,F=t._yOffset*a.height+O*t._ySize|0;return this._textureContent[4*(B+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,b=u.c.Vector3[0],x=u.c.Vector3[1],O=e.getViewMatrix(),B=0;Bz){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,b),J.pickedPoint=u.e.TransformCoordinates(b,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),b=u.c.Vector3[1].copyFromFloats(0,0,0),x=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; -}`;ze.a.ShadersStore.spriteMapPixelShader=Xg;var Yg=`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; -}`;ze.a.ShadersStore.spriteMapVertexShader=Yg;var _i,Kg=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 of(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,b=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}(),_f=f(146),rv=f(145),gi=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}(),xa=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}(gi),Yc=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}(gi),Ca=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}(gi),Ra=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}(gi),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 lens flares on/off"},t.prototype.apply=function(e,n){return e.lensFlaresEnabled=n.isInImprovementMode,!0},t}(gi),mf=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}(gi),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 particles on/off"},t.prototype.apply=function(e,n){return e.particlesEnabled=n.isInImprovementMode,!0},t}(gi),Kc=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}(gi),Ia=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 x=0;x0)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&&Xe.b.Download(t,this._fileName)},r._defaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3},r}(),Ro=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){Xe.b._ScreenshotCanvas||(Xe.b._ScreenshotCanvas=document.createElement("canvas")),Xe.b._ScreenshotCanvas.width=d,Xe.b._ScreenshotCanvas.height=s;var p=Xe.b._ScreenshotCanvas.getContext("2d"),b=t.getRenderWidth()/t.getRenderHeight(),x=d,O=x/b;O>s&&(x=(O=s)*b);var B=Math.max(0,d-x)/2,F=Math.max(0,s-O)/2,z=t.getRenderingCanvas();p&&z&&p.drawImage(z,B,F,x,O),Xe.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,b){o===void 0&&(o="image/png"),a===void 0&&(a=1),s===void 0&&(s=!1),p===void 0&&(p=!1),b===void 0&&(b=!1);var x=r._getScreenshotSize(t,e,n),O=x.height,B=x.width,F={width:B,height:O};if(O&&B){var z=t.getRenderingCanvas();if(z){var J={width:z.width,height:z.height};t.setSize(B,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,b);ue.renderList=null,ue.samples=a,ue.renderSprites=p,ue.onAfterRenderObservable.add(function(){Xe.b.DumpFramebuffer(B,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 Co("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,b){r.CreateScreenshotUsingRenderTarget(t,e,n,function(x){x!==void 0?p(x):b(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}();Xe.b.CreateScreenshot=Ro.CreateScreenshot,Xe.b.CreateScreenshotAsync=Ro.CreateScreenshotAsync,Xe.b.CreateScreenshotUsingRenderTarget=Ro.CreateScreenshotUsingRenderTarget,Xe.b.CreateScreenshotUsingRenderTargetAsync=Ro.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"}(Xc||(Xc={}));var kr,lv=f(140),uv=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 Qn.a.Decode(this.readUint8Array(t))},r.prototype.skipBytes=function(t){this._dataByteOffset+=t,this.byteOffset+=t},r}(),hv=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}(),dv=function(){function r(){this._trackedScene=null}return r.prototype.track=function(t){this._trackedScene=t,this._savedJSON=Zc.Serialize(t)},r.prototype.getDelta=function(){if(!this._trackedScene)return null;var t=Zc.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,b=d.length,x=n._costMatrix;x[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}(),vf=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),x)}),x.scaleInPlace(a),d.chars[z].addInPlace(x),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}(),pv=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=vf.Deserialize(e.vector3Alphabet),n._levenshteinAlphabet=kr.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=ai.FEATURE_POINTS,t.Version=1,t}(si);qn.AddWebXRFeature(Va.Name,function(r){return function(){return new Va(r)}},Va.Version);var yf=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 b=p.transform.position,x=p.transform.orientation;a.position.set(b.x,b.y,b.z),a.rotationQuaternion.set(x.x,x.y,x.z,x.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 va("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(b){return b+(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(),Xe.b.Error("error loading hand mesh"),console.log(d),[3,4];case 4:return[2]}})})},r}(),ka=function(r){function t(e,n){var i=r.call(this,e)||this;return i.options=n,i.onHandAddedObservable=new R.c,i.onHandRemovedObservable=new R.c,i._hands={},i._attachHand=function(o){var a,s,d,p,b,x,O,B,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)||Un.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&&v._OperatorPriority[V()]>=v._OperatorPriority[de];)D.push(X());I(de),j++}else ne+=te;j++}for(N();w!==-1;)V()==="("?X():D.push(X());return D},v._OperatorPriority={")":0,"(":1,"||":2,"&&":3},v._Stack=["","","","","","","","","","","","","","","","","","","",""],v}(),m=function(v){function E(D,w){w===void 0&&(w=!1);var N=v.call(this)||this;return N.define=D,N.not=w,N}return Object(u.d)(E,v),E.prototype.isTrue=function(D){var w=D[this.define]!==void 0;return this.not&&(w=!w),w},E}(P),c=function(v){function E(){return v!==null&&v.apply(this,arguments)||this}return Object(u.d)(E,v),E.prototype.isTrue=function(D){return this.leftOperand.isTrue(D)||this.rightOperand.isTrue(D)},E}(P),T=function(v){function E(){return v!==null&&v.apply(this,arguments)||this}return Object(u.d)(E,v),E.prototype.isTrue=function(D){return this.leftOperand.isTrue(D)&&this.rightOperand.isTrue(D)},E}(P),A=function(v){function E(D,w,N){var I=v.call(this)||this;return I.define=D,I.operand=w,I.testValue=N,I}return Object(u.d)(E,v),E.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},E}(P),S=f(21),g=/defined\s*?\((.+?)\)/g,l=/defined\s*?\[(.+?)\]/g,h=function(){function v(){}return v.Process=function(E,D,w,N){var I=this;this._ProcessIncludes(E,D,function(V){var X=I._ProcessShaderConversion(V,D,N);w(X)})},v._ProcessPrecision=function(E,D){var w=D.shouldUseHighPrecisionShader;return E.indexOf("precision highp float")===-1?E=w?`precision highp float; -`+E:`precision mediump float; -`+E:w||(E=E.replace("precision highp float","precision mediump float")),E},v._ExtractOperation=function(E){var D=/defined\((.+)\)/.exec(E);if(D&&D.length)return new m(D[1].trim(),E[0]==="!");for(var w="",N=0,I=0,V=["==",">=","<=","<",">"];I-1));I++);if(N===-1)return new m(E);var X=E.substring(0,N).trim(),j=E.substring(N+w.length).trim();return new A(X,w,j)},v._BuildSubExpression=function(E){E=E.replace(g,"defined[$1]");for(var D=[],w=0,N=P.infixToPostfix(E);w=2){var V=D[D.length-1],X=D[D.length-2];D.length-=2;var j=I=="&&"?new T:new c;typeof V=="string"&&(V=V.replace(l,"defined($1)")),typeof X=="string"&&(X=X.replace(l,"defined($1)")),j.leftOperand=typeof X=="string"?this._ExtractOperation(X):X,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},v._BuildExpression=function(E,D){var w=new C,N=E.substring(0,D),I=E.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},v._MoveCursorWithinIf=function(E,D,w){for(var N=E.currentLine;this._MoveCursor(E,w);){var I=(N=E.currentLine).substring(0,5).toLowerCase();if(I==="#else"){var V=new _;return D.children.push(V),void this._MoveCursor(E,V)}if(I==="#elif"){var X=this._BuildExpression(N,5);D.children.push(X),w=X}}},v._MoveCursor=function(E,D){for(;E.canRead;){E.lineIndex++;var w=E.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(E,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(E,I,V);break;case"#if":I=new M,V=this._BuildExpression(w,3),D.children.push(I),I.children.push(V),this._MoveCursorWithinIf(E,I,V)}else{var X=new _;if(X.line=w,D.children.push(X),w[0]==="#"&&w[1]==="d"){var j=w.replace(";","").split(" ");X.additionalDefineKey=j[1],j.length===3&&(X.additionalDefineValue=j[2])}}}return!1},v._EvaluatePreProcessors=function(E,D,w){var N=new _,I=new R;return I.lineIndex=-1,I.lines=E.split(` -`),this._MoveCursor(I,N),N.process(D,w)},v._PreparePreProcessors=function(E){for(var D={},w=0,N=E.defines;w1?I[1]:""}return D.GL_ES="true",D.__VERSION__=E.version,D[E.platformName]="true",D},v._ProcessShaderConversion=function(E,D,w){var N=this._ProcessPrecision(E,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},v._ProcessIncludes=function(E,D,w){for(var N=this,I=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,V=I.exec(E),X=new String(E),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 v._FileToolsLoadFile(te,function(Y){D.includesShadersStore[ne]=Y,N._ProcessIncludes(X,D,w)})}var de=D.includesShadersStore[ne];if(V[2])for(var pe=V[3].split(","),ae=0;ae=0,V=I.exec(E)}j?this._ProcessIncludes(X.toString(),D,w):w(X)},v._FileToolsLoadFile=function(E,D,w,N,I,V){throw S.a.WarnImport("FileTools")},v}()},function(Ie,y,f){f(26).a.prototype._readTexturePixels=function(U,_,R,u,M,C){u===void 0&&(u=-1),M===void 0&&(M=0),C===void 0&&(C=null);var P=this._gl;if(!P)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){var m=P.createFramebuffer();if(!m)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=m}P.bindFramebuffer(P.FRAMEBUFFER,this._dummyFramebuffer),u>-1?P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_CUBE_MAP_POSITIVE_X+u,U._webGLTexture,M):P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,U._webGLTexture,M);var c=U.type!==void 0?this._getWebGLTextureType(U.type):P.UNSIGNED_BYTE;switch(c){case P.UNSIGNED_BYTE:C||(C=new Uint8Array(4*_*R)),c=P.UNSIGNED_BYTE;break;default:C||(C=new Float32Array(4*_*R)),c=P.FLOAT}return P.readPixels(0,0,_,R,P.RGBA,c,C),P.bindFramebuffer(P.FRAMEBUFFER,this._currentFramebuffer),C}},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U=`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=U},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U=`#ifdef FOG -float fog=CalcFogFactor(); -color.rgb=fog*color.rgb+(1.0-fog)*vFogColor; -#endif`;f(5).a.IncludesShadersStore.fogFragment=U},function(Ie,y,f){var U="fogVertexDeclaration",_=`#ifdef FOG -varying vec3 vFogDistance; -#endif`;f(5).a.IncludesShadersStore[U]=_},function(Ie,y,f){var U="shadowsVertex",_=`#ifdef SHADOWS -#if defined(SHADOWCSM{X}) -vPositionFromCamera{X}=view*worldPos; -for (int i=0; i1)for(var T=0;T=R||M.indexOf("file:")!==-1?-1:Math.pow(2,P)*u}},_}()},function(Ie,y,f){f.d(y,"a",function(){return U});var U=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(R){this._zOffset!==R&&(this._zOffset=R,this._isZOffsetDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"cullFace",{get:function(){return this._cullFace},set:function(R){this._cullFace!==R&&(this._cullFace=R,this._isCullFaceDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"cull",{get:function(){return this._cull},set:function(R){this._cull!==R&&(this._cull=R,this._isCullDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(R){this._depthFunc!==R&&(this._depthFunc=R,this._isDepthFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"depthMask",{get:function(){return this._depthMask},set:function(R){this._depthMask!==R&&(this._depthMask=R,this._isDepthMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"depthTest",{get:function(){return this._depthTest},set:function(R){this._depthTest!==R&&(this._depthTest=R,this._isDepthTestDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"frontFace",{get:function(){return this._frontFace},set:function(R){this._frontFace!==R&&(this._frontFace=R,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(R){this.isDirty&&(this._isCullDirty&&(this.cull?R.enable(R.CULL_FACE):R.disable(R.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(R.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(R.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?R.enable(R.DEPTH_TEST):R.disable(R.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(R.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset?(R.enable(R.POLYGON_OFFSET_FILL),R.polygonOffset(this.zOffset,0)):R.disable(R.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(R.frontFace(this.frontFace),this._isFrontFaceDirty=!1))},_}()},function(Ie,y,f){f.d(y,"a",function(){return _});var U=f(2),_=function(){function R(){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.reset()}return Object.defineProperty(R.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!1,configurable:!0}),Object.defineProperty(R.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(R.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(R.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(R.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(R.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(R.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(R.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(R.prototype,"stencilTest",{get:function(){return this._stencilTest},set:function(u){this._stencilTest!==u&&(this._stencilTest=u,this._isStencilTestDirty=!0)},enumerable:!1,configurable:!0}),R.prototype.reset=function(){this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=R.ALWAYS,this._stencilFuncRef=1,this._stencilFuncMask=255,this._stencilOpStencilFail=R.KEEP,this._stencilOpDepthFail=R.KEEP,this._stencilOpStencilDepthPass=R.REPLACE,this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},R.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))},R.ALWAYS=U.a.ALWAYS,R.KEEP=U.a.KEEP,R.REPLACE=U.a.REPLACE,R}()},function(Ie,y,f){f.d(y,"a",function(){return U});var U=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(R){this._alphaBlend!==R&&(this._alphaBlend=R,this._isAlphaBlendDirty=!0)},enumerable:!1,configurable:!0}),_.prototype.setAlphaBlendConstants=function(R,u,M,C){this._blendConstants[0]===R&&this._blendConstants[1]===u&&this._blendConstants[2]===M&&this._blendConstants[3]===C||(this._blendConstants[0]=R,this._blendConstants[1]=u,this._blendConstants[2]=M,this._blendConstants[3]=C,this._isBlendConstantsDirty=!0)},_.prototype.setAlphaBlendFunctionParameters=function(R,u,M,C){this._blendFunctionParameters[0]===R&&this._blendFunctionParameters[1]===u&&this._blendFunctionParameters[2]===M&&this._blendFunctionParameters[3]===C||(this._blendFunctionParameters[0]=R,this._blendFunctionParameters[1]=u,this._blendFunctionParameters[2]=M,this._blendFunctionParameters[3]=C,this._isBlendFunctionParametersDirty=!0)},_.prototype.setAlphaEquationParameters=function(R,u){this._blendEquationParameters[0]===R&&this._blendEquationParameters[1]===u||(this._blendEquationParameters[0]=R,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(R){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?R.enable(R.BLEND):R.disable(R.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(R.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(R.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(R.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))},_}()},function(Ie,y,f){f.d(y,"a",function(){return U});var U=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(R){R&&this.program&&R(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(Ie,y,f){var U;f.d(y,"a",function(){return u}),function(M){M[M.Pending=0]="Pending",M[M.Fulfilled=1]="Fulfilled",M[M.Rejected=2]="Rejected"}(U||(U={}));var _=function(){this.count=0,this.target=0,this.results=[]},R=function(){function M(C){var P=this;if(this._state=U.Pending,this._children=new Array,this._rejectWasConsumed=!1,C)try{C(function(m){P._resolve(m)},function(m){P._reject(m)})}catch(m){this._reject(m)}}return Object.defineProperty(M.prototype,"_result",{get:function(){return this._resultValue},set:function(C){this._resultValue=C,this._parent&&this._parent._result===void 0&&(this._parent._result=C)},enumerable:!1,configurable:!0}),M.prototype.catch=function(C){return this.then(void 0,C)},M.prototype.then=function(C,P){var m=this,c=new M;return c._onFulfilled=C,c._onRejected=P,this._children.push(c),c._parent=this,this._state!==U.Pending&&setTimeout(function(){if(m._state===U.Fulfilled||m._rejectWasConsumed){var T=c._resolve(m._result);if(T!=null)if(T._state!==void 0){var A=T;c._children.push(A),A._parent=c,c=A}else c._result=T}else c._reject(m._reason)}),c},M.prototype._moveChildren=function(C){var P,m=this;if((P=this._children).push.apply(P,C.splice(0,C.length)),this._children.forEach(function(g){g._parent=m}),this._state===U.Fulfilled)for(var c=0,T=this._children;c"u")&&(window.Promise=R)},M}()},function(Ie,y,f){f.d(y,"a",function(){return _}),f.d(y,"b",function(){return R});var U=f(57),_=function(){function u(M){M===void 0&&(M=30),this._enabled=!0,this._rollingFrameTime=new R(M)}return u.prototype.sampleFrame=function(M){if(M===void 0&&(M=U.a.Now),this._enabled){if(this._lastFrameTimeMs!=null){var C=M-this._lastFrameTimeMs;this._rollingFrameTime.add(C)}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}(),R=function(){function u(M){this._samples=new Array(M),this.reset()}return u.prototype.add=function(M){var C;if(this.isSaturated()){var P=this._samples[this._pos];C=P-this.average,this.average-=C/(this._sampleCount-1),this._m2-=C*(P-this.average)}else this._sampleCount++;C=M-this.average,this.average+=C/this._sampleCount,this._m2+=C*(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 C=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(C-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 C=this._samples.length;return(M%C+C)%C},u}()},function(Ie,y,f){f.d(y,"a",function(){return _});var U=f(0),_=function(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new U.e(0,0,0),this._diffPositionForCollisions=new U.e(0,0,0),this._collisionResponse=!0}},function(Ie,y,f){f.d(y,"a",function(){return u});var U=f(33),_=f(0),R=f(2),u=function(){function M(C,P,m,c,T){m===void 0&&(m=null),c===void 0&&(c=null),T===void 0&&(T=null),this.index=C,this._opaqueSubMeshes=new U.a(256),this._transparentSubMeshes=new U.a(256),this._alphaTestSubMeshes=new U.a(256),this._depthOnlySubMeshes=new U.a(256),this._particleSystems=new U.a(256),this._spriteManagers=new U.a(256),this._edgesRenderers=new U.b(16),this._scene=P,this.opaqueSortCompareFn=m,this.alphaTestSortCompareFn=c,this.transparentSortCompareFn=T}return Object.defineProperty(M.prototype,"opaqueSortCompareFn",{set:function(C){this._opaqueSortCompareFn=C,this._renderOpaque=C?this.renderOpaqueSorted:M.renderUnsorted},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"alphaTestSortCompareFn",{set:function(C){this._alphaTestSortCompareFn=C,this._renderAlphaTest=C?this.renderAlphaTestSorted:M.renderUnsorted},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"transparentSortCompareFn",{set:function(C){this._transparentSortCompareFn=C||M.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!1,configurable:!0}),M.prototype.render=function(C,P,m,c){if(C)C(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);else{var T=this._scene.getEngine();this._depthOnlySubMeshes.length!==0&&(T.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),T.setColorWrite(!0)),this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);var A=T.getStencilBuffer();if(T.setStencilBuffer(!1),P&&this._renderSprites(),m&&this._renderParticles(c),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),this._transparentSubMeshes.length!==0&&(T.setStencilBuffer(A),this._renderTransparent(this._transparentSubMeshes),T.setAlphaMode(R.a.ALPHA_DISABLE)),T.setStencilBuffer(!1),this._edgesRenderers.length){for(var S=0;SP._alphaIndex?1:C._alphaIndexP._distanceToCamera?-1:0},M.frontToBackSortCompare=function(C,P){return C._distanceToCameraP._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(C,P,m){P===void 0&&(P=C.getMesh()),m===void 0&&(m=C.getMaterial()),m!=null&&(m.needAlphaBlendingForMesh(P)?this._transparentSubMeshes.push(C):m.needAlphaTesting()?(m.needDepthPrePass&&this._depthOnlySubMeshes.push(C),this._alphaTestSubMeshes.push(C)):(m.needDepthPrePass&&this._depthOnlySubMeshes.push(C),this._opaqueSubMeshes.push(C)),P._renderingGroup=this,P._edgesRenderer&&P._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(P._edgesRenderer))},M.prototype.dispatchSprites=function(C){this._spriteManagers.push(C)},M.prototype.dispatchParticles=function(C){this._particleSystems.push(C)},M.prototype._renderParticles=function(C){if(this._particleSystems.length!==0){var P=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var m=0;m=0;){var g=P[A];g<0?g=0:g>1&&(g=1),S[A]=255*g}P=S}var l=document.createElement("canvas");l.width=c,l.height=T;var h=l.getContext("2d");if(!h)return null;var v=h.createImageData(c,T);if(v.data.set(P),h.putImageData(v,0,0),C.invertY){var E=document.createElement("canvas");E.width=c,E.height=T;var D=E.getContext("2d");return D?(D.translate(0,T),D.scale(1,-1),D.drawImage(l,0,0),E.toDataURL("image/png")):null}return l.toDataURL("image/png")},_}()},function(Ie,y,f){f.d(y,"a",function(){return A});var U=f(1),_=f(0),R=f(8),u=f(31),M=f(7),C=f(41),P=f(46),m=f(4),c=f(43),T=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 v=S.call(this,l,h.getScene())||this;v._indexInSourceMeshInstanceArray=-1,h.addInstance(v),v._sourceMesh=h,v._unIndexed=h._unIndexed,v.position.copyFrom(h.position),v.rotation.copyFrom(h.rotation),v.scaling.copyFrom(h.scaling),h.rotationQuaternion&&(v.rotationQuaternion=h.rotationQuaternion.clone()),v.animations=T.b.Slice(h.animations);for(var E=0,D=h.getAnimationRanges();E0!=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!==P.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[U]=_},function(Ie,y,f){var U="logDepthFragment",_=`#ifdef LOGARITHMICDEPTH -gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; -#endif`;f(5).a.IncludesShadersStore[U]=_},function(Ie,y,f){var U=`#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=U},function(Ie,y,f){var U=`#ifdef FOG -vFogDistance=(view*worldPos).xyz; -#endif`;f(5).a.IncludesShadersStore.fogVertex=U},function(Ie,y,f){var U="logDepthVertex",_=`#ifdef LOGARITHMICDEPTH -vFragmentDepth=1.0+gl_Position.w; -gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; -#endif`;f(5).a.IncludesShadersStore[U]=_},function(Ie,y){var f;f=function(){return this}();try{f=f||new Function("return this")()}catch{typeof window=="object"&&(f=window)}Ie.exports=f},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U=`#ifdef DEPTHPREPASS -gl_FragColor=vec4(0.,0.,0.,1.0); -return; -#endif`;f(5).a.IncludesShadersStore.depthPrePass=U},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U="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[U]=_},function(Ie,y,f){var U=f(5),_=(f(115),f(110),"colorPixelShader"),R=`#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 -}`;U.a.ShadersStore[_]=R},function(Ie,y,f){var U=f(5),_=(f(78),f(117),f(79),f(80),f(81),f(111),"colorVertexShader"),R=` -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 -}`;U.a.ShadersStore[_]=R},function(Ie,y,f){(function(U){f.d(y,"b",function(){return T}),f.d(y,"a",function(){return A});var _=f(1),R=f(8),u=f(13),M=f(102),C=f(27),P=f(2),m=f(89),c=f(74),T=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 T);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},R.a.Log("Babylon.js v"+u.a.Version+" - Null engine");var v=typeof self<"u"?self:U!==void 0?U:window;return typeof URL>"u"&&(v.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(v.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,v,E){},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,v){this._cachedViewport=l},g.prototype.createShaderProgram=function(l,h,v,E,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,v,E){},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,v){return!0},g.prototype.setFloat3=function(l,h,v,E){return!0},g.prototype.setBool=function(l,h){return!0},g.prototype.setFloat4=function(l,h,v,E,D){return!0},g.prototype.setAlphaMode=function(l,h){h===void 0&&(h=!1),this._alphaMode!==l&&(this.alphaState.alphaBlend=l!==P.a.ALPHA_DISABLE,h||this.setDepthWrite(l===P.a.ALPHA_DISABLE),this._alphaMode=l)},g.prototype.bindBuffers=function(l,h,v){},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,v,E){},g.prototype.drawElementsType=function(l,h,v,E){},g.prototype.drawArraysType=function(l,h,v,E){},g.prototype._createTexture=function(){return{}},g.prototype._releaseTexture=function(l){},g.prototype.createTexture=function(l,h,v,E,D,w,N,I,V,X,j,ne){D===void 0&&(D=P.a.TEXTURE_TRILINEAR_SAMPLINGMODE),w===void 0&&(w=null),X===void 0&&(X=null);var te=new C.a(this,C.b.Url),de=String(l);return te.url=de,te.generateMipMaps=!h,te.samplingMode=D,te.invertY=v,te.baseWidth=this._options.textureSize,te.baseHeight=this._options.textureSize,te.width=this._options.textureSize,te.height=this._options.textureSize,X&&(te.format=X),te.isReady=!0,w&&w(),this._internalTexturesCache.push(te),te},g.prototype.createRenderTargetTexture=function(l,h){var v=new M.a;h!==void 0&&typeof h=="object"?(v.generateMipMaps=h.generateMipMaps,v.generateDepthBuffer=h.generateDepthBuffer===void 0||h.generateDepthBuffer,v.generateStencilBuffer=v.generateDepthBuffer&&h.generateStencilBuffer,v.type=h.type===void 0?P.a.TEXTURETYPE_UNSIGNED_INT:h.type,v.samplingMode=h.samplingMode===void 0?P.a.TEXTURE_TRILINEAR_SAMPLINGMODE:h.samplingMode):(v.generateMipMaps=h,v.generateDepthBuffer=!0,v.generateStencilBuffer=!1,v.type=P.a.TEXTURETYPE_UNSIGNED_INT,v.samplingMode=P.a.TEXTURE_TRILINEAR_SAMPLINGMODE);var E=new C.a(this,C.b.RenderTarget),D=l.width||l,w=l.height||l;return E._depthStencilBuffer={},E._framebuffer={},E.baseWidth=D,E.baseHeight=w,E.width=D,E.height=w,E.isReady=!0,E.samples=1,E.generateMipMaps=!!v.generateMipMaps,E.samplingMode=v.samplingMode,E.type=v.type,E._generateDepthBuffer=v.generateDepthBuffer,E._generateStencilBuffer=!!v.generateStencilBuffer,this._internalTexturesCache.push(E),E},g.prototype.updateTextureSamplingMode=function(l,h){h.samplingMode=l},g.prototype.bindFramebuffer=function(l,h,v,E,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,v,E)},g.prototype.unBindFramebuffer=function(l,h,v){this._currentRenderTarget=null,v&&(l._MSAAFramebuffer&&(this._currentFramebuffer=l._framebuffer),v()),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,v,E,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,v){},g.prototype.updateDynamicVertexBuffer=function(l,h,v,E){},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,v,E,D,w,N){},g.prototype._uploadDataToTextureDirectly=function(l,h,v,E){},g.prototype._uploadArrayBufferViewToTexture=function(l,h,v,E){},g.prototype._uploadImageToTexture=function(l,h,v,E){},g}(u.a)}).call(this,f(159))},function(Ie,y,f){f.r(y),function(U){f.d(y,"Debug",function(){return m});var _=f(127),R=f(99);f.d(y,"AbstractScene",function(){return _.AbstractScene}),f.d(y,"AbstractActionManager",function(){return _.AbstractActionManager}),f.d(y,"Action",function(){return _.Action}),f.d(y,"ActionEvent",function(){return _.ActionEvent}),f.d(y,"ActionManager",function(){return _.ActionManager}),f.d(y,"Condition",function(){return _.Condition}),f.d(y,"ValueCondition",function(){return _.ValueCondition}),f.d(y,"PredicateCondition",function(){return _.PredicateCondition}),f.d(y,"StateCondition",function(){return _.StateCondition}),f.d(y,"SwitchBooleanAction",function(){return _.SwitchBooleanAction}),f.d(y,"SetStateAction",function(){return _.SetStateAction}),f.d(y,"SetValueAction",function(){return _.SetValueAction}),f.d(y,"IncrementValueAction",function(){return _.IncrementValueAction}),f.d(y,"PlayAnimationAction",function(){return _.PlayAnimationAction}),f.d(y,"StopAnimationAction",function(){return _.StopAnimationAction}),f.d(y,"DoNothingAction",function(){return _.DoNothingAction}),f.d(y,"CombineAction",function(){return _.CombineAction}),f.d(y,"ExecuteCodeAction",function(){return _.ExecuteCodeAction}),f.d(y,"SetParentAction",function(){return _.SetParentAction}),f.d(y,"PlaySoundAction",function(){return _.PlaySoundAction}),f.d(y,"StopSoundAction",function(){return _.StopSoundAction}),f.d(y,"InterpolateValueAction",function(){return _.InterpolateValueAction}),f.d(y,"Animatable",function(){return _.Animatable}),f.d(y,"_IAnimationState",function(){return _._IAnimationState}),f.d(y,"Animation",function(){return _.Animation}),f.d(y,"TargetedAnimation",function(){return _.TargetedAnimation}),f.d(y,"AnimationGroup",function(){return _.AnimationGroup}),f.d(y,"AnimationPropertiesOverride",function(){return _.AnimationPropertiesOverride}),f.d(y,"EasingFunction",function(){return _.EasingFunction}),f.d(y,"CircleEase",function(){return _.CircleEase}),f.d(y,"BackEase",function(){return _.BackEase}),f.d(y,"BounceEase",function(){return _.BounceEase}),f.d(y,"CubicEase",function(){return _.CubicEase}),f.d(y,"ElasticEase",function(){return _.ElasticEase}),f.d(y,"ExponentialEase",function(){return _.ExponentialEase}),f.d(y,"PowerEase",function(){return _.PowerEase}),f.d(y,"QuadraticEase",function(){return _.QuadraticEase}),f.d(y,"QuarticEase",function(){return _.QuarticEase}),f.d(y,"QuinticEase",function(){return _.QuinticEase}),f.d(y,"SineEase",function(){return _.SineEase}),f.d(y,"BezierCurveEase",function(){return _.BezierCurveEase}),f.d(y,"RuntimeAnimation",function(){return _.RuntimeAnimation}),f.d(y,"AnimationEvent",function(){return _.AnimationEvent}),f.d(y,"AnimationKeyInterpolation",function(){return _.AnimationKeyInterpolation}),f.d(y,"AnimationRange",function(){return _.AnimationRange}),f.d(y,"KeepAssets",function(){return _.KeepAssets}),f.d(y,"InstantiatedEntries",function(){return _.InstantiatedEntries}),f.d(y,"AssetContainer",function(){return _.AssetContainer}),f.d(y,"Analyser",function(){return _.Analyser}),f.d(y,"AudioEngine",function(){return _.AudioEngine}),f.d(y,"AudioSceneComponent",function(){return _.AudioSceneComponent}),f.d(y,"Sound",function(){return _.Sound}),f.d(y,"SoundTrack",function(){return _.SoundTrack}),f.d(y,"WeightedSound",function(){return _.WeightedSound}),f.d(y,"AutoRotationBehavior",function(){return _.AutoRotationBehavior}),f.d(y,"BouncingBehavior",function(){return _.BouncingBehavior}),f.d(y,"FramingBehavior",function(){return _.FramingBehavior}),f.d(y,"AttachToBoxBehavior",function(){return _.AttachToBoxBehavior}),f.d(y,"FadeInOutBehavior",function(){return _.FadeInOutBehavior}),f.d(y,"MultiPointerScaleBehavior",function(){return _.MultiPointerScaleBehavior}),f.d(y,"PointerDragBehavior",function(){return _.PointerDragBehavior}),f.d(y,"SixDofDragBehavior",function(){return _.SixDofDragBehavior}),f.d(y,"Bone",function(){return _.Bone}),f.d(y,"BoneIKController",function(){return _.BoneIKController}),f.d(y,"BoneLookController",function(){return _.BoneLookController}),f.d(y,"Skeleton",function(){return _.Skeleton}),f.d(y,"ArcRotateCameraGamepadInput",function(){return _.ArcRotateCameraGamepadInput}),f.d(y,"ArcRotateCameraKeyboardMoveInput",function(){return _.ArcRotateCameraKeyboardMoveInput}),f.d(y,"ArcRotateCameraMouseWheelInput",function(){return _.ArcRotateCameraMouseWheelInput}),f.d(y,"ArcRotateCameraPointersInput",function(){return _.ArcRotateCameraPointersInput}),f.d(y,"ArcRotateCameraVRDeviceOrientationInput",function(){return _.ArcRotateCameraVRDeviceOrientationInput}),f.d(y,"FlyCameraKeyboardInput",function(){return _.FlyCameraKeyboardInput}),f.d(y,"FlyCameraMouseInput",function(){return _.FlyCameraMouseInput}),f.d(y,"FollowCameraKeyboardMoveInput",function(){return _.FollowCameraKeyboardMoveInput}),f.d(y,"FollowCameraMouseWheelInput",function(){return _.FollowCameraMouseWheelInput}),f.d(y,"FollowCameraPointersInput",function(){return _.FollowCameraPointersInput}),f.d(y,"FreeCameraDeviceOrientationInput",function(){return _.FreeCameraDeviceOrientationInput}),f.d(y,"FreeCameraGamepadInput",function(){return _.FreeCameraGamepadInput}),f.d(y,"FreeCameraKeyboardMoveInput",function(){return _.FreeCameraKeyboardMoveInput}),f.d(y,"FreeCameraMouseInput",function(){return _.FreeCameraMouseInput}),f.d(y,"FreeCameraMouseWheelInput",function(){return _.FreeCameraMouseWheelInput}),f.d(y,"FreeCameraTouchInput",function(){return _.FreeCameraTouchInput}),f.d(y,"FreeCameraVirtualJoystickInput",function(){return _.FreeCameraVirtualJoystickInput}),f.d(y,"CameraInputTypes",function(){return _.CameraInputTypes}),f.d(y,"CameraInputsManager",function(){return _.CameraInputsManager}),f.d(y,"Camera",function(){return _.Camera}),f.d(y,"TargetCamera",function(){return _.TargetCamera}),f.d(y,"FreeCamera",function(){return _.FreeCamera}),f.d(y,"FreeCameraInputsManager",function(){return _.FreeCameraInputsManager}),f.d(y,"TouchCamera",function(){return _.TouchCamera}),f.d(y,"ArcRotateCamera",function(){return _.ArcRotateCamera}),f.d(y,"ArcRotateCameraInputsManager",function(){return _.ArcRotateCameraInputsManager}),f.d(y,"DeviceOrientationCamera",function(){return _.DeviceOrientationCamera}),f.d(y,"FlyCamera",function(){return _.FlyCamera}),f.d(y,"FlyCameraInputsManager",function(){return _.FlyCameraInputsManager}),f.d(y,"FollowCamera",function(){return _.FollowCamera}),f.d(y,"ArcFollowCamera",function(){return _.ArcFollowCamera}),f.d(y,"FollowCameraInputsManager",function(){return _.FollowCameraInputsManager}),f.d(y,"GamepadCamera",function(){return _.GamepadCamera}),f.d(y,"AnaglyphArcRotateCamera",function(){return _.AnaglyphArcRotateCamera}),f.d(y,"AnaglyphFreeCamera",function(){return _.AnaglyphFreeCamera}),f.d(y,"AnaglyphGamepadCamera",function(){return _.AnaglyphGamepadCamera}),f.d(y,"AnaglyphUniversalCamera",function(){return _.AnaglyphUniversalCamera}),f.d(y,"StereoscopicArcRotateCamera",function(){return _.StereoscopicArcRotateCamera}),f.d(y,"StereoscopicFreeCamera",function(){return _.StereoscopicFreeCamera}),f.d(y,"StereoscopicGamepadCamera",function(){return _.StereoscopicGamepadCamera}),f.d(y,"StereoscopicUniversalCamera",function(){return _.StereoscopicUniversalCamera}),f.d(y,"UniversalCamera",function(){return _.UniversalCamera}),f.d(y,"VirtualJoysticksCamera",function(){return _.VirtualJoysticksCamera}),f.d(y,"VRCameraMetrics",function(){return _.VRCameraMetrics}),f.d(y,"VRDeviceOrientationArcRotateCamera",function(){return _.VRDeviceOrientationArcRotateCamera}),f.d(y,"VRDeviceOrientationFreeCamera",function(){return _.VRDeviceOrientationFreeCamera}),f.d(y,"VRDeviceOrientationGamepadCamera",function(){return _.VRDeviceOrientationGamepadCamera}),f.d(y,"OnAfterEnteringVRObservableEvent",function(){return _.OnAfterEnteringVRObservableEvent}),f.d(y,"VRExperienceHelper",function(){return _.VRExperienceHelper}),f.d(y,"WebVRFreeCamera",function(){return _.WebVRFreeCamera}),f.d(y,"Collider",function(){return _.Collider}),f.d(y,"DefaultCollisionCoordinator",function(){return _.DefaultCollisionCoordinator}),f.d(y,"PickingInfo",function(){return _.PickingInfo}),f.d(y,"IntersectionInfo",function(){return _.IntersectionInfo}),f.d(y,"_MeshCollisionData",function(){return _._MeshCollisionData}),f.d(y,"BoundingBox",function(){return _.BoundingBox}),f.d(y,"BoundingInfo",function(){return _.BoundingInfo}),f.d(y,"BoundingSphere",function(){return _.BoundingSphere}),f.d(y,"Octree",function(){return _.Octree}),f.d(y,"OctreeBlock",function(){return _.OctreeBlock}),f.d(y,"OctreeSceneComponent",function(){return _.OctreeSceneComponent}),f.d(y,"Ray",function(){return _.Ray}),f.d(y,"AxesViewer",function(){return _.AxesViewer}),f.d(y,"BoneAxesViewer",function(){return _.BoneAxesViewer}),f.d(y,"DebugLayerTab",function(){return _.DebugLayerTab}),f.d(y,"DebugLayer",function(){return _.DebugLayer}),f.d(y,"PhysicsViewer",function(){return _.PhysicsViewer}),f.d(y,"RayHelper",function(){return _.RayHelper}),f.d(y,"SkeletonViewer",function(){return _.SkeletonViewer}),f.d(y,"DeviceInputSystem",function(){return _.DeviceInputSystem}),f.d(y,"DeviceType",function(){return _.DeviceType}),f.d(y,"PointerInput",function(){return _.PointerInput}),f.d(y,"DualShockInput",function(){return _.DualShockInput}),f.d(y,"XboxInput",function(){return _.XboxInput}),f.d(y,"SwitchInput",function(){return _.SwitchInput}),f.d(y,"DeviceSource",function(){return _.DeviceSource}),f.d(y,"DeviceSourceManager",function(){return _.DeviceSourceManager}),f.d(y,"Constants",function(){return _.Constants}),f.d(y,"ThinEngine",function(){return _.ThinEngine}),f.d(y,"Engine",function(){return _.Engine}),f.d(y,"EngineStore",function(){return _.EngineStore}),f.d(y,"NullEngineOptions",function(){return _.NullEngineOptions}),f.d(y,"NullEngine",function(){return _.NullEngine}),f.d(y,"_OcclusionDataStorage",function(){return _._OcclusionDataStorage}),f.d(y,"_forceTransformFeedbackToBundle",function(){return _._forceTransformFeedbackToBundle}),f.d(y,"EngineView",function(){return _.EngineView}),f.d(y,"WebGLPipelineContext",function(){return _.WebGLPipelineContext}),f.d(y,"WebGL2ShaderProcessor",function(){return _.WebGL2ShaderProcessor}),f.d(y,"NativeEngine",function(){return _.NativeEngine}),f.d(y,"ShaderCodeInliner",function(){return _.ShaderCodeInliner}),f.d(y,"PerformanceConfigurator",function(){return _.PerformanceConfigurator}),f.d(y,"KeyboardEventTypes",function(){return _.KeyboardEventTypes}),f.d(y,"KeyboardInfo",function(){return _.KeyboardInfo}),f.d(y,"KeyboardInfoPre",function(){return _.KeyboardInfoPre}),f.d(y,"PointerEventTypes",function(){return _.PointerEventTypes}),f.d(y,"PointerInfoBase",function(){return _.PointerInfoBase}),f.d(y,"PointerInfoPre",function(){return _.PointerInfoPre}),f.d(y,"PointerInfo",function(){return _.PointerInfo}),f.d(y,"ClipboardEventTypes",function(){return _.ClipboardEventTypes}),f.d(y,"ClipboardInfo",function(){return _.ClipboardInfo}),f.d(y,"DaydreamController",function(){return _.DaydreamController}),f.d(y,"GearVRController",function(){return _.GearVRController}),f.d(y,"GenericController",function(){return _.GenericController}),f.d(y,"OculusTouchController",function(){return _.OculusTouchController}),f.d(y,"PoseEnabledControllerType",function(){return _.PoseEnabledControllerType}),f.d(y,"PoseEnabledControllerHelper",function(){return _.PoseEnabledControllerHelper}),f.d(y,"PoseEnabledController",function(){return _.PoseEnabledController}),f.d(y,"ViveController",function(){return _.ViveController}),f.d(y,"WebVRController",function(){return _.WebVRController}),f.d(y,"WindowsMotionController",function(){return _.WindowsMotionController}),f.d(y,"XRWindowsMotionController",function(){return _.XRWindowsMotionController}),f.d(y,"StickValues",function(){return _.StickValues}),f.d(y,"Gamepad",function(){return _.Gamepad}),f.d(y,"GenericPad",function(){return _.GenericPad}),f.d(y,"GamepadManager",function(){return _.GamepadManager}),f.d(y,"GamepadSystemSceneComponent",function(){return _.GamepadSystemSceneComponent}),f.d(y,"Xbox360Button",function(){return _.Xbox360Button}),f.d(y,"Xbox360Dpad",function(){return _.Xbox360Dpad}),f.d(y,"Xbox360Pad",function(){return _.Xbox360Pad}),f.d(y,"DualShockButton",function(){return _.DualShockButton}),f.d(y,"DualShockDpad",function(){return _.DualShockDpad}),f.d(y,"DualShockPad",function(){return _.DualShockPad}),f.d(y,"AxisDragGizmo",function(){return _.AxisDragGizmo}),f.d(y,"AxisScaleGizmo",function(){return _.AxisScaleGizmo}),f.d(y,"BoundingBoxGizmo",function(){return _.BoundingBoxGizmo}),f.d(y,"Gizmo",function(){return _.Gizmo}),f.d(y,"GizmoManager",function(){return _.GizmoManager}),f.d(y,"PlaneRotationGizmo",function(){return _.PlaneRotationGizmo}),f.d(y,"PositionGizmo",function(){return _.PositionGizmo}),f.d(y,"RotationGizmo",function(){return _.RotationGizmo}),f.d(y,"ScaleGizmo",function(){return _.ScaleGizmo}),f.d(y,"LightGizmo",function(){return _.LightGizmo}),f.d(y,"CameraGizmo",function(){return _.CameraGizmo}),f.d(y,"PlaneDragGizmo",function(){return _.PlaneDragGizmo}),f.d(y,"EnvironmentHelper",function(){return _.EnvironmentHelper}),f.d(y,"PhotoDome",function(){return _.PhotoDome}),f.d(y,"_forceSceneHelpersToBundle",function(){return _._forceSceneHelpersToBundle}),f.d(y,"VideoDome",function(){return _.VideoDome}),f.d(y,"EngineInstrumentation",function(){return _.EngineInstrumentation}),f.d(y,"SceneInstrumentation",function(){return _.SceneInstrumentation}),f.d(y,"_TimeToken",function(){return _._TimeToken}),f.d(y,"EffectLayer",function(){return _.EffectLayer}),f.d(y,"EffectLayerSceneComponent",function(){return _.EffectLayerSceneComponent}),f.d(y,"GlowLayer",function(){return _.GlowLayer}),f.d(y,"HighlightLayer",function(){return _.HighlightLayer}),f.d(y,"Layer",function(){return _.Layer}),f.d(y,"LayerSceneComponent",function(){return _.LayerSceneComponent}),f.d(y,"LensFlare",function(){return _.LensFlare}),f.d(y,"LensFlareSystem",function(){return _.LensFlareSystem}),f.d(y,"LensFlareSystemSceneComponent",function(){return _.LensFlareSystemSceneComponent}),f.d(y,"Light",function(){return _.Light}),f.d(y,"ShadowLight",function(){return _.ShadowLight}),f.d(y,"ShadowGenerator",function(){return _.ShadowGenerator}),f.d(y,"CascadedShadowGenerator",function(){return _.CascadedShadowGenerator}),f.d(y,"ShadowGeneratorSceneComponent",function(){return _.ShadowGeneratorSceneComponent}),f.d(y,"DirectionalLight",function(){return _.DirectionalLight}),f.d(y,"HemisphericLight",function(){return _.HemisphericLight}),f.d(y,"PointLight",function(){return _.PointLight}),f.d(y,"SpotLight",function(){return _.SpotLight}),f.d(y,"DefaultLoadingScreen",function(){return _.DefaultLoadingScreen}),f.d(y,"_BabylonLoaderRegistered",function(){return _._BabylonLoaderRegistered}),f.d(y,"BabylonFileLoaderConfiguration",function(){return _.BabylonFileLoaderConfiguration}),f.d(y,"SceneLoaderAnimationGroupLoadingMode",function(){return _.SceneLoaderAnimationGroupLoadingMode}),f.d(y,"SceneLoader",function(){return _.SceneLoader}),f.d(y,"SceneLoaderFlags",function(){return _.SceneLoaderFlags}),f.d(y,"BackgroundMaterial",function(){return _.BackgroundMaterial}),f.d(y,"ColorCurves",function(){return _.ColorCurves}),f.d(y,"EffectFallbacks",function(){return _.EffectFallbacks}),f.d(y,"Effect",function(){return _.Effect}),f.d(y,"FresnelParameters",function(){return _.FresnelParameters}),f.d(y,"ImageProcessingConfigurationDefines",function(){return _.ImageProcessingConfigurationDefines}),f.d(y,"ImageProcessingConfiguration",function(){return _.ImageProcessingConfiguration}),f.d(y,"Material",function(){return _.Material}),f.d(y,"MaterialDefines",function(){return _.MaterialDefines}),f.d(y,"ThinMaterialHelper",function(){return _.ThinMaterialHelper}),f.d(y,"MaterialHelper",function(){return _.MaterialHelper}),f.d(y,"MultiMaterial",function(){return _.MultiMaterial}),f.d(y,"PBRMaterialDefines",function(){return _.PBRMaterialDefines}),f.d(y,"PBRBaseMaterial",function(){return _.PBRBaseMaterial}),f.d(y,"PBRBaseSimpleMaterial",function(){return _.PBRBaseSimpleMaterial}),f.d(y,"PBRMaterial",function(){return _.PBRMaterial}),f.d(y,"PBRMetallicRoughnessMaterial",function(){return _.PBRMetallicRoughnessMaterial}),f.d(y,"PBRSpecularGlossinessMaterial",function(){return _.PBRSpecularGlossinessMaterial}),f.d(y,"PushMaterial",function(){return _.PushMaterial}),f.d(y,"ShaderMaterial",function(){return _.ShaderMaterial}),f.d(y,"StandardMaterialDefines",function(){return _.StandardMaterialDefines}),f.d(y,"StandardMaterial",function(){return _.StandardMaterial}),f.d(y,"BaseTexture",function(){return _.BaseTexture}),f.d(y,"ColorGradingTexture",function(){return _.ColorGradingTexture}),f.d(y,"CubeTexture",function(){return _.CubeTexture}),f.d(y,"DynamicTexture",function(){return _.DynamicTexture}),f.d(y,"EquiRectangularCubeTexture",function(){return _.EquiRectangularCubeTexture}),f.d(y,"HDRFiltering",function(){return _.HDRFiltering}),f.d(y,"HDRCubeTexture",function(){return _.HDRCubeTexture}),f.d(y,"HtmlElementTexture",function(){return _.HtmlElementTexture}),f.d(y,"InternalTextureSource",function(){return _.InternalTextureSource}),f.d(y,"InternalTexture",function(){return _.InternalTexture}),f.d(y,"_DDSTextureLoader",function(){return _._DDSTextureLoader}),f.d(y,"_ENVTextureLoader",function(){return _._ENVTextureLoader}),f.d(y,"_KTXTextureLoader",function(){return _._KTXTextureLoader}),f.d(y,"_TGATextureLoader",function(){return _._TGATextureLoader}),f.d(y,"_BasisTextureLoader",function(){return _._BasisTextureLoader}),f.d(y,"MirrorTexture",function(){return _.MirrorTexture}),f.d(y,"MultiRenderTarget",function(){return _.MultiRenderTarget}),f.d(y,"TexturePacker",function(){return _.TexturePacker}),f.d(y,"TexturePackerFrame",function(){return _.TexturePackerFrame}),f.d(y,"CustomProceduralTexture",function(){return _.CustomProceduralTexture}),f.d(y,"NoiseProceduralTexture",function(){return _.NoiseProceduralTexture}),f.d(y,"ProceduralTexture",function(){return _.ProceduralTexture}),f.d(y,"ProceduralTextureSceneComponent",function(){return _.ProceduralTextureSceneComponent}),f.d(y,"RawCubeTexture",function(){return _.RawCubeTexture}),f.d(y,"RawTexture",function(){return _.RawTexture}),f.d(y,"RawTexture2DArray",function(){return _.RawTexture2DArray}),f.d(y,"RawTexture3D",function(){return _.RawTexture3D}),f.d(y,"RefractionTexture",function(){return _.RefractionTexture}),f.d(y,"RenderTargetTexture",function(){return _.RenderTargetTexture}),f.d(y,"Texture",function(){return _.Texture}),f.d(y,"VideoTexture",function(){return _.VideoTexture}),f.d(y,"UniformBuffer",function(){return _.UniformBuffer}),f.d(y,"MaterialFlags",function(){return _.MaterialFlags}),f.d(y,"NodeMaterialBlockTargets",function(){return _.NodeMaterialBlockTargets}),f.d(y,"NodeMaterialBlockConnectionPointTypes",function(){return _.NodeMaterialBlockConnectionPointTypes}),f.d(y,"NodeMaterialBlockConnectionPointMode",function(){return _.NodeMaterialBlockConnectionPointMode}),f.d(y,"NodeMaterialSystemValues",function(){return _.NodeMaterialSystemValues}),f.d(y,"NodeMaterialModes",function(){return _.NodeMaterialModes}),f.d(y,"NodeMaterialConnectionPointCompatibilityStates",function(){return _.NodeMaterialConnectionPointCompatibilityStates}),f.d(y,"NodeMaterialConnectionPointDirection",function(){return _.NodeMaterialConnectionPointDirection}),f.d(y,"NodeMaterialConnectionPoint",function(){return _.NodeMaterialConnectionPoint}),f.d(y,"NodeMaterialBlock",function(){return _.NodeMaterialBlock}),f.d(y,"NodeMaterialDefines",function(){return _.NodeMaterialDefines}),f.d(y,"NodeMaterial",function(){return _.NodeMaterial}),f.d(y,"VertexOutputBlock",function(){return _.VertexOutputBlock}),f.d(y,"BonesBlock",function(){return _.BonesBlock}),f.d(y,"InstancesBlock",function(){return _.InstancesBlock}),f.d(y,"MorphTargetsBlock",function(){return _.MorphTargetsBlock}),f.d(y,"LightInformationBlock",function(){return _.LightInformationBlock}),f.d(y,"FragmentOutputBlock",function(){return _.FragmentOutputBlock}),f.d(y,"ImageProcessingBlock",function(){return _.ImageProcessingBlock}),f.d(y,"PerturbNormalBlock",function(){return _.PerturbNormalBlock}),f.d(y,"DiscardBlock",function(){return _.DiscardBlock}),f.d(y,"FrontFacingBlock",function(){return _.FrontFacingBlock}),f.d(y,"DerivativeBlock",function(){return _.DerivativeBlock}),f.d(y,"FragCoordBlock",function(){return _.FragCoordBlock}),f.d(y,"ScreenSizeBlock",function(){return _.ScreenSizeBlock}),f.d(y,"FogBlock",function(){return _.FogBlock}),f.d(y,"LightBlock",function(){return _.LightBlock}),f.d(y,"TextureBlock",function(){return _.TextureBlock}),f.d(y,"ReflectionTextureBlock",function(){return _.ReflectionTextureBlock}),f.d(y,"CurrentScreenBlock",function(){return _.CurrentScreenBlock}),f.d(y,"InputBlock",function(){return _.InputBlock}),f.d(y,"AnimatedInputBlockTypes",function(){return _.AnimatedInputBlockTypes}),f.d(y,"MultiplyBlock",function(){return _.MultiplyBlock}),f.d(y,"AddBlock",function(){return _.AddBlock}),f.d(y,"ScaleBlock",function(){return _.ScaleBlock}),f.d(y,"ClampBlock",function(){return _.ClampBlock}),f.d(y,"CrossBlock",function(){return _.CrossBlock}),f.d(y,"DotBlock",function(){return _.DotBlock}),f.d(y,"TransformBlock",function(){return _.TransformBlock}),f.d(y,"RemapBlock",function(){return _.RemapBlock}),f.d(y,"NormalizeBlock",function(){return _.NormalizeBlock}),f.d(y,"TrigonometryBlockOperations",function(){return _.TrigonometryBlockOperations}),f.d(y,"TrigonometryBlock",function(){return _.TrigonometryBlock}),f.d(y,"ColorMergerBlock",function(){return _.ColorMergerBlock}),f.d(y,"VectorMergerBlock",function(){return _.VectorMergerBlock}),f.d(y,"ColorSplitterBlock",function(){return _.ColorSplitterBlock}),f.d(y,"VectorSplitterBlock",function(){return _.VectorSplitterBlock}),f.d(y,"LerpBlock",function(){return _.LerpBlock}),f.d(y,"DivideBlock",function(){return _.DivideBlock}),f.d(y,"SubtractBlock",function(){return _.SubtractBlock}),f.d(y,"StepBlock",function(){return _.StepBlock}),f.d(y,"OneMinusBlock",function(){return _.OneMinusBlock}),f.d(y,"ViewDirectionBlock",function(){return _.ViewDirectionBlock}),f.d(y,"FresnelBlock",function(){return _.FresnelBlock}),f.d(y,"MaxBlock",function(){return _.MaxBlock}),f.d(y,"MinBlock",function(){return _.MinBlock}),f.d(y,"DistanceBlock",function(){return _.DistanceBlock}),f.d(y,"LengthBlock",function(){return _.LengthBlock}),f.d(y,"NegateBlock",function(){return _.NegateBlock}),f.d(y,"PowBlock",function(){return _.PowBlock}),f.d(y,"RandomNumberBlock",function(){return _.RandomNumberBlock}),f.d(y,"ArcTan2Block",function(){return _.ArcTan2Block}),f.d(y,"SmoothStepBlock",function(){return _.SmoothStepBlock}),f.d(y,"ReciprocalBlock",function(){return _.ReciprocalBlock}),f.d(y,"ReplaceColorBlock",function(){return _.ReplaceColorBlock}),f.d(y,"PosterizeBlock",function(){return _.PosterizeBlock}),f.d(y,"WaveBlockKind",function(){return _.WaveBlockKind}),f.d(y,"WaveBlock",function(){return _.WaveBlock}),f.d(y,"GradientBlockColorStep",function(){return _.GradientBlockColorStep}),f.d(y,"GradientBlock",function(){return _.GradientBlock}),f.d(y,"NLerpBlock",function(){return _.NLerpBlock}),f.d(y,"WorleyNoise3DBlock",function(){return _.WorleyNoise3DBlock}),f.d(y,"SimplexPerlin3DBlock",function(){return _.SimplexPerlin3DBlock}),f.d(y,"NormalBlendBlock",function(){return _.NormalBlendBlock}),f.d(y,"Rotate2dBlock",function(){return _.Rotate2dBlock}),f.d(y,"ReflectBlock",function(){return _.ReflectBlock}),f.d(y,"RefractBlock",function(){return _.RefractBlock}),f.d(y,"DesaturateBlock",function(){return _.DesaturateBlock}),f.d(y,"PBRMetallicRoughnessBlock",function(){return _.PBRMetallicRoughnessBlock}),f.d(y,"SheenBlock",function(){return _.SheenBlock}),f.d(y,"AnisotropyBlock",function(){return _.AnisotropyBlock}),f.d(y,"ReflectionBlock",function(){return _.ReflectionBlock}),f.d(y,"ClearCoatBlock",function(){return _.ClearCoatBlock}),f.d(y,"RefractionBlock",function(){return _.RefractionBlock}),f.d(y,"SubSurfaceBlock",function(){return _.SubSurfaceBlock}),f.d(y,"ParticleTextureBlock",function(){return _.ParticleTextureBlock}),f.d(y,"ParticleRampGradientBlock",function(){return _.ParticleRampGradientBlock}),f.d(y,"ParticleBlendMultiplyBlock",function(){return _.ParticleBlendMultiplyBlock}),f.d(y,"ModBlock",function(){return _.ModBlock}),f.d(y,"NodeMaterialOptimizer",function(){return _.NodeMaterialOptimizer}),f.d(y,"PropertyTypeForEdition",function(){return _.PropertyTypeForEdition}),f.d(y,"editableInPropertyPage",function(){return _.editableInPropertyPage}),f.d(y,"EffectRenderer",function(){return _.EffectRenderer}),f.d(y,"EffectWrapper",function(){return _.EffectWrapper}),f.d(y,"ShadowDepthWrapper",function(){return _.ShadowDepthWrapper}),f.d(y,"Scalar",function(){return _.Scalar}),f.d(y,"extractMinAndMaxIndexed",function(){return _.extractMinAndMaxIndexed}),f.d(y,"extractMinAndMax",function(){return _.extractMinAndMax}),f.d(y,"Space",function(){return _.Space}),f.d(y,"Axis",function(){return _.Axis}),f.d(y,"Coordinate",function(){return _.Coordinate}),f.d(y,"Color3",function(){return _.Color3}),f.d(y,"Color4",function(){return _.Color4}),f.d(y,"TmpColors",function(){return _.TmpColors}),f.d(y,"ToGammaSpace",function(){return _.ToGammaSpace}),f.d(y,"ToLinearSpace",function(){return _.ToLinearSpace}),f.d(y,"Epsilon",function(){return _.Epsilon}),f.d(y,"Frustum",function(){return _.Frustum}),f.d(y,"Orientation",function(){return _.Orientation}),f.d(y,"BezierCurve",function(){return _.BezierCurve}),f.d(y,"Angle",function(){return _.Angle}),f.d(y,"Arc2",function(){return _.Arc2}),f.d(y,"Path2",function(){return _.Path2}),f.d(y,"Path3D",function(){return _.Path3D}),f.d(y,"Curve3",function(){return _.Curve3}),f.d(y,"Plane",function(){return _.Plane}),f.d(y,"Size",function(){return _.Size}),f.d(y,"Vector2",function(){return _.Vector2}),f.d(y,"Vector3",function(){return _.Vector3}),f.d(y,"Vector4",function(){return _.Vector4}),f.d(y,"Quaternion",function(){return _.Quaternion}),f.d(y,"Matrix",function(){return _.Matrix}),f.d(y,"TmpVectors",function(){return _.TmpVectors}),f.d(y,"PositionNormalVertex",function(){return _.PositionNormalVertex}),f.d(y,"PositionNormalTextureVertex",function(){return _.PositionNormalTextureVertex}),f.d(y,"Viewport",function(){return _.Viewport}),f.d(y,"SphericalHarmonics",function(){return _.SphericalHarmonics}),f.d(y,"SphericalPolynomial",function(){return _.SphericalPolynomial}),f.d(y,"AbstractMesh",function(){return _.AbstractMesh}),f.d(y,"Buffer",function(){return _.Buffer}),f.d(y,"VertexBuffer",function(){return _.VertexBuffer}),f.d(y,"DracoCompression",function(){return _.DracoCompression}),f.d(y,"CSG",function(){return _.CSG}),f.d(y,"Geometry",function(){return _.Geometry}),f.d(y,"GroundMesh",function(){return _.GroundMesh}),f.d(y,"TrailMesh",function(){return _.TrailMesh}),f.d(y,"InstancedMesh",function(){return _.InstancedMesh}),f.d(y,"LinesMesh",function(){return _.LinesMesh}),f.d(y,"InstancedLinesMesh",function(){return _.InstancedLinesMesh}),f.d(y,"_CreationDataStorage",function(){return _._CreationDataStorage}),f.d(y,"_InstancesBatch",function(){return _._InstancesBatch}),f.d(y,"Mesh",function(){return _.Mesh}),f.d(y,"VertexData",function(){return _.VertexData}),f.d(y,"MeshBuilder",function(){return _.MeshBuilder}),f.d(y,"SimplificationSettings",function(){return _.SimplificationSettings}),f.d(y,"SimplificationQueue",function(){return _.SimplificationQueue}),f.d(y,"SimplificationType",function(){return _.SimplificationType}),f.d(y,"QuadraticErrorSimplification",function(){return _.QuadraticErrorSimplification}),f.d(y,"SimplicationQueueSceneComponent",function(){return _.SimplicationQueueSceneComponent}),f.d(y,"Polygon",function(){return _.Polygon}),f.d(y,"PolygonMeshBuilder",function(){return _.PolygonMeshBuilder}),f.d(y,"SubMesh",function(){return _.SubMesh}),f.d(y,"MeshLODLevel",function(){return _.MeshLODLevel}),f.d(y,"TransformNode",function(){return _.TransformNode}),f.d(y,"BoxBuilder",function(){return _.BoxBuilder}),f.d(y,"TiledBoxBuilder",function(){return _.TiledBoxBuilder}),f.d(y,"DiscBuilder",function(){return _.DiscBuilder}),f.d(y,"RibbonBuilder",function(){return _.RibbonBuilder}),f.d(y,"SphereBuilder",function(){return _.SphereBuilder}),f.d(y,"HemisphereBuilder",function(){return _.HemisphereBuilder}),f.d(y,"CylinderBuilder",function(){return _.CylinderBuilder}),f.d(y,"TorusBuilder",function(){return _.TorusBuilder}),f.d(y,"TorusKnotBuilder",function(){return _.TorusKnotBuilder}),f.d(y,"LinesBuilder",function(){return _.LinesBuilder}),f.d(y,"PolygonBuilder",function(){return _.PolygonBuilder}),f.d(y,"ShapeBuilder",function(){return _.ShapeBuilder}),f.d(y,"LatheBuilder",function(){return _.LatheBuilder}),f.d(y,"PlaneBuilder",function(){return _.PlaneBuilder}),f.d(y,"TiledPlaneBuilder",function(){return _.TiledPlaneBuilder}),f.d(y,"GroundBuilder",function(){return _.GroundBuilder}),f.d(y,"TubeBuilder",function(){return _.TubeBuilder}),f.d(y,"PolyhedronBuilder",function(){return _.PolyhedronBuilder}),f.d(y,"IcoSphereBuilder",function(){return _.IcoSphereBuilder}),f.d(y,"DecalBuilder",function(){return _.DecalBuilder}),f.d(y,"CapsuleBuilder",function(){return _.CapsuleBuilder}),f.d(y,"DataBuffer",function(){return _.DataBuffer}),f.d(y,"WebGLDataBuffer",function(){return _.WebGLDataBuffer}),f.d(y,"MorphTarget",function(){return _.MorphTarget}),f.d(y,"MorphTargetManager",function(){return _.MorphTargetManager}),f.d(y,"RecastJSPlugin",function(){return _.RecastJSPlugin}),f.d(y,"RecastJSCrowd",function(){return _.RecastJSCrowd}),f.d(y,"Node",function(){return _.Node}),f.d(y,"Database",function(){return _.Database}),f.d(y,"BaseParticleSystem",function(){return _.BaseParticleSystem}),f.d(y,"BoxParticleEmitter",function(){return _.BoxParticleEmitter}),f.d(y,"ConeParticleEmitter",function(){return _.ConeParticleEmitter}),f.d(y,"CylinderParticleEmitter",function(){return _.CylinderParticleEmitter}),f.d(y,"CylinderDirectedParticleEmitter",function(){return _.CylinderDirectedParticleEmitter}),f.d(y,"HemisphericParticleEmitter",function(){return _.HemisphericParticleEmitter}),f.d(y,"PointParticleEmitter",function(){return _.PointParticleEmitter}),f.d(y,"SphereParticleEmitter",function(){return _.SphereParticleEmitter}),f.d(y,"SphereDirectedParticleEmitter",function(){return _.SphereDirectedParticleEmitter}),f.d(y,"CustomParticleEmitter",function(){return _.CustomParticleEmitter}),f.d(y,"MeshParticleEmitter",function(){return _.MeshParticleEmitter}),f.d(y,"GPUParticleSystem",function(){return _.GPUParticleSystem}),f.d(y,"Particle",function(){return _.Particle}),f.d(y,"ParticleHelper",function(){return _.ParticleHelper}),f.d(y,"ParticleSystem",function(){return _.ParticleSystem}),f.d(y,"ParticleSystemSet",function(){return _.ParticleSystemSet}),f.d(y,"SolidParticle",function(){return _.SolidParticle}),f.d(y,"ModelShape",function(){return _.ModelShape}),f.d(y,"DepthSortedParticle",function(){return _.DepthSortedParticle}),f.d(y,"SolidParticleVertex",function(){return _.SolidParticleVertex}),f.d(y,"SolidParticleSystem",function(){return _.SolidParticleSystem}),f.d(y,"CloudPoint",function(){return _.CloudPoint}),f.d(y,"PointsGroup",function(){return _.PointsGroup}),f.d(y,"PointColor",function(){return _.PointColor}),f.d(y,"PointsCloudSystem",function(){return _.PointsCloudSystem}),f.d(y,"SubEmitterType",function(){return _.SubEmitterType}),f.d(y,"SubEmitter",function(){return _.SubEmitter}),f.d(y,"PhysicsEngine",function(){return _.PhysicsEngine}),f.d(y,"PhysicsEngineSceneComponent",function(){return _.PhysicsEngineSceneComponent}),f.d(y,"PhysicsHelper",function(){return _.PhysicsHelper}),f.d(y,"PhysicsRadialExplosionEventOptions",function(){return _.PhysicsRadialExplosionEventOptions}),f.d(y,"PhysicsUpdraftEventOptions",function(){return _.PhysicsUpdraftEventOptions}),f.d(y,"PhysicsVortexEventOptions",function(){return _.PhysicsVortexEventOptions}),f.d(y,"PhysicsRadialImpulseFalloff",function(){return _.PhysicsRadialImpulseFalloff}),f.d(y,"PhysicsUpdraftMode",function(){return _.PhysicsUpdraftMode}),f.d(y,"PhysicsImpostor",function(){return _.PhysicsImpostor}),f.d(y,"PhysicsJoint",function(){return _.PhysicsJoint}),f.d(y,"DistanceJoint",function(){return _.DistanceJoint}),f.d(y,"MotorEnabledJoint",function(){return _.MotorEnabledJoint}),f.d(y,"HingeJoint",function(){return _.HingeJoint}),f.d(y,"Hinge2Joint",function(){return _.Hinge2Joint}),f.d(y,"CannonJSPlugin",function(){return _.CannonJSPlugin}),f.d(y,"AmmoJSPlugin",function(){return _.AmmoJSPlugin}),f.d(y,"OimoJSPlugin",function(){return _.OimoJSPlugin}),f.d(y,"AnaglyphPostProcess",function(){return _.AnaglyphPostProcess}),f.d(y,"BlackAndWhitePostProcess",function(){return _.BlackAndWhitePostProcess}),f.d(y,"BloomEffect",function(){return _.BloomEffect}),f.d(y,"BloomMergePostProcess",function(){return _.BloomMergePostProcess}),f.d(y,"BlurPostProcess",function(){return _.BlurPostProcess}),f.d(y,"ChromaticAberrationPostProcess",function(){return _.ChromaticAberrationPostProcess}),f.d(y,"CircleOfConfusionPostProcess",function(){return _.CircleOfConfusionPostProcess}),f.d(y,"ColorCorrectionPostProcess",function(){return _.ColorCorrectionPostProcess}),f.d(y,"ConvolutionPostProcess",function(){return _.ConvolutionPostProcess}),f.d(y,"DepthOfFieldBlurPostProcess",function(){return _.DepthOfFieldBlurPostProcess}),f.d(y,"DepthOfFieldEffectBlurLevel",function(){return _.DepthOfFieldEffectBlurLevel}),f.d(y,"DepthOfFieldEffect",function(){return _.DepthOfFieldEffect}),f.d(y,"DepthOfFieldMergePostProcessOptions",function(){return _.DepthOfFieldMergePostProcessOptions}),f.d(y,"DepthOfFieldMergePostProcess",function(){return _.DepthOfFieldMergePostProcess}),f.d(y,"DisplayPassPostProcess",function(){return _.DisplayPassPostProcess}),f.d(y,"ExtractHighlightsPostProcess",function(){return _.ExtractHighlightsPostProcess}),f.d(y,"FilterPostProcess",function(){return _.FilterPostProcess}),f.d(y,"FxaaPostProcess",function(){return _.FxaaPostProcess}),f.d(y,"GrainPostProcess",function(){return _.GrainPostProcess}),f.d(y,"HighlightsPostProcess",function(){return _.HighlightsPostProcess}),f.d(y,"ImageProcessingPostProcess",function(){return _.ImageProcessingPostProcess}),f.d(y,"MotionBlurPostProcess",function(){return _.MotionBlurPostProcess}),f.d(y,"PassPostProcess",function(){return _.PassPostProcess}),f.d(y,"PassCubePostProcess",function(){return _.PassCubePostProcess}),f.d(y,"PostProcess",function(){return _.PostProcess}),f.d(y,"PostProcessManager",function(){return _.PostProcessManager}),f.d(y,"RefractionPostProcess",function(){return _.RefractionPostProcess}),f.d(y,"DefaultRenderingPipeline",function(){return _.DefaultRenderingPipeline}),f.d(y,"LensRenderingPipeline",function(){return _.LensRenderingPipeline}),f.d(y,"SSAO2RenderingPipeline",function(){return _.SSAO2RenderingPipeline}),f.d(y,"SSAORenderingPipeline",function(){return _.SSAORenderingPipeline}),f.d(y,"StandardRenderingPipeline",function(){return _.StandardRenderingPipeline}),f.d(y,"PostProcessRenderEffect",function(){return _.PostProcessRenderEffect}),f.d(y,"PostProcessRenderPipeline",function(){return _.PostProcessRenderPipeline}),f.d(y,"PostProcessRenderPipelineManager",function(){return _.PostProcessRenderPipelineManager}),f.d(y,"PostProcessRenderPipelineManagerSceneComponent",function(){return _.PostProcessRenderPipelineManagerSceneComponent}),f.d(y,"SharpenPostProcess",function(){return _.SharpenPostProcess}),f.d(y,"StereoscopicInterlacePostProcessI",function(){return _.StereoscopicInterlacePostProcessI}),f.d(y,"StereoscopicInterlacePostProcess",function(){return _.StereoscopicInterlacePostProcess}),f.d(y,"TonemappingOperator",function(){return _.TonemappingOperator}),f.d(y,"TonemapPostProcess",function(){return _.TonemapPostProcess}),f.d(y,"VolumetricLightScatteringPostProcess",function(){return _.VolumetricLightScatteringPostProcess}),f.d(y,"VRDistortionCorrectionPostProcess",function(){return _.VRDistortionCorrectionPostProcess}),f.d(y,"VRMultiviewToSingleviewPostProcess",function(){return _.VRMultiviewToSingleviewPostProcess}),f.d(y,"ScreenSpaceReflectionPostProcess",function(){return _.ScreenSpaceReflectionPostProcess}),f.d(y,"ScreenSpaceCurvaturePostProcess",function(){return _.ScreenSpaceCurvaturePostProcess}),f.d(y,"ReflectionProbe",function(){return _.ReflectionProbe}),f.d(y,"BoundingBoxRenderer",function(){return _.BoundingBoxRenderer}),f.d(y,"DepthRenderer",function(){return _.DepthRenderer}),f.d(y,"DepthRendererSceneComponent",function(){return _.DepthRendererSceneComponent}),f.d(y,"EdgesRenderer",function(){return _.EdgesRenderer}),f.d(y,"LineEdgesRenderer",function(){return _.LineEdgesRenderer}),f.d(y,"GeometryBufferRenderer",function(){return _.GeometryBufferRenderer}),f.d(y,"GeometryBufferRendererSceneComponent",function(){return _.GeometryBufferRendererSceneComponent}),f.d(y,"PrePassRenderer",function(){return _.PrePassRenderer}),f.d(y,"PrePassRendererSceneComponent",function(){return _.PrePassRendererSceneComponent}),f.d(y,"SubSurfaceSceneComponent",function(){return _.SubSurfaceSceneComponent}),f.d(y,"OutlineRenderer",function(){return _.OutlineRenderer}),f.d(y,"RenderingGroup",function(){return _.RenderingGroup}),f.d(y,"RenderingGroupInfo",function(){return _.RenderingGroupInfo}),f.d(y,"RenderingManager",function(){return _.RenderingManager}),f.d(y,"UtilityLayerRenderer",function(){return _.UtilityLayerRenderer}),f.d(y,"Scene",function(){return _.Scene}),f.d(y,"SceneComponentConstants",function(){return _.SceneComponentConstants}),f.d(y,"Stage",function(){return _.Stage}),f.d(y,"Sprite",function(){return _.Sprite}),f.d(y,"SpriteManager",function(){return _.SpriteManager}),f.d(y,"SpriteMap",function(){return _.SpriteMap}),f.d(y,"SpritePackedManager",function(){return _.SpritePackedManager}),f.d(y,"SpriteSceneComponent",function(){return _.SpriteSceneComponent}),f.d(y,"AlphaState",function(){return _.AlphaState}),f.d(y,"DepthCullingState",function(){return _.DepthCullingState}),f.d(y,"StencilState",function(){return _.StencilState}),f.d(y,"AndOrNotEvaluator",function(){return _.AndOrNotEvaluator}),f.d(y,"AssetTaskState",function(){return _.AssetTaskState}),f.d(y,"AbstractAssetTask",function(){return _.AbstractAssetTask}),f.d(y,"AssetsProgressEvent",function(){return _.AssetsProgressEvent}),f.d(y,"ContainerAssetTask",function(){return _.ContainerAssetTask}),f.d(y,"MeshAssetTask",function(){return _.MeshAssetTask}),f.d(y,"TextFileAssetTask",function(){return _.TextFileAssetTask}),f.d(y,"BinaryFileAssetTask",function(){return _.BinaryFileAssetTask}),f.d(y,"ImageAssetTask",function(){return _.ImageAssetTask}),f.d(y,"TextureAssetTask",function(){return _.TextureAssetTask}),f.d(y,"CubeTextureAssetTask",function(){return _.CubeTextureAssetTask}),f.d(y,"HDRCubeTextureAssetTask",function(){return _.HDRCubeTextureAssetTask}),f.d(y,"EquiRectangularCubeTextureAssetTask",function(){return _.EquiRectangularCubeTextureAssetTask}),f.d(y,"AssetsManager",function(){return _.AssetsManager}),f.d(y,"BasisTranscodeConfiguration",function(){return _.BasisTranscodeConfiguration}),f.d(y,"BasisTools",function(){return _.BasisTools}),f.d(y,"DDSTools",function(){return _.DDSTools}),f.d(y,"expandToProperty",function(){return _.expandToProperty}),f.d(y,"serialize",function(){return _.serialize}),f.d(y,"serializeAsTexture",function(){return _.serializeAsTexture}),f.d(y,"serializeAsColor3",function(){return _.serializeAsColor3}),f.d(y,"serializeAsFresnelParameters",function(){return _.serializeAsFresnelParameters}),f.d(y,"serializeAsVector2",function(){return _.serializeAsVector2}),f.d(y,"serializeAsVector3",function(){return _.serializeAsVector3}),f.d(y,"serializeAsMeshReference",function(){return _.serializeAsMeshReference}),f.d(y,"serializeAsColorCurves",function(){return _.serializeAsColorCurves}),f.d(y,"serializeAsColor4",function(){return _.serializeAsColor4}),f.d(y,"serializeAsImageProcessingConfiguration",function(){return _.serializeAsImageProcessingConfiguration}),f.d(y,"serializeAsQuaternion",function(){return _.serializeAsQuaternion}),f.d(y,"serializeAsMatrix",function(){return _.serializeAsMatrix}),f.d(y,"serializeAsCameraReference",function(){return _.serializeAsCameraReference}),f.d(y,"SerializationHelper",function(){return _.SerializationHelper}),f.d(y,"Deferred",function(){return _.Deferred}),f.d(y,"EnvironmentTextureTools",function(){return _.EnvironmentTextureTools}),f.d(y,"MeshExploder",function(){return _.MeshExploder}),f.d(y,"FilesInput",function(){return _.FilesInput}),f.d(y,"CubeMapToSphericalPolynomialTools",function(){return _.CubeMapToSphericalPolynomialTools}),f.d(y,"HDRTools",function(){return _.HDRTools}),f.d(y,"PanoramaToCubeMapTools",function(){return _.PanoramaToCubeMapTools}),f.d(y,"KhronosTextureContainer",function(){return _.KhronosTextureContainer}),f.d(y,"EventState",function(){return _.EventState}),f.d(y,"Observer",function(){return _.Observer}),f.d(y,"MultiObserver",function(){return _.MultiObserver}),f.d(y,"Observable",function(){return _.Observable}),f.d(y,"PerformanceMonitor",function(){return _.PerformanceMonitor}),f.d(y,"RollingAverage",function(){return _.RollingAverage}),f.d(y,"PromisePolyfill",function(){return _.PromisePolyfill}),f.d(y,"SceneOptimization",function(){return _.SceneOptimization}),f.d(y,"TextureOptimization",function(){return _.TextureOptimization}),f.d(y,"HardwareScalingOptimization",function(){return _.HardwareScalingOptimization}),f.d(y,"ShadowsOptimization",function(){return _.ShadowsOptimization}),f.d(y,"PostProcessesOptimization",function(){return _.PostProcessesOptimization}),f.d(y,"LensFlaresOptimization",function(){return _.LensFlaresOptimization}),f.d(y,"CustomOptimization",function(){return _.CustomOptimization}),f.d(y,"ParticlesOptimization",function(){return _.ParticlesOptimization}),f.d(y,"RenderTargetsOptimization",function(){return _.RenderTargetsOptimization}),f.d(y,"MergeMeshesOptimization",function(){return _.MergeMeshesOptimization}),f.d(y,"SceneOptimizerOptions",function(){return _.SceneOptimizerOptions}),f.d(y,"SceneOptimizer",function(){return _.SceneOptimizer}),f.d(y,"SceneSerializer",function(){return _.SceneSerializer}),f.d(y,"SmartArray",function(){return _.SmartArray}),f.d(y,"SmartArrayNoDuplicate",function(){return _.SmartArrayNoDuplicate}),f.d(y,"StringDictionary",function(){return _.StringDictionary}),f.d(y,"Tags",function(){return _.Tags}),f.d(y,"TextureTools",function(){return _.TextureTools}),f.d(y,"TGATools",function(){return _.TGATools}),f.d(y,"Tools",function(){return _.Tools}),f.d(y,"className",function(){return _.className}),f.d(y,"AsyncLoop",function(){return _.AsyncLoop}),f.d(y,"VideoRecorder",function(){return _.VideoRecorder}),f.d(y,"JoystickAxis",function(){return _.JoystickAxis}),f.d(y,"VirtualJoystick",function(){return _.VirtualJoystick}),f.d(y,"WorkerPool",function(){return _.WorkerPool}),f.d(y,"Logger",function(){return _.Logger}),f.d(y,"_TypeStore",function(){return _._TypeStore}),f.d(y,"FilesInputStore",function(){return _.FilesInputStore}),f.d(y,"DeepCopier",function(){return _.DeepCopier}),f.d(y,"PivotTools",function(){return _.PivotTools}),f.d(y,"PrecisionDate",function(){return _.PrecisionDate}),f.d(y,"ScreenshotTools",function(){return _.ScreenshotTools}),f.d(y,"WebRequest",function(){return _.WebRequest}),f.d(y,"InspectableType",function(){return _.InspectableType}),f.d(y,"BRDFTextureTools",function(){return _.BRDFTextureTools}),f.d(y,"RGBDTextureTools",function(){return _.RGBDTextureTools}),f.d(y,"ColorGradient",function(){return _.ColorGradient}),f.d(y,"Color3Gradient",function(){return _.Color3Gradient}),f.d(y,"FactorGradient",function(){return _.FactorGradient}),f.d(y,"GradientHelper",function(){return _.GradientHelper}),f.d(y,"PerfCounter",function(){return _.PerfCounter}),f.d(y,"RetryStrategy",function(){return _.RetryStrategy}),f.d(y,"CanvasGenerator",function(){return _.CanvasGenerator}),f.d(y,"LoadFileError",function(){return _.LoadFileError}),f.d(y,"RequestFileError",function(){return _.RequestFileError}),f.d(y,"ReadFileError",function(){return _.ReadFileError}),f.d(y,"FileTools",function(){return _.FileTools}),f.d(y,"StringTools",function(){return _.StringTools}),f.d(y,"DataReader",function(){return _.DataReader}),f.d(y,"MinMaxReducer",function(){return _.MinMaxReducer}),f.d(y,"DepthReducer",function(){return _.DepthReducer}),f.d(y,"DataStorage",function(){return _.DataStorage}),f.d(y,"SceneRecorder",function(){return _.SceneRecorder}),f.d(y,"KhronosTextureContainer2",function(){return _.KhronosTextureContainer2}),f.d(y,"Trajectory",function(){return _.Trajectory}),f.d(y,"TrajectoryClassifier",function(){return _.TrajectoryClassifier}),f.d(y,"TimerState",function(){return _.TimerState}),f.d(y,"setAndStartTimer",function(){return _.setAndStartTimer}),f.d(y,"AdvancedTimer",function(){return _.AdvancedTimer}),f.d(y,"CopyTools",function(){return _.CopyTools}),f.d(y,"WebXRCamera",function(){return _.WebXRCamera}),f.d(y,"WebXREnterExitUIButton",function(){return _.WebXREnterExitUIButton}),f.d(y,"WebXREnterExitUIOptions",function(){return _.WebXREnterExitUIOptions}),f.d(y,"WebXREnterExitUI",function(){return _.WebXREnterExitUI}),f.d(y,"WebXRExperienceHelper",function(){return _.WebXRExperienceHelper}),f.d(y,"WebXRInput",function(){return _.WebXRInput}),f.d(y,"WebXRInputSource",function(){return _.WebXRInputSource}),f.d(y,"WebXRManagedOutputCanvasOptions",function(){return _.WebXRManagedOutputCanvasOptions}),f.d(y,"WebXRManagedOutputCanvas",function(){return _.WebXRManagedOutputCanvas}),f.d(y,"WebXRState",function(){return _.WebXRState}),f.d(y,"WebXRTrackingState",function(){return _.WebXRTrackingState}),f.d(y,"WebXRSessionManager",function(){return _.WebXRSessionManager}),f.d(y,"WebXRDefaultExperienceOptions",function(){return _.WebXRDefaultExperienceOptions}),f.d(y,"WebXRDefaultExperience",function(){return _.WebXRDefaultExperience}),f.d(y,"WebXRFeatureName",function(){return _.WebXRFeatureName}),f.d(y,"WebXRFeaturesManager",function(){return _.WebXRFeaturesManager}),f.d(y,"WebXRAbstractFeature",function(){return _.WebXRAbstractFeature}),f.d(y,"WebXRHitTestLegacy",function(){return _.WebXRHitTestLegacy}),f.d(y,"WebXRAnchorSystem",function(){return _.WebXRAnchorSystem}),f.d(y,"WebXRPlaneDetector",function(){return _.WebXRPlaneDetector}),f.d(y,"WebXRBackgroundRemover",function(){return _.WebXRBackgroundRemover}),f.d(y,"WebXRMotionControllerTeleportation",function(){return _.WebXRMotionControllerTeleportation}),f.d(y,"WebXRControllerPointerSelection",function(){return _.WebXRControllerPointerSelection}),f.d(y,"IWebXRControllerPhysicsOptions",function(){return _.IWebXRControllerPhysicsOptions}),f.d(y,"WebXRControllerPhysics",function(){return _.WebXRControllerPhysics}),f.d(y,"WebXRHitTest",function(){return _.WebXRHitTest}),f.d(y,"WebXRFeaturePointSystem",function(){return _.WebXRFeaturePointSystem}),f.d(y,"WebXRHand",function(){return _.WebXRHand}),f.d(y,"WebXRHandTracking",function(){return _.WebXRHandTracking}),f.d(y,"WebXRAbstractMotionController",function(){return _.WebXRAbstractMotionController}),f.d(y,"WebXRControllerComponent",function(){return _.WebXRControllerComponent}),f.d(y,"WebXRGenericTriggerMotionController",function(){return _.WebXRGenericTriggerMotionController}),f.d(y,"WebXRMicrosoftMixedRealityController",function(){return _.WebXRMicrosoftMixedRealityController}),f.d(y,"WebXRMotionControllerManager",function(){return _.WebXRMotionControllerManager}),f.d(y,"WebXROculusTouchMotionController",function(){return _.WebXROculusTouchMotionController}),f.d(y,"WebXRHTCViveMotionController",function(){return _.WebXRHTCViveMotionController}),f.d(y,"WebXRProfiledMotionController",function(){return _.WebXRProfiledMotionController});var u=U!==void 0?U: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 C=[];for(var P in R)M.Debug[P]=R[P],C.push(P);for(var P in _)M[P]=_[P]}var m={AxesViewer:R.AxesViewer,BoneAxesViewer:R.BoneAxesViewer,PhysicsViewer:R.PhysicsViewer,SkeletonViewer:R.SkeletonViewer}}.call(this,f(159))}])})})(zn);var pl={exports:{}};(function(ft,Ze){(function(Ie,y){ft.exports=y(zn.exports)})(typeof self<"u"?self:typeof Qr<"u"?Qr:Qr,function(Ie){return function(y){var f={};function U(_){if(f[_])return f[_].exports;var R=f[_]={i:_,l:!1,exports:{}};return y[_].call(R.exports,R,R.exports,U),R.l=!0,R.exports}return U.m=y,U.c=f,U.d=function(_,R,u){U.o(_,R)||Object.defineProperty(_,R,{enumerable:!0,get:u})},U.r=function(_){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(_,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(_,"__esModule",{value:!0})},U.t=function(_,R){if(1&R&&(_=U(_)),8&R||4&R&&typeof _=="object"&&_&&_.__esModule)return _;var u=Object.create(null);if(U.r(u),Object.defineProperty(u,"default",{enumerable:!0,value:_}),2&R&&typeof _!="string")for(var M in _)U.d(u,M,function(C){return _[C]}.bind(null,M));return u},U.n=function(_){var R=_&&_.__esModule?function(){return _.default}:function(){return _};return U.d(R,"a",R),R},U.o=function(_,R){return Object.prototype.hasOwnProperty.call(_,R)},U.p="",U(U.s=20)}([function(y,f){y.exports=Ie},function(y,f,U){U.d(f,"a",function(){return u}),U.d(f,"b",function(){return M});var _=U(0),R=U(2),u=function(){function C(){}return C.Get=function(P,m,c){if(!m||c==null||!m[c])throw new Error(P+": Failed to find index ("+c+")");return m[c]},C.Assign=function(P){if(P)for(var m=0;m "+R.GLTFLoaderState[R.GLTFLoaderState.READY],A=R.GLTFLoaderState[R.GLTFLoaderState.LOADING]+" => "+R.GLTFLoaderState[R.GLTFLoaderState.COMPLETE];c._parent._startPerformanceCounter(T),c._parent._startPerformanceCounter(A),c._setState(R.GLTFLoaderState.LOADING),c._extensionsOnLoading();var S=new Array,g=c._babylonScene.blockMaterialDirtyMechanism;if(c._babylonScene.blockMaterialDirtyMechanism=!0,P)S.push(c.loadSceneAsync("/nodes",{nodes:P,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;hP.bin.byteLength)&&_.Logger.Warn("Binary buffer length ("+c.byteLength+") from JSON does not match chunk length ("+P.bin.byteLength+")"),this._bin=P.bin}else _.Logger.Warn("Unexpected BIN chunk")}},C.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 P={},m=0,c=this._gltf.nodes;m=2)throw new Error(P+"/texCoord: Invalid value ("+m.texCoord+")");var S=u.Get(P+"/index",this._gltf.textures,m.index);S._textureInfo=m;var g=this._loadTextureAsync("/textures/"+m.index,S,function(l){l.coordinatesIndex=m.texCoord||0,C.AddPointerMetadata(l,P),T._parent.onTextureLoadedObservable.notifyObservers(l),c(l)});return this.logClose(),g},C.prototype._loadTextureAsync=function(P,m,c){c===void 0&&(c=function(){});var T=this._extensionsLoadTextureAsync(P,m,c);if(T)return T;this.logOpen(P+" "+(m.name||""));var A=m.sampler==null?C.DefaultSampler:u.Get(P+"/sampler",this._gltf.samplers,m.sampler),S=u.Get(P+"/source",this._gltf.images,m.source),g=this._createTextureAsync(P,A,S,c);return this.logClose(),g},C.prototype._createTextureAsync=function(P,m,c,T,A){var S=this;T===void 0&&(T=function(){});var g=this._loadSampler("/samplers/"+m.index,m),l=new Array,h=new _.Deferred;this._babylonScene._blockEntityCollection=this._forAssetContainer;var v=new _.Texture(null,this._babylonScene,g.noMipMaps,!1,g.samplingMode,function(){S._disposed||h.resolve()},function(E,D){S._disposed||h.reject(new Error(P+": "+(D&&D.message?D.message:E||"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(E){var D=c.uri||S._fileName+"#image"+c.index,w="data:"+S._uniqueRootUrl+D;v.updateURL(w,E)})),v.wrapU=g.wrapU,v.wrapV=g.wrapV,T(v),Promise.all(l).then(function(){return v})},C.prototype._loadSampler=function(P,m){return m._data||(m._data={noMipMaps:m.minFilter===9728||m.minFilter===9729,samplingMode:C._GetTextureSamplingMode(P,m),wrapU:C._GetTextureWrapMode(P+"/wrapS",m.wrapS),wrapV:C._GetTextureWrapMode(P+"/wrapT",m.wrapT)}),m._data},C.prototype.loadImageAsync=function(P,m){if(!m._data){if(this.logOpen(P+" "+(m.name||"")),m.uri)m._data=this.loadUriAsync(P+"/uri",m,m.uri);else{var c=u.Get(P+"/bufferView",this._gltf.bufferViews,m.bufferView);m._data=this.loadBufferViewAsync("/bufferViews/"+c.index,c)}this.logClose()}return m._data},C.prototype.loadUriAsync=function(P,m,c){var T=this,A=this._extensionsLoadUriAsync(P,m,c);if(A)return A;if(!C._ValidateUri(c))throw new Error(P+": '"+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){T._parent._loadFile(g,T._babylonScene,function(v){T._disposed||(T.log("Loaded "+c+" ("+v.byteLength+" bytes)"),l(new Uint8Array(v)))},!0,function(v){h(new _.LoadFileError(P+": Failed to load '"+c+"'"+(v?": "+v.status+" "+v.statusText:""),v))})})})},C.AddPointerMetadata=function(P,m){var c=P.metadata=P.metadata||{},T=c.gltf=c.gltf||{};(T.pointers=T.pointers||[]).push(m)},C._GetTextureWrapMode=function(P,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(P+": Invalid value ("+m+")"),_.Texture.WRAP_ADDRESSMODE}},C._GetTextureSamplingMode=function(P,m){var c=m.magFilter==null?9729:m.magFilter,T=m.minFilter==null?9987:m.minFilter;if(c===9729)switch(T){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(P+"/minFilter: Invalid value ("+T+")"),_.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(c!==9728&&_.Logger.Warn(P+"/magFilter: Invalid value ("+c+")"),T){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(P+"/minFilter: Invalid value ("+T+")"),_.Texture.NEAREST_NEAREST_MIPNEAREST}},C._GetTypedArrayConstructor=function(P,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(P+": Invalid component type "+m)}},C._GetTypedArray=function(P,m,c,T,A){var S=c.buffer;T=c.byteOffset+(T||0);var g=C._GetTypedArrayConstructor(P+"/componentType",m);try{return new g(S,T,A)}catch(l){throw new Error(P+": "+l)}},C._GetNumComponents=function(P,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(P+": Invalid type ("+m+")")},C._ValidateUri=function(P){return _.Tools.IsBase64(P)||P.indexOf("..")===-1},C._GetDrawMode=function(P,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(P+": Invalid mesh primitive mode ("+m+")")},C.prototype._compileMaterialsAsync=function(){var P=this;this._parent._startPerformanceCounter("Compile materials");var m=new Array;if(this._gltf.materials)for(var c=0,T=this._gltf.materials;c-1&&h.materials.splice(N,1),(N=v.indexOf(w))>-1&&v.splice(N,1)})});var E=[];l.onTextureLoadedObservable.add(function(w){E.push(w),w.onDisposeObservable.addOnce(function(){var N=h.textures.indexOf(w);N>-1&&h.textures.splice(N,1),(N=E.indexOf(w))>-1&&E.splice(N,1)})});var D=[];return l.onCameraLoadedObservable.add(function(w){D.push(w)}),l._loader.importMeshAsync(null,c,!0,T,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,v),Array.prototype.push.apply(h.textures,E),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,T){if(M.StringTools.StartsWith(T,"base64,"+m.magicBase64Encoded)||M.StringTools.StartsWith(T,"application/octet-stream;base64,"+m.magicBase64Encoded)||M.StringTools.StartsWith(T,"model/gltf-binary;base64,"+m.magicBase64Encoded)){var A=M.Tools.DecodeBase64(T);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,T),Promise.resolve({json:this._parseJson(T)})},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(T,A){c.onCompleteObservable.addOnce(function(){T()}),c.onErrorObservable.addOnce(function(S){A(S)})})},m.prototype._loadFile=function(c,T,A,S,g){var l=this,h=T._loadFile(c,A,function(v){l._onProgress(v,h)},void 0,S,g);return h.onCompleteObservable.add(function(v){l._requests.splice(l._requests.indexOf(v),1)}),this._requests.push(h),h},m.prototype._requestFile=function(c,T,A,S,g,l){var h=this,v=T._requestFile(c,A,function(E){h._onProgress(E,v)},void 0,S,g,l);return v.onCompleteObservable.add(function(E){h._requests.splice(h._requests.indexOf(E),1)}),this._requests.push(v),v},m.prototype._onProgress=function(c,T){if(this._progressCallback){T._lengthComputable=c.lengthComputable,T._loaded=c.loaded,T._total=c.total;for(var A=!0,S=0,g=0,l=0,h=this._requests;l0)throw new Error("Incompatible minimum version: "+T.minVersion)}var g={1:m._CreateGLTF1Loader,2:m._CreateGLTF2Loader}[A.major];if(!g)throw new Error("Unsupported version: "+T.version);return g(this)},m.prototype._parseJson=function(c){this._startPerformanceCounter("Parse JSON"),this._log("JSON length: "+c.length);var T=JSON.parse(c);return this._endPerformanceCounter("Parse JSON"),T},m.prototype._unpackBinaryAsync=function(c){var T=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();T.loggingEnabled&&T._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=T._unpackBinaryV1Async(c,l);break;case 2:g=T._unpackBinaryV2Async(c,l);break;default:throw new Error("Unsupported version: "+S)}return T._endPerformanceCounter("Unpack Binary"),g})},m.prototype._unpackBinaryV1Async=function(c,T){var A=c.readUint32(),S=c.readUint32();if(S!==0)throw new Error("Unexpected content format: "+S);var g=T-c.byteOffset,l={json:this._parseJson(c.readString(A)),bin:null};if(g!==0){var h=c.byteOffset;l.bin={readAsync:function(v,E){return c.buffer.readAsync(h+v,E)},byteLength:g}}return Promise.resolve(l)},m.prototype._unpackBinaryV2Async=function(c,T){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===T?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},v=function(){var E=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:E},c.skipBytes(E);break;default:c.skipBytes(E)}return c.byteOffset!==T?c.loadAsync(8).then(v):Promise.resolve(h)};return v()})},m._parseVersion=function(c){if(c==="1.0"||c==="1.0.1")return{major:1,minor:0};var T=(c+"").match(/^(\d+)\.(\d+)/);return T?{major:parseInt(T[1]),minor:parseInt(T[2])}:null},m._compareVersion=function(c,T){return c.major>T.major?1:c.majorT.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(R.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}();R.b.RegisterExtension("ExtrasAsMetadata",function(ae){return new pe(ae)})},function(y,f,U){U.r(f),U.d(f,"GLTFBinaryExtension",function(){return H}),U.d(f,"GLTFLoaderBase",function(){return re}),U.d(f,"GLTFLoader",function(){return Y}),U.d(f,"GLTFLoaderExtension",function(){return k}),U.d(f,"EComponentType",function(){return _}),U.d(f,"EShaderType",function(){return R}),U.d(f,"EParameterType",function(){return u}),U.d(f,"ETextureWrapMode",function(){return M}),U.d(f,"ETextureFilterType",function(){return C}),U.d(f,"ETextureFormat",function(){return P}),U.d(f,"ECullingType",function(){return m}),U.d(f,"EBlendingFunction",function(){return c}),U.d(f,"GLTFUtils",function(){return g}),U.d(f,"GLTFMaterialsCommonExtension",function(){return Z});var _,R,u,M,C,P,m,c,T=U(4);(function(W){W[W.BYTE=5120]="BYTE",W[W.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",W[W.SHORT=5122]="SHORT",W[W.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",W[W.FLOAT=5126]="FLOAT"})(_||(_={})),function(W){W[W.FRAGMENT=35632]="FRAGMENT",W[W.VERTEX=35633]="VERTEX"}(R||(R={})),function(W){W[W.BYTE=5120]="BYTE",W[W.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",W[W.SHORT=5122]="SHORT",W[W.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",W[W.INT=5124]="INT",W[W.UNSIGNED_INT=5125]="UNSIGNED_INT",W[W.FLOAT=5126]="FLOAT",W[W.FLOAT_VEC2=35664]="FLOAT_VEC2",W[W.FLOAT_VEC3=35665]="FLOAT_VEC3",W[W.FLOAT_VEC4=35666]="FLOAT_VEC4",W[W.INT_VEC2=35667]="INT_VEC2",W[W.INT_VEC3=35668]="INT_VEC3",W[W.INT_VEC4=35669]="INT_VEC4",W[W.BOOL=35670]="BOOL",W[W.BOOL_VEC2=35671]="BOOL_VEC2",W[W.BOOL_VEC3=35672]="BOOL_VEC3",W[W.BOOL_VEC4=35673]="BOOL_VEC4",W[W.FLOAT_MAT2=35674]="FLOAT_MAT2",W[W.FLOAT_MAT3=35675]="FLOAT_MAT3",W[W.FLOAT_MAT4=35676]="FLOAT_MAT4",W[W.SAMPLER_2D=35678]="SAMPLER_2D"}(u||(u={})),function(W){W[W.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",W[W.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",W[W.REPEAT=10497]="REPEAT"}(M||(M={})),function(W){W[W.NEAREST=9728]="NEAREST",W[W.LINEAR=9728]="LINEAR",W[W.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",W[W.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",W[W.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",W[W.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"}(C||(C={})),function(W){W[W.ALPHA=6406]="ALPHA",W[W.RGB=6407]="RGB",W[W.RGBA=6408]="RGBA",W[W.LUMINANCE=6409]="LUMINANCE",W[W.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"}(P||(P={})),function(W){W[W.FRONT=1028]="FRONT",W[W.BACK=1029]="BACK",W[W.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(m||(m={})),function(W){W[W.ZERO=0]="ZERO",W[W.ONE=1]="ONE",W[W.SRC_COLOR=768]="SRC_COLOR",W[W.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",W[W.DST_COLOR=774]="DST_COLOR",W[W.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",W[W.SRC_ALPHA=770]="SRC_ALPHA",W[W.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",W[W.DST_ALPHA=772]="DST_ALPHA",W[W.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",W[W.CONSTANT_COLOR=32769]="CONSTANT_COLOR",W[W.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",W[W.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",W[W.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",W[W.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"}(c||(c={}));var A,S=U(0),g=function(){function W(){}return W.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)}},W.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}},W.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}},W.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}},W.GetTextureFilterMode=function(q){switch(q){case C.LINEAR:case C.LINEAR_MIPMAP_NEAREST:case C.LINEAR_MIPMAP_LINEAR:return S.Texture.TRILINEAR_SAMPLINGMODE;case C.NEAREST:case C.NEAREST_MIPMAP_NEAREST:return S.Texture.NEAREST_SAMPLINGMODE;default:return S.Texture.BILINEAR_SAMPLINGMODE}},W.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 Pe=be.buffer;switch(ge+=be.byteOffset,_e){case _.BYTE:return new Int8Array(Pe,ge,me);case _.UNSIGNED_BYTE:return new Uint8Array(Pe,ge,me);case _.SHORT:return new Int16Array(Pe,ge,me);case _.UNSIGNED_SHORT:return new Uint16Array(Pe,ge,me);default:return new Float32Array(Pe,ge,me)}},W.GetBufferFromAccessor=function(q,he){var ge=q.bufferViews[he.bufferView],me=he.count*W.GetByteStrideFromType(he);return W.GetBufferFromBufferView(q,ge,he.byteOffset,me,he.componentType)},W.DecodeBufferToText=function(q){for(var he="",ge=q.byteLength,me=0;me=this._maxPos},W}(),v=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],E=["world","view","projection","worldView","worldViewProjection","mBones"],D=["translation","rotation","scale"],w=["position","rotationQuaternion","scaling"],N=function(W,q,he){for(var ge in W){var me=W[ge];he[q][ge]=me}},I=function(W){if(W)for(var q=0;q0&&(We=ne(_e,me))&&be.indexOf(We)===-1&&be.push(We),new S.Bone(ye.jointName||"",ge,We,$e).id=me}}else S.Tools.Warn("Joint named "+q.jointNames[Pe]+" does not exist")}var ct=ge.bones;for(ge.bones=[],Pe=0;Pe1?(_e=new S.MultiMaterial("multimat"+ge,W.scene)).subMaterials=be:_e=new S.StandardMaterial("multimat"+ge,W.scene),be.length===1&&(_e=be[0]),me.material||(me.material=_e),new S.Geometry(ge,W.scene,Pe,!1,me),me.computeWorldMatrix(!0),W.scene._blockEntityCollection=!1,me.subMeshes=[];var Zt=0;for(je=0;je0&&W.importMeshesNames.indexOf(q.name||"")===-1)return null;if(q.skin){if(q.meshes){var _e=W.skins[q.skin];(be=ae(W,q,q.meshes,he,q.babylonNode)).skeleton=W.scene.getLastSkeletonByID(q.skin),be.skeleton===null&&(be.skeleton=pe(W,_e,0,_e.babylonSkeleton,q.skin),_e.babylonSkeleton||(_e.babylonSkeleton=be.skeleton)),me=be}}else if(q.meshes){var be;me=be=ae(W,q,q.mesh?[q.mesh]:q.meshes,he,q.babylonNode)}else if(!q.light||q.babylonNode||W.importOnlyMeshes){if(q.camera&&!q.babylonNode&&!W.importOnlyMeshes){var Pe=W.cameras[q.camera];if(Pe){if(W.scene._blockEntityCollection=W.forAssetContainer,Pe.type==="orthographic"){var ye=new S.FreeCamera(q.camera,S.Vector3.Zero(),W.scene,!1);ye.name=q.name||"",ye.mode=S.Camera.ORTHOGRAPHIC_CAMERA,ye.attachControl(),me=ye}else if(Pe.type==="perspective"){var Be=Pe[Pe.type],ke=new S.FreeCamera(q.camera,S.Vector3.Zero(),W.scene,!1);ke.name=q.name||"",ke.attachControl(),Be.aspectRatio||(Be.aspectRatio=W.scene.getEngine().getRenderWidth()/W.scene.getEngine().getRenderHeight()),Be.znear&&Be.zfar&&(ke.maxZ=Be.zfar,ke.minZ=Be.znear),me=ke}W.scene._blockEntityCollection=!1}}}else{var We=W.lights[q.light];if(We){if(We.type==="ambient"){var je=We[We.type],He=new S.HemisphericLight(q.light,S.Vector3.Zero(),W.scene);He.name=q.name||"",je.color&&(He.diffuse=S.Color3.FromArray(je.color)),me=He}else if(We.type==="directional"){var Qe=We[We.type],Ge=new S.DirectionalLight(q.light,S.Vector3.Zero(),W.scene);Ge.name=q.name||"",Qe.color&&(Ge.diffuse=S.Color3.FromArray(Qe.color)),me=Ge}else if(We.type==="point"){var nt=We[We.type],$e=new S.PointLight(q.light,S.Vector3.Zero(),W.scene);$e.name=q.name||"",nt.color&&($e.diffuse=S.Color3.FromArray(nt.color)),me=$e}else if(We.type==="spot"){var ct=We[We.type],st=new S.SpotLight(q.light,S.Vector3.Zero(),S.Vector3.Zero(),0,0,W.scene);st.name=q.name||"",ct.color&&(st.diffuse=S.Color3.FromArray(ct.color)),ct.fallOfAngle&&(st.angle=ct.fallOfAngle),ct.fallOffExponent&&(st.exponent=ct.fallOffExponent),me=st}}}if(!q.jointName){if(q.babylonNode)return q.babylonNode;if(me===null){W.scene._blockEntityCollection=W.forAssetContainer;var mt=new S.Mesh(q.name||"",W.scene);W.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(W,q,he,ge){ge===void 0&&(ge=!1);var me=W.nodes[q],_e=null;if(ge=!(W.importOnlyMeshes&&!ge&&W.importMeshesNames)||W.importMeshesNames.indexOf(me.name||"")!==-1||W.importMeshesNames.length===0,!me.jointName&&ge&&(_e=K(W,me,q))!==null&&(_e.id=q,_e.parent=he),me.children)for(var be=0;be=0?h.substring(0,v):h;E=E.toLowerCase();var D=v>=0?h.substring(v+1).trim():"";E==="newmtl"?(g&&this.materials.push(g),C._blockEntityCollection=c,g=new _.StandardMaterial(D,C),C._blockEntityCollection=!1):E==="kd"&&g?(T=D.split(S,3).map(parseFloat),g.diffuseColor=_.Color3.FromArray(T)):E==="ka"&&g?(T=D.split(S,3).map(parseFloat),g.ambientColor=_.Color3.FromArray(T)):E==="ks"&&g?(T=D.split(S,3).map(parseFloat),g.specularColor=_.Color3.FromArray(T)):E==="ke"&&g?(T=D.split(S,3).map(parseFloat),g.emissiveColor=_.Color3.FromArray(T)):E==="ns"&&g?g.specularPower=parseFloat(D):E==="d"&&g?g.alpha=parseFloat(D):E==="map_ka"&&g?g.ambientTexture=M._getTexture(m,D,C):E==="map_kd"&&g?g.diffuseTexture=M._getTexture(m,D,C):E==="map_ks"&&g?g.specularTexture=M._getTexture(m,D,C):E==="map_ns"||(E==="map_bump"&&g?g.bumpTexture=M._getTexture(m,D,C):E==="map_d"&&g&&(g.opacityTexture=M._getTexture(m,D,C)))}}g&&this.materials.push(g)}},M._getTexture=function(C,P,m){if(!P)return null;var c=C;if(C==="file:"){var T=P.lastIndexOf("\\");T===-1&&(T=P.lastIndexOf("/")),c+=T>-1?P.substr(T+1):P}else c+=P;return new _.Texture(c,m,!1,M.INVERT_TEXTURE_Y)},M.INVERT_TEXTURE_Y=!0,M}(),u=function(){function M(C){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=C||M.currentMeshLoadOptions}return Object.defineProperty(M,"INVERT_TEXTURE_Y",{get:function(){return R.INVERT_TEXTURE_Y},set:function(C){R.INVERT_TEXTURE_Y=C},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(C,P,m,c){var T=_.Tools.BaseUrl+P+C;_.Tools.LoadFile(T,m,void 0,void 0,!1,function(A,S){c(T,S)})},M.prototype.createPlugin=function(){return new M(M.currentMeshLoadOptions)},M.prototype.canDirectLoad=function(C){return!1},M.prototype.importMeshAsync=function(C,P,m,c,T,A){return this._parseSolid(C,P,m,c).then(function(S){return{meshes:S,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[]}})},M.prototype.loadAsync=function(C,P,m,c,T){return this.importMeshAsync(null,C,P,m,c).then(function(){})},M.prototype.loadAssetContainerAsync=function(C,P,m,c,T){var A=this;return this._forAssetContainer=!0,this.importMeshAsync(null,C,P,m).then(function(S){var g=new _.AssetContainer(C);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(v){g.textures.indexOf(v)==-1&&g.textures.push(v)}))}),A._forAssetContainer=!1,g}).catch(function(S){throw A._forAssetContainer=!1,S})},M.prototype._parseSolid=function(C,P,m,c){for(var T,A=this,S=[],g=[],l=[],h=[],v=[],E=[],D=[],w=[],N=[],I=[],V=[],X=0,j=!1,ne=[],te=[],de=[],pe=[],ae=[],ee="",K="",$=new R,L=1,G=!0,Q=new _.Color4(.5,.5,.5,1),oe=function(Ge,nt,$e,ct,st,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,[Ge,$e,nt]):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,[Ge,$e]))===-1?(E.push(D.length),D.push(ct),w.push(st),I.push(mt),St!==void 0&&N.push(St),V[Ge].normals.push($e),V[Ge].idx.push(X++),A._meshLoadOptions.OptimizeWithUV&&V[Ge].uv.push(nt)):E.push(wt)},re=function(){for(var Ge=0;Ge0&&(T=v[v.length-1],re(),E.reverse(),T.indices=E.slice(),T.positions=ne.slice(),T.normals=de.slice(),T.uvs=pe.slice(),A._meshLoadOptions.ImportVertexColors===!0&&(T.colors=te.slice()),E=[],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)W(_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 Pe={name:be.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:""};he(),v.push(Pe),j=!0,G=!0,L=1}else this.usemtl.test(be)?(ee=be.substring(7).trim(),(!G||!j)&&(he(),Pe={name:"mesh_mm"+L.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,colors:void 0,materialName:ee},L++,v.push(Pe),j=!0),j&&G&&(v[v.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&&(T=v[v.length-1],E.reverse(),re(),T.indices=E,T.positions=ne,T.normals=de,T.uvs=pe,this._meshLoadOptions.ImportVertexColors===!0&&(T.colors=te)),j||(E.reverse(),re(),v.push({name:_.Geometry.RandomId(),indices:E,positions:ne,colors:te,normals:de,uvs:pe,materialName:ee}));for(var ye=[],Be=new Array,ke=0;ke-1;)St.push(st),mt=st+1;if(st===-1&&St.length===0)$.materials[ct].dispose();else for(var wt=0;wt127)return!0;return!1},u.prototype._parseBinary=function(M,C){for(var P=new DataView(C),m=P.getUint32(80,!0),c=0,T=new Float32Array(3*m*3),A=new Float32Array(3*m*3),S=new Uint32Array(3*m),g=0,l=0;l-1||(P.GLTF2[c]=M[c])}}).call(this,U(5))},function(y,f,U){U.r(f),function(_){var R=U(10);U.d(f,"MTLFileLoader",function(){return R.MTLFileLoader}),U.d(f,"OBJFileLoader",function(){return R.OBJFileLoader});var u=_!==void 0?_:typeof window<"u"?window:void 0;if(u!==void 0)for(var M in R)u.BABYLON[M]=R[M]}.call(this,U(5))},function(y,f,U){U.r(f),function(_){var R=U(11);U.d(f,"STLFileLoader",function(){return R.STLFileLoader});var u=_!==void 0?_:typeof window<"u"?window:void 0;if(u!==void 0)for(var M in R)u.BABYLON[M]=R[M]}.call(this,U(5))},,,,function(y,f,U){U.r(f),U.d(f,"GLTFLoaderCoordinateSystemMode",function(){return _.c}),U.d(f,"GLTFLoaderAnimationStartMode",function(){return _.b}),U.d(f,"GLTFLoaderState",function(){return _.d}),U.d(f,"GLTFFileLoader",function(){return _.a}),U.d(f,"GLTFValidation",function(){return _.e}),U.d(f,"GLTF1",function(){return R.a}),U.d(f,"GLTF2",function(){return u.a}),U.d(f,"MTLFileLoader",function(){return M.MTLFileLoader}),U.d(f,"OBJFileLoader",function(){return M.OBJFileLoader}),U.d(f,"STLFileLoader",function(){return C.STLFileLoader}),U(2),U(3),U(8),U(9),U(10),U(11);var _=U(12),R=U(13),u=U(14),M=U(15),C=U(16)}])})})(pl);function kv(ft){let Ze,Ie,y,f;return y=new fl({}),{c(){Ze=hr("div"),Ie=hr("div"),Mi(y.$$.fragment),Lo(Ie,"class","h-10 dark:text-white opacity-50"),Lo(Ze,"class","h-full min-h-[16rem] flex justify-center items-center")},m(U,_){bn(U,Ze,_),ol(Ze,Ie),Ii(y,Ie,null),f=!0},p:Do,i(U){f||(Fn(y.$$.fragment,U),f=!0)},o(U){wn(y.$$.fragment,U),f=!1},d(U){U&&yn(Ze),Di(y)}}}function Gv(ft){let Ze;return{c(){Ze=hr("canvas"),Lo(Ze,"class","w-full h-full object-contain")},m(Ie,y){bn(Ie,Ze,y),ft[5](Ze)},p:Do,i:Do,o:Do,d(Ie){Ie&&yn(Ze),ft[5](null)}}}function zv(ft){let Ze,Ie,y,f,U,_;Ze=new Of({props:{show_label:ft[2],Icon:fl,label:ft[1]||"3D Model"}});const R=[Gv,kv],u=[];function M(C,P){return C[0]?0:1}return y=M(ft),f=u[y]=R[y](ft),{c(){Mi(Ze.$$.fragment),Ie=qr(),f.c(),U=ll()},m(C,P){Ii(Ze,C,P),bn(C,Ie,P),u[y].m(C,P),bn(C,U,P),_=!0},p(C,[P]){const m={};P&4&&(m.show_label=C[2]),P&2&&(m.label=C[1]||"3D Model"),Ze.$set(m);let c=y;y=M(C),y===c?u[y].p(C,P):(ul(),wn(u[c],1,1,()=>{u[c]=null}),hl(),f=u[y],f?f.p(C,P):(f=u[y]=R[y](C),f.c()),Fn(f,1),f.m(U.parentNode,U))},i(C){_||(Fn(Ze.$$.fragment,C),Fn(f),_=!0)},o(C){wn(Ze.$$.fragment,C),wn(f),_=!1},d(C){Di(Ze,C),C&&yn(Ie),u[y].d(C),C&&yn(U)}}}function jv(ft,Ze,Ie){let{value:y}=Ze,{clearColor:f}=Ze,{label:U=""}=Ze,{show_label:_}=Ze;pl.exports.OBJFileLoader.IMPORT_VERTEX_COLORS=!0;let R,u,M;Cf(()=>{M=new zn.exports.Engine(R,!0),window.addEventListener("resize",()=>{M?.resize()})}),Rf(()=>{u&&(u.dispose(),M?.stopRenderLoop(),M?.dispose(),M=null,M=new zn.exports.Engine(R,!0),window.addEventListener("resize",()=>{M?.resize()})),C()});function C(){if(u=new zn.exports.Scene(M),u.createDefaultCameraOrLight(),u.clearColor=f?u.clearColor=new zn.exports.Color4(f[0],f[1],f[2],f[3]):new zn.exports.Color4(.2,.2,.2,1),M?.runRenderLoop(()=>{u.render()}),!y)return;let m;if(y.is_file)m=y.data;else{let c=y.data,T=zn.exports.Tools.DecodeBase64(c),A=new Blob([T]);m=URL.createObjectURL(A)}zn.exports.SceneLoader.Append("",m,u,()=>{u.createDefaultCamera(!0,!0,!0)},void 0,void 0,"."+y.name.split(".")[1])}function P(m){dl[m?"unshift":"push"](()=>{R=m,Ie(3,R)})}return ft.$$set=m=>{"value"in m&&Ie(0,y=m.value),"clearColor"in m&&Ie(4,f=m.clearColor),"label"in m&&Ie(1,U=m.label),"show_label"in m&&Ie(2,_=m.show_label)},[y,U,_,R,f,P]}class Hv extends al{constructor(Ze){super(),sl(this,Ze,jv,zv,cl,{value:0,clearColor:4,label:1,show_label:2})}}function Wv(ft){let Ze,Ie,y,f,U;return Ie=new Vv({props:{absolute:!0}}),Ie.$on("clear",ft[9]),{c(){Ze=hr("div"),Mi(Ie.$$.fragment),y=qr(),f=hr("canvas"),Lo(f,"class","w-full h-full object-contain"),Lo(Ze,"class","input-model w-full h-60 flex justify-center items-center bg-gray-200 dark:bg-gray-600 relative")},m(_,R){bn(_,Ze,R),Ii(Ie,Ze,null),ol(Ze,y),ol(Ze,f),ft[11](f),U=!0},p:Do,i(_){U||(Fn(Ie.$$.fragment,_),U=!0)},o(_){wn(Ie.$$.fragment,_),U=!1},d(_){_&&yn(Ze),Di(Ie),ft[11](null)}}}function Xv(ft){let Ze,Ie,y;function f(_){ft[10](_)}let U={filetype:".obj, .gltf, .glb",$$slots:{default:[Yv]},$$scope:{ctx:ft}};return ft[6]!==void 0&&(U.dragging=ft[6]),Ze=new Uv({props:U}),dl.push(()=>Rv(Ze,"dragging",f)),Ze.$on("load",ft[8]),{c(){Mi(Ze.$$.fragment)},m(_,R){Ii(Ze,_,R),y=!0},p(_,R){const u={};R&131086&&(u.$$scope={dirty:R,ctx:_}),!Ie&&R&64&&(Ie=!0,u.dragging=_[6],Ov(()=>Ie=!1)),Ze.$set(u)},i(_){y||(Fn(Ze.$$.fragment,_),y=!0)},o(_){wn(Ze.$$.fragment,_),y=!1},d(_){Di(Ze,_)}}}function Yv(ft){let Ze,Ie,y,f,U,_,R,u,M;return{c(){Ze=Io(ft[1]),Ie=qr(),y=hr("br"),f=Io("- "),U=Io(ft[2]),_=Io(" -"),R=hr("br"),u=qr(),M=Io(ft[3])},m(C,P){bn(C,Ze,P),bn(C,Ie,P),bn(C,y,P),bn(C,f,P),bn(C,U,P),bn(C,_,P),bn(C,R,P),bn(C,u,P),bn(C,M,P)},p(C,P){P&2&&rl(Ze,C[1]),P&4&&rl(U,C[2]),P&8&&rl(M,C[3])},d(C){C&&yn(Ze),C&&yn(Ie),C&&yn(y),C&&yn(f),C&&yn(U),C&&yn(_),C&&yn(R),C&&yn(u),C&&yn(M)}}}function Kv(ft){let Ze,Ie,y,f,U,_;Ze=new Of({props:{show_label:ft[5],Icon:fl,label:ft[4]||"3D Model"}});const R=[Xv,Wv],u=[];function M(C,P){return C[0]===null?0:1}return y=M(ft),f=u[y]=R[y](ft),{c(){Mi(Ze.$$.fragment),Ie=qr(),f.c(),U=ll()},m(C,P){Ii(Ze,C,P),bn(C,Ie,P),u[y].m(C,P),bn(C,U,P),_=!0},p(C,[P]){const m={};P&32&&(m.show_label=C[5]),P&16&&(m.label=C[4]||"3D Model"),Ze.$set(m);let c=y;y=M(C),y===c?u[y].p(C,P):(ul(),wn(u[c],1,1,()=>{u[c]=null}),hl(),f=u[y],f?f.p(C,P):(f=u[y]=R[y](C),f.c()),Fn(f,1),f.m(U.parentNode,U))},i(C){_||(Fn(Ze.$$.fragment,C),Fn(f),_=!0)},o(C){wn(Ze.$$.fragment,C),wn(f),_=!1},d(C){Di(Ze,C),C&&yn(Ie),u[y].d(C),C&&yn(U)}}}function Qv(ft,Ze,Ie){let{value:y}=Ze,{drop_text:f="Drop a file"}=Ze,{or_text:U="or"}=Ze,{upload_text:_="click to upload"}=Ze,{label:R=""}=Ze,{show_label:u}=Ze;Cf(()=>{y!=null&&S()}),Rf(()=>{y!=null&&y.is_file&&S()});async function M({detail:h}){Ie(0,y=h),await Pf(),P("change",y),S()}async function C(){T&&A&&(T.dispose(),A.dispose()),Ie(0,y=null),await Pf(),P("clear")}const P=Cv();let m=!1;pl.exports.OBJFileLoader.IMPORT_VERTEX_COLORS=!0;let c,T,A;function S(){if(T&&!T.isDisposed&&A&&(T.dispose(),A.dispose()),A=new zn.exports.Engine(c,!0),T=new zn.exports.Scene(A),T.createDefaultCameraOrLight(),T.clearColor=new zn.exports.Color4(.2,.2,.2,1),A.runRenderLoop(()=>{T.render()}),window.addEventListener("resize",()=>{A.resize()}),!y)return;let h;if(y.is_file)h=y.data;else{let v=y.data,E=zn.exports.Tools.DecodeBase64(v),D=new Blob([E]);h=URL.createObjectURL(D)}zn.exports.SceneLoader.Append(h,"",T,()=>{T.createDefaultCamera(!0,!0,!0)},void 0,void 0,"."+y.name.split(".")[1])}function g(h){m=h,Ie(6,m)}function l(h){dl[h?"unshift":"push"](()=>{c=h,Ie(7,c)})}return ft.$$set=h=>{"value"in h&&Ie(0,y=h.value),"drop_text"in h&&Ie(1,f=h.drop_text),"or_text"in h&&Ie(2,U=h.or_text),"upload_text"in h&&Ie(3,_=h.upload_text),"label"in h&&Ie(4,R=h.label),"show_label"in h&&Ie(5,u=h.show_label)},ft.$$.update=()=>{ft.$$.dirty&64&&P("drag",m)},[y,f,U,_,R,u,m,c,M,C,g,l]}class qv extends al{constructor(Ze){super(),sl(this,Ze,Qv,Kv,cl,{value:0,drop_text:1,or_text:2,upload_text:3,label:4,show_label:5})}}function Zv(ft){let Ze,Ie;return Ze=new Hv({props:{value:ft[8],clearColor:ft[4],label:ft[6],show_label:ft[7]}}),{c(){Mi(Ze.$$.fragment)},m(y,f){Ii(Ze,y,f),Ie=!0},p(y,f){const U={};f&256&&(U.value=y[8]),f&16&&(U.clearColor=y[4]),f&64&&(U.label=y[6]),f&128&&(U.show_label=y[7]),Ze.$set(U)},i(y){Ie||(Fn(Ze.$$.fragment,y),Ie=!0)},o(y){wn(Ze.$$.fragment,y),Ie=!1},d(y){Di(Ze,y)}}}function Jv(ft){let Ze,Ie;return Ze=new qv({props:{label:ft[6],show_label:ft[7],value:ft[8],drop_text:ft[10]("interface.drop_file"),or_text:ft[10]("or"),upload_text:ft[10]("interface.click_to_upload")}}),Ze.$on("change",ft[13]),Ze.$on("drag",ft[14]),Ze.$on("change",ft[15]),Ze.$on("clear",ft[16]),{c(){Mi(Ze.$$.fragment)},m(y,f){Ii(Ze,y,f),Ie=!0},p(y,f){const U={};f&64&&(U.label=y[6]),f&128&&(U.show_label=y[7]),f&256&&(U.value=y[8]),f&1024&&(U.drop_text=y[10]("interface.drop_file")),f&1024&&(U.or_text=y[10]("or")),f&1024&&(U.upload_text=y[10]("interface.click_to_upload")),Ze.$set(U)},i(y){Ie||(Fn(Ze.$$.fragment,y),Ie=!0)},o(y){wn(Ze.$$.fragment,y),Ie=!1},d(y){Di(Ze,y)}}}function $v(ft){let Ze,Ie,y,f,U,_;const R=[ft[5]];let u={};for(let m=0;m{C[A]=null}),hl()),~y?(f=C[y],f?f.p(m,c):(f=C[y]=M[y](m),f.c()),Fn(f,1),f.m(U.parentNode,U)):f=null)},i(m){_||(Fn(Ze.$$.fragment,m),Fn(f),_=!0)},o(m){wn(Ze.$$.fragment,m),wn(f),_=!1},d(m){Di(Ze,m),m&&yn(Ie),~y&&C[y].d(m),m&&yn(U)}}}function eb(ft){let Ze,Ie;return Ze=new Mv({props:{visible:ft[2],variant:ft[0]===null?"dashed":"solid",color:ft[9]?"green":"grey",padding:!1,elem_id:ft[1],$$slots:{default:[$v]},$$scope:{ctx:ft}}}),{c(){Mi(Ze.$$.fragment)},m(y,f){Ii(Ze,y,f),Ie=!0},p(y,[f]){const U={};f&4&&(U.visible=y[2]),f&1&&(U.variant=y[0]===null?"dashed":"solid"),f&512&&(U.color=y[9]?"green":"grey"),f&2&&(U.elem_id=y[1]),f&133113&&(U.$$scope={dirty:f,ctx:y}),Ze.$set(U)},i(y){Ie||(Fn(Ze.$$.fragment,y),Ie=!0)},o(y){wn(Ze.$$.fragment,y),Ie=!1},d(y){Di(Ze,y)}}}function tb(ft,Ze,Ie){let y;Iv(ft,Dv,v=>Ie(10,y=v));let{elem_id:f=""}=Ze,{visible:U=!0}=Ze,{value:_=null}=Ze,{mode:R}=Ze,{root:u}=Ze,{root_url:M}=Ze,{clearColor:C}=Ze,{loading_status:P}=Ze,{label:m}=Ze,{show_label:c}=Ze,T,A=!1;const S=({detail:v})=>Ie(0,_=v),g=({detail:v})=>Ie(9,A=v);function l(v){xf.call(this,ft,v)}function h(v){xf.call(this,ft,v)}return ft.$$set=v=>{"elem_id"in v&&Ie(1,f=v.elem_id),"visible"in v&&Ie(2,U=v.visible),"value"in v&&Ie(0,_=v.value),"mode"in v&&Ie(3,R=v.mode),"root"in v&&Ie(11,u=v.root),"root_url"in v&&Ie(12,M=v.root_url),"clearColor"in v&&Ie(4,C=v.clearColor),"loading_status"in v&&Ie(5,P=v.loading_status),"label"in v&&Ie(6,m=v.label),"show_label"in v&&Ie(7,c=v.show_label)},ft.$$.update=()=>{ft.$$.dirty&6145&&Ie(8,T=Bv(_,M??u))},[_,f,U,R,C,P,m,c,T,A,y,u,M,S,g,l,h]}class nb extends al{constructor(Ze){super(),sl(this,Ze,tb,eb,cl,{elem_id:1,visible:2,value:0,mode:3,root:11,root_url:12,clearColor:4,loading_status:5,label:6,show_label:7})}}var ub=nb;const hb=["static","dynamic"],db=ft=>({type:"{ name: string; data: string }",description:"file name and base64 data of Model3D object"});export{ub as Component,_b as ExampleComponent,db as document,hb as modes}; -//# sourceMappingURL=index.a8c8aa0f.js.map diff --git a/spaces/HuseynG/ECS7022P-WGAN-GP/img_styles.css b/spaces/HuseynG/ECS7022P-WGAN-GP/img_styles.css deleted file mode 100644 index 4c023b206342877b913ab85ca8f5373f9fd767df..0000000000000000000000000000000000000000 --- a/spaces/HuseynG/ECS7022P-WGAN-GP/img_styles.css +++ /dev/null @@ -1,4 +0,0 @@ -.gradio-content img { - max-width: 50%; - max-height: 50%; -} \ No newline at end of file diff --git a/spaces/ICML2022/OFA/fairseq/examples/hubert/simple_kmeans/dump_mfcc_feature.py b/spaces/ICML2022/OFA/fairseq/examples/hubert/simple_kmeans/dump_mfcc_feature.py deleted file mode 100644 index 70d0016663b7d0b90033f4eb301b527f2c92a3f8..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/hubert/simple_kmeans/dump_mfcc_feature.py +++ /dev/null @@ -1,78 +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 logging -import os -import sys - -import soundfile as sf -import torch -import torchaudio - -from feature_utils import get_path_iterator, dump_feature - -logging.basicConfig( - format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - level=os.environ.get("LOGLEVEL", "INFO").upper(), - stream=sys.stdout, -) -logger = logging.getLogger("dump_mfcc_feature") - - -class MfccFeatureReader(object): - def __init__(self, sample_rate): - self.sample_rate = sample_rate - - def read_audio(self, path, ref_len=None): - wav, sr = sf.read(path) - assert sr == self.sample_rate, sr - if wav.ndim == 2: - wav = wav.mean(-1) - assert wav.ndim == 1, wav.ndim - if ref_len is not None and abs(ref_len - len(wav)) > 160: - logging.warning(f"ref {ref_len} != read {len(wav)} ({path})") - return wav - - def get_feats(self, path, ref_len=None): - x = self.read_audio(path, ref_len) - with torch.no_grad(): - x = torch.from_numpy(x).float() - x = x.view(1, -1) - - mfccs = torchaudio.compliance.kaldi.mfcc( - waveform=x, - sample_frequency=self.sample_rate, - use_energy=False, - ) # (time, freq) - mfccs = mfccs.transpose(0, 1) # (freq, time) - deltas = torchaudio.functional.compute_deltas(mfccs) - ddeltas = torchaudio.functional.compute_deltas(deltas) - concat = torch.cat([mfccs, deltas, ddeltas], dim=0) - concat = concat.transpose(0, 1).contiguous() # (freq, time) - return concat - - -def main(tsv_dir, split, nshard, rank, feat_dir, sample_rate): - reader = MfccFeatureReader(sample_rate) - generator, num = get_path_iterator(f"{tsv_dir}/{split}.tsv", nshard, rank) - dump_feature(reader, generator, num, split, nshard, rank, feat_dir) - - - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("tsv_dir") - parser.add_argument("split") - parser.add_argument("nshard", type=int) - parser.add_argument("rank", type=int) - parser.add_argument("feat_dir") - parser.add_argument("--sample_rate", type=int, default=16000) - args = parser.parse_args() - logger.info(args) - - main(**vars(args)) diff --git a/spaces/ICML2022/OFA/fairseq/examples/hubert/simple_kmeans/dump_w2v2_feature.py b/spaces/ICML2022/OFA/fairseq/examples/hubert/simple_kmeans/dump_w2v2_feature.py deleted file mode 100644 index a1f0d902acf0756580a1f4604feee8fc499a9a63..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/hubert/simple_kmeans/dump_w2v2_feature.py +++ /dev/null @@ -1,95 +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 logging -import os -import sys - -import fairseq -import soundfile as sf -import torch -import torch.nn.functional as F - -from feature_utils import get_path_iterator, dump_feature - - -logging.basicConfig( - format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - level=os.environ.get("LOGLEVEL", "INFO").upper(), - stream=sys.stdout, -) -logger = logging.getLogger("dump_w2v2_feature") - - -class Wav2Vec2FeatureReader(object): - def __init__(self, ckpt_path, layer, max_chunk=1600000): - ( - model, - cfg, - task, - ) = fairseq.checkpoint_utils.load_model_ensemble_and_task([ckpt_path]) - self.model = model[0].eval().cuda() - self.task = task - self.layer = layer # assume this is 1-based like HuBERT - self.max_chunk = max_chunk - logger.info(f"TASK CONFIG:\n{self.task.cfg}") - logger.info(f" max_chunk = {self.max_chunk}") - logger.info(f" model:\n{self.model}") - - def read_audio(self, path, ref_len=None): - wav, sr = sf.read(path) - assert sr == self.task.cfg.sample_rate, sr - if wav.ndim == 2: - wav = wav.mean(-1) - assert wav.ndim == 1, wav.ndim - if ref_len is not None and abs(ref_len - len(wav)) > 160: - logging.warning(f"ref {ref_len} != read {len(wav)} ({path})") - return wav - - def get_feats(self, path, ref_len=None): - x = self.read_audio(path, ref_len) - with torch.no_grad(): - x = torch.from_numpy(x).float().cuda() - if self.task.cfg.normalize: - x = F.layer_norm(x, x.shape) - x = x.view(1, -1) - - feat = [] - for start in range(0, x.size(1), self.max_chunk): - x_chunk = x[:, start: start + self.max_chunk] - res = self.model.extract_features( - source=x_chunk, - padding_mask=None, - mask=False, - layer=self.layer - 1, - ) - feat_chunk = res["x"] - feat.append(feat_chunk) - return torch.cat(feat, 1).squeeze(0) - - -def main(tsv_dir, split, ckpt_path, layer, nshard, rank, feat_dir, max_chunk): - reader = Wav2Vec2FeatureReader(ckpt_path, layer, max_chunk) - generator, num = get_path_iterator(f"{tsv_dir}/{split}.tsv", nshard, rank) - dump_feature(reader, generator, num, split, nshard, rank, feat_dir) - - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("tsv_dir") - parser.add_argument("split") - parser.add_argument("ckpt_path") - parser.add_argument("layer", type=int) - parser.add_argument("nshard", type=int) - parser.add_argument("rank", type=int) - parser.add_argument("feat_dir") - parser.add_argument("--max_chunk", type=int, default=1600000) - args = parser.parse_args() - logger.info(args) - - main(**vars(args)) diff --git a/spaces/ICML2022/OFA/fairseq/examples/shuffled_word_order/README.md b/spaces/ICML2022/OFA/fairseq/examples/shuffled_word_order/README.md deleted file mode 100644 index f20483849a8ca33bf349b57882a79155ba593bf1..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/shuffled_word_order/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# Masked Language Modeling and the Distributional Hypothesis: Order Word Matters Pre-training for Little - -[https://arxiv.org/abs/2104.06644](https://arxiv.org/abs/2104.06644) - -## Introduction - -In this work, we pre-train [RoBERTa](../roberta) base on various word shuffled variants of BookWiki corpus (16GB). We observe that a word shuffled pre-trained model achieves surprisingly good scores on GLUE, PAWS and several parametric probing tasks. Please read our paper for more details on the experiments. - -## Pre-trained models - -| Model | Description | Download | -| ------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -| `roberta.base.orig` | RoBERTa (base) trained on natural corpus | [roberta.base.orig.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.orig.tar.gz) | -| `roberta.base.shuffle.n1` | RoBERTa (base) trained on n=1 gram sentence word shuffled data | [roberta.base.shuffle.n1.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n1.tar.gz) | -| `roberta.base.shuffle.n2` | RoBERTa (base) trained on n=2 gram sentence word shuffled data | [roberta.base.shuffle.n2.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n2.tar.gz) | -| `roberta.base.shuffle.n3` | RoBERTa (base) trained on n=3 gram sentence word shuffled data | [roberta.base.shuffle.n3.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n3.tar.gz) | -| `roberta.base.shuffle.n4` | RoBERTa (base) trained on n=4 gram sentence word shuffled data | [roberta.base.shuffle.n4.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n4.tar.gz) | -| `roberta.base.shuffle.512` | RoBERTa (base) trained on unigram 512 word block shuffled data | [roberta.base.shuffle.512.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.512.tar.gz) | -| `roberta.base.shuffle.corpus` | RoBERTa (base) trained on unigram corpus word shuffled data | [roberta.base.shuffle.corpus.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus.tar.gz) | -| `roberta.base.shuffle.corpus_uniform` | RoBERTa (base) trained on unigram corpus word shuffled data, where all words are uniformly sampled | [roberta.base.shuffle.corpus_uniform.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus_uniform.tar.gz) | -| `roberta.base.nopos` | RoBERTa (base) without positional embeddings, trained on natural corpus | [roberta.base.nopos.tar.gz](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.nopos.tar.gz) | - -## Results - -[GLUE (Wang et al, 2019)](https://gluebenchmark.com/) & [PAWS (Zhang et al, 2019)](https://github.com/google-research-datasets/paws) _(dev set, single model, single-task fine-tuning, median of 5 seeds)_ - -| name | CoLA | MNLI | MRPC | PAWS | QNLI | QQP | RTE | SST-2 | -| :----------------------------------- | ----: | ----: | ----: | ----: | ----: | ----: | ----: | ----: | -| `roberta.base.orig` | 61.4 | 86.11 | 89.19 | 94.46 | 92.53 | 91.26 | 74.64 | 93.92 | -| `roberta.base.shuffle.n1` | 35.15 | 82.64 | 86 | 89.97 | 89.02 | 91.01 | 69.02 | 90.47 | -| `roberta.base.shuffle.n2` | 54.37 | 83.43 | 86.24 | 93.46 | 90.44 | 91.36 | 70.83 | 91.79 | -| `roberta.base.shuffle.n3` | 48.72 | 83.85 | 86.36 | 94.05 | 91.69 | 91.24 | 70.65 | 92.02 | -| `roberta.base.shuffle.n4` | 58.64 | 83.77 | 86.98 | 94.32 | 91.69 | 91.4 | 70.83 | 92.48 | -| `roberta.base.shuffle.512` | 12.76 | 77.52 | 79.61 | 84.77 | 85.19 | 90.2 | 56.52 | 86.34 | -| `roberta.base.shuffle.corpus` | 0 | 71.9 | 70.52 | 58.52 | 71.11 | 85.52 | 53.99 | 83.35 | -| `roberta.base.shuffle.corpus_random` | 9.19 | 72.33 | 70.76 | 58.42 | 77.76 | 85.93 | 53.99 | 84.04 | -| `roberta.base.nopos` | 0 | 63.5 | 72.73 | 57.08 | 77.72 | 87.87 | 54.35 | 83.24 | - -For more results on probing tasks, please refer to [our paper](https://arxiv.org/abs/2104.06644). - -## Example Usage - -Follow the same usage as in [RoBERTa](https://github.com/pytorch/fairseq/tree/main/examples/roberta) to load and test your models: - -```python -# Download roberta.base.shuffle.n1 model -wget https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n1.tar.gz -tar -xzvf roberta.base.shuffle.n1.tar.gz - -# Load the model in fairseq -from fairseq.models.roberta import RoBERTaModel -roberta = RoBERTaModel.from_pretrained('/path/to/roberta.base.shuffle.n1', checkpoint_file='model.pt') -roberta.eval() # disable dropout (or leave in train mode to finetune) -``` - -**Note**: The model trained without positional embeddings (`roberta.base.nopos`) is a modified `RoBERTa` model, where the positional embeddings are not used. Thus, the typical `from_pretrained` method on fairseq version of RoBERTa will not be able to load the above model weights. To do so, construct a new `RoBERTaModel` object by setting the flag `use_positional_embeddings` to `False` (or [in the latest code](https://github.com/pytorch/fairseq/blob/main/fairseq/models/roberta/model.py#L543), set `no_token_positional_embeddings` to `True`), and then load the individual weights. - -## Fine-tuning Evaluation - -We provide the trained fine-tuned models on MNLI here for each model above for quick evaluation (1 seed for each model). Please refer to [finetuning details](README.finetuning.md) for the parameters of these models. Follow [RoBERTa](https://github.com/pytorch/fairseq/tree/main/examples/roberta) instructions to evaluate these models. - -| Model | MNLI M Dev Accuracy | Link | -| :----------------------------------------- | :------------------ | :--------------------------------------------------------------------------------------------------------------- | -| `roberta.base.orig.mnli` | 86.14 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.orig.mnli.tar.gz) | -| `roberta.base.shuffle.n1.mnli` | 82.55 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n1.mnli.tar.gz) | -| `roberta.base.shuffle.n2.mnli` | 83.21 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n2.mnli.tar.gz) | -| `roberta.base.shuffle.n3.mnli` | 83.89 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n3.mnli.tar.gz) | -| `roberta.base.shuffle.n4.mnli` | 84.00 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.n4.mnli.tar.gz) | -| `roberta.base.shuffle.512.mnli` | 77.22 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.512.mnli.tar.gz) | -| `roberta.base.shuffle.corpus.mnli` | 71.88 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus.mnli.tar.gz) | -| `roberta.base.shuffle.corpus_uniform.mnli` | 72.46 | [Download](https://dl.fbaipublicfiles.com/unnatural_pretraining/roberta.base.shuffle.corpus_uniform.mnli.tar.gz) | - -## Citation - -```bibtex -@misc{sinha2021masked, - title={Masked Language Modeling and the Distributional Hypothesis: Order Word Matters Pre-training for Little}, - author={Koustuv Sinha and Robin Jia and Dieuwke Hupkes and Joelle Pineau and Adina Williams and Douwe Kiela}, - year={2021}, - eprint={2104.06644}, - archivePrefix={arXiv}, - primaryClass={cs.CL} -} -``` diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/modules/transpose_last.py b/spaces/ICML2022/OFA/fairseq/fairseq/modules/transpose_last.py deleted file mode 100644 index e578b3ec5097bfac5c976b207ea46bec1d9bd4f5..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/modules/transpose_last.py +++ /dev/null @@ -1,20 +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. -""" -transpose last 2 dimensions of the input -""" - -import torch.nn as nn - - -class TransposeLast(nn.Module): - def __init__(self, deconstruct_idx=None): - super().__init__() - self.deconstruct_idx = deconstruct_idx - - def forward(self, x): - if self.deconstruct_idx is not None: - x = x[self.deconstruct_idx] - return x.transpose(-2, -1) diff --git a/spaces/ICML2022/resefa/utils/visualizers/html_visualizer.py b/spaces/ICML2022/resefa/utils/visualizers/html_visualizer.py deleted file mode 100644 index 7bb63385af54021febb4791bdda6534324d2d901..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/resefa/utils/visualizers/html_visualizer.py +++ /dev/null @@ -1,438 +0,0 @@ -# python3.7 -"""Contains the visualizer to visualize images with HTML page.""" - -import os -import base64 -import cv2 -import numpy as np -from bs4 import BeautifulSoup - -from ..image_utils import get_grid_shape -from ..image_utils import parse_image_size -from ..image_utils import load_image -from ..image_utils import resize_image -from ..image_utils import list_images_from_dir - -__all__ = ['HtmlVisualizer', 'HtmlReader'] - - -def get_sortable_html_header(column_name_list, sort_by_ascending=False): - """Gets header for sortable HTML page. - - Basically, the HTML page contains a sortable table, where user can sort the - rows by a particular column by clicking the column head. - - Example: - - column_name_list = [name_1, name_2, name_3] - header = get_sortable_html_header(column_name_list) - footer = get_sortable_html_footer() - sortable_table = ... - html_page = header + sortable_table + footer - - Args: - column_name_list: List of column header names. - sort_by_ascending: Default sorting order. If set as `True`, the HTML - page will be sorted by ascending order when the header is clicked - for the first time. - - Returns: - A string, which represents for the header for a sortable HTML page. - """ - header = '\n'.join([ - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '']) - for idx, name in enumerate(column_name_list): - header += f' \n' - header += '\n' - header += '\n' - header += '\n' - - return header - - -def get_sortable_html_footer(): - """Gets footer for sortable HTML page. - - Check function `get_sortable_html_header()` for more details. - """ - return '\n
{name}
\n\n\n\n' - - -def encode_image_to_html_str(image, image_size=None): - """Encodes an image to HTML language. - - NOTE: Input image is always assumed to be with `RGB` channel order. - - Args: - image: The input image to encode. Should be with `RGB` channel order. - image_size: This field is used to resize the image before encoding. - `None` disables resizing. (default: None) - - Returns: - A string that represents the encoded image. - """ - if image is None: - return '' - - assert image.ndim == 3 and image.shape[2] in [1, 3, 4] - if image.shape[2] == 3: - image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) - elif image.shape[2] == 4: - image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGRA) - - # Resize the image if needed. - height, width = parse_image_size(image_size) - height = height or image.shape[0] - width = width or image.shape[1] - if image.shape[0:2] != (height, width): - image = resize_image(image, (width, height)) - - # Encode the image to HTML-format string. - if image.shape[2] == 4: # Use `png` to encoder RGBA image. - encoded = cv2.imencode('.png', image)[1].tostring() - encoded_base64 = base64.b64encode(encoded).decode('utf-8') - html_str = f'' - else: - encoded = cv2.imencode('.jpg', image)[1].tostring() - encoded_base64 = base64.b64encode(encoded).decode('utf-8') - html_str = f'' - - return html_str - - -def decode_html_str_to_image(html_str, image_size=None): - """Decodes an image from HTML string. - - Args: - html_str: An HTML string that represents an image. - image_size: This field is used to resize the image after decoding. - `None` disables resizing. (default: None) - - Returns: - An image with `RGB` channel order. - """ - if not html_str: - return None - - assert isinstance(html_str, str) - image_str = html_str.split(',')[-1].strip() - encoded_image = base64.b64decode(image_str) - encoded_image_numpy = np.frombuffer(encoded_image, dtype=np.uint8) - image = cv2.imdecode(encoded_image_numpy, flags=cv2.IMREAD_UNCHANGED) - - if image.ndim == 2: - image = image[:, :, np.newaxis] - assert image.ndim == 3 and image.shape[2] in [1, 3, 4] - if image.shape[2] == 3: - image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) - if image.shape[2] == 4: - image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA) - - # Resize the image if needed. - height, width = parse_image_size(image_size) - height = height or image.shape[0] - width = width or image.shape[1] - if image.shape[0:2] != (height, width): - image = resize_image(image, (width, height)) - - return image - - -class HtmlVisualizer(object): - """Defines the HTML visualizer that visualizes images on an HTML page. - - This class can be used to visualize image results on an HTML page. - Basically, it is based on an HTML-format sorted table with helper functions - `get_sortable_html_header()`, `get_sortable_html_footer()`, and - `encode_image_to_html_str()`. To simplify the usage, specifying the - following fields are enough to create a visualization page: - - (1) num_rows: Number of rows of the table (header-row exclusive). - (2) num_cols: Number of columns of the table. - (3) header_contents (optional): Title of each column. - - NOTE: `grid_size` can be used to assign `num_rows` and `num_cols` - automatically. - - Example: - - html = HtmlVisualizer(num_rows, num_cols) - html.set_headers([...]) - for i in range(num_rows): - for j in range(num_cols): - html.set_cell(i, j, text=..., image=..., highlight=False) - html.save('visualize.html') - """ - - def __init__(self, - grid_size=0, - num_rows=0, - num_cols=0, - is_portrait=True, - image_size=None): - """Initializes the html visualizer. - - Args: - grid_size: Total number of cells, i.e., height * width. (default: 0) - num_rows: Number of rows. (default: 0) - num_cols: Number of columns. (default: 0) - is_portrait: Whether the HTML page should be portrait or landscape. - This is only used when it requires to compute `num_rows` and - `num_cols` automatically. See function `get_grid_shape()` in - file `./image_utils.py` for details. (default: True) - image_size: Size to visualize each image. (default: None) - """ - self.reset(grid_size, num_rows, num_cols, is_portrait) - self.set_image_size(image_size) - - def reset(self, - grid_size=0, - num_rows=0, - num_cols=0, - is_portrait=True): - """Resets the HTML page with new number of rows and columns.""" - if grid_size > 0: - num_rows, num_cols = get_grid_shape(grid_size, - height=num_rows, - width=num_cols, - is_portrait=is_portrait) - self.grid_size = num_rows * num_cols - self.num_rows = num_rows - self.num_cols = num_cols - self.headers = ['' for _ in range(self.num_cols)] - self.cells = [[{ - 'text': '', - 'image': '', - 'highlight': False, - } for _ in range(self.num_cols)] for _ in range(self.num_rows)] - - def set_image_size(self, image_size=None): - """Sets the image size of each cell in the HTML page.""" - self.image_size = image_size - - def set_header(self, col_idx, content): - """Sets the content of a particular header by column index.""" - self.headers[col_idx] = content - - def set_headers(self, contents): - """Sets the contents of all headers.""" - assert isinstance(contents, (list, tuple)) - assert len(contents) == self.num_cols - for col_idx, content in enumerate(contents): - self.set_header(col_idx, content) - - def set_cell(self, row_idx, col_idx, text='', image=None, highlight=False): - """Sets the content of a particular cell. - - Basically, a cell contains some text as well as an image. Both text and - image can be empty. - - NOTE: The image is assumed to be with `RGB` channel order. - - Args: - row_idx: Row index of the cell to edit. - col_idx: Column index of the cell to edit. - text: Text to add into the target cell. (default: None) - image: Image to show in the target cell. Should be with `RGB` - channel order. (default: None) - highlight: Whether to highlight this cell. (default: False) - """ - self.cells[row_idx][col_idx]['text'] = text - self.cells[row_idx][col_idx]['image'] = encode_image_to_html_str( - image, self.image_size) - self.cells[row_idx][col_idx]['highlight'] = bool(highlight) - - def visualize_collection(self, - images, - save_path=None, - num_rows=0, - num_cols=0, - is_portrait=True, - is_row_major=True): - """Visualizes a collection of images one by one.""" - self.reset(grid_size=len(images), - num_rows=num_rows, - num_cols=num_cols, - is_portrait=is_portrait) - for idx, image in enumerate(images): - if is_row_major: - row_idx, col_idx = divmod(idx, self.num_cols) - else: - col_idx, row_idx = divmod(idx, self.num_rows) - self.set_cell(row_idx, col_idx, text=f'Index {idx:03d}', - image=image) - if save_path: - self.save(save_path) - - def visualize_list(self, - image_list, - save_path=None, - num_rows=0, - num_cols=0, - is_portrait=True, - is_row_major=True): - """Visualizes a list of image files.""" - self.reset(grid_size=len(image_list), - num_rows=num_rows, - num_cols=num_cols, - is_portrait=is_portrait) - for idx, filename in enumerate(image_list): - basename = os.path.basename(filename) - image = load_image(filename) - if is_row_major: - row_idx, col_idx = divmod(idx, self.num_cols) - else: - col_idx, row_idx = divmod(idx, self.num_rows) - self.set_cell(row_idx, col_idx, - text=f'{basename} (index {idx:03d})', image=image) - if save_path: - self.save(save_path) - - def visualize_directory(self, - directory, - save_path=None, - num_rows=0, - num_cols=0, - is_portrait=True, - is_row_major=True): - """Visualizes all images under a directory.""" - image_list = list_images_from_dir(directory) - self.visualize_list(image_list=image_list, - save_path=save_path, - num_rows=num_rows, - num_cols=num_cols, - is_portrait=is_portrait, - is_row_major=is_row_major) - - def save(self, path): - """Saves the HTML page.""" - html = '' - for i in range(self.num_rows): - html += '\n' - for j in range(self.num_cols): - text = self.cells[i][j]['text'] - image = self.cells[i][j]['image'] - if self.cells[i][j]['highlight']: - color = ' bgcolor="#FF8888"' - else: - color = '' - if text: - html += f' {text}

{image}\n' - else: - html += f' {image}\n' - html += '\n' - - header = get_sortable_html_header(self.headers) - footer = get_sortable_html_footer() - - with open(path, 'w') as f: - f.write(header + html + footer) - - -class HtmlReader(object): - """Defines the HTML page reader. - - This class can be used to parse results from the visualization page - generated by `HtmlVisualizer`. - - Example: - - html = HtmlReader(html_path) - for j in range(html.num_cols): - header = html.get_header(j) - for i in range(html.num_rows): - for j in range(html.num_cols): - text = html.get_text(i, j) - image = html.get_image(i, j, image_size=None) - """ - def __init__(self, path): - """Initializes by loading the content from file.""" - self.path = path - - # Load content. - with open(path, 'r') as f: - self.html = BeautifulSoup(f, 'html.parser') - - # Parse headers. - thead = self.html.find('thead') - headers = thead.findAll('th') - self.headers = [] - for header in headers: - self.headers.append(header.text) - self.num_cols = len(self.headers) - - # Parse cells. - tbody = self.html.find('tbody') - rows = tbody.findAll('tr') - self.cells = [] - for row in rows: - cells = row.findAll('td') - self.cells.append([]) - for cell in cells: - self.cells[-1].append({ - 'text': cell.text, - 'image': cell.find('img')['src'], - }) - assert len(self.cells[-1]) == self.num_cols - self.num_rows = len(self.cells) - - def get_header(self, j): - """Gets header for a particular column.""" - return self.headers[j] - - def get_text(self, i, j): - """Gets text from a particular cell.""" - return self.cells[i][j]['text'] - - def get_image(self, i, j, image_size=None): - """Gets image from a particular cell.""" - return decode_html_str_to_image(self.cells[i][j]['image'], image_size) diff --git a/spaces/Illia56/llama-2-7b-chat/app.py b/spaces/Illia56/llama-2-7b-chat/app.py deleted file mode 100644 index 44d9f871d7557e9a2388c974ad0d20480adca4d3..0000000000000000000000000000000000000000 --- a/spaces/Illia56/llama-2-7b-chat/app.py +++ /dev/null @@ -1,428 +0,0 @@ -"""Run codes.""" -# pylint: disable=line-too-long, broad-exception-caught, invalid-name, missing-function-docstring, too-many-instance-attributes, missing-class-docstring -# ruff: noqa: E501 -import os -import platform -import random -import time -from dataclasses import asdict, dataclass -from pathlib import Path - -# from types import SimpleNamespace -import gradio as gr -import psutil -from about_time import about_time -from ctransformers import AutoModelForCausalLM -from dl_hf_model import dl_hf_model -from loguru import logger - -filename_list = [ - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q2_K.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_L.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_M.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_S.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_0.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_1.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_M.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_S.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_0.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_1.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_K_M.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_K_S.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q6_K.bin", - "Wizard-Vicuna-7B-Uncensored.ggmlv3.q8_0.bin", -] - - -URL = "https://huggingface.co/TheBloke/Wizard-Vicuna-7B-Uncensored-GGML/raw/main/Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_M.bin" # 4.05G - -url = "https://huggingface.co/savvamadar/ggml-gpt4all-j-v1.3-groovy/blob/main/ggml-gpt4all-j-v1.3-groovy.bin" -url = "https://huggingface.co/TheBloke/Llama-2-13B-GGML/blob/main/llama-2-13b.ggmlv3.q4_K_S.bin" # 7.37G -# url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.bin" -url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.bin" # 6.93G -# url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.binhttps://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q4_K_M.bin" # 7.87G - -url = "https://huggingface.co/localmodels/Llama-2-13B-Chat-ggml/blob/main/llama-2-13b-chat.ggmlv3.q4_K_S.bin" # 7.37G - -_ = ( - "golay" in platform.node() - or "okteto" in platform.node() - or Path("/kaggle").exists() - # or psutil.cpu_count(logical=False) < 4 - or 1 # run 7b in hf -) - -if _: - # url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q2_K.bin" - url = "https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q2_K.bin" # 2.87G - url = "https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q4_K_M.bin" # 2.87G - -prompt_template = """Below is an instruction that describes a task. Write a response that appropriately completes the request. - -### Instruction: {user_prompt} - -### Response: -""" - -prompt_template = """System: You are a helpful, -respectful and honest assistant. Always answer as -helpfully as possible, while being safe. Your answers -should not include any harmful, unethical, racist, -sexist, toxic, dangerous, or illegal content. Please -ensure that your responses are socially unbiased and -positive in nature. If a question does not make any -sense, or is not factually coherent, explain why instead -of answering something not correct. If you don't know -the answer to a question, please don't share false -information. -User: {prompt} -Assistant: """ - -prompt_template = """System: You are a helpful assistant. -User: {prompt} -Assistant: """ - -prompt_template = """Question: {question} -Answer: Let's work this out in a step by step way to be sure we have the right answer.""" - -prompt_template = """[INST] <> -You are a helpful, respectful and honest assistant. Always answer as helpfully as possible assistant. Think step by step. -<> - -What NFL team won the Super Bowl in the year Justin Bieber was born? -[/INST]""" - -prompt_template = """[INST] <> -You are an unhelpful assistant. Always answer as helpfully as possible. Think step by step. <> - -{question} [/INST] -""" - -prompt_template = """[INST] <> -You are a helpful assistant. -<> - -{question} [/INST] -""" - -_ = [elm for elm in prompt_template.splitlines() if elm.strip()] -stop_string = [elm.split(":")[0] + ":" for elm in _][-2] - -logger.debug(f"{stop_string=}") - -_ = psutil.cpu_count(logical=False) - 1 -cpu_count: int = int(_) if _ else 1 -logger.debug(f"{cpu_count=}") - -LLM = None - -try: - model_loc, file_size = dl_hf_model(url) -except Exception as exc_: - logger.error(exc_) - raise SystemExit(1) from exc_ - -LLM = AutoModelForCausalLM.from_pretrained( - model_loc, - model_type="llama", - # threads=cpu_count, -) - -logger.info(f"done load llm {model_loc=} {file_size=}G") - -os.environ["TZ"] = "Asia/Shanghai" -try: - time.tzset() # type: ignore # pylint: disable=no-member -except Exception: - # Windows - logger.warning("Windows, cant run time.tzset()") - -_ = """ -ns = SimpleNamespace( - response="", - generator=(_ for _ in []), -) -# """ - -@dataclass -class GenerationConfig: - temperature: float = 0.7 - top_k: int = 50 - top_p: float = 0.9 - repetition_penalty: float = 1.0 - max_new_tokens: int = 512 - seed: int = 42 - reset: bool = False - stream: bool = True - # threads: int = cpu_count - # stop: list[str] = field(default_factory=lambda: [stop_string]) - - -def generate( - question: str, - llm=LLM, - config: GenerationConfig = GenerationConfig(), -): - """Run model inference, will return a Generator if streaming is true.""" - # _ = prompt_template.format(question=question) - # print(_) - - prompt = prompt_template.format(question=question) - - return llm( - prompt, - **asdict(config), - ) - - -logger.debug(f"{asdict(GenerationConfig())=}") - - -def user(user_message, history): - # return user_message, history + [[user_message, None]] - history.append([user_message, None]) - return user_message, history # keep user_message - - -def user1(user_message, history): - # return user_message, history + [[user_message, None]] - history.append([user_message, None]) - return "", history # clear user_message - - -def bot_(history): - user_message = history[-1][0] - resp = random.choice(["How are you?", "I love you", "I'm very hungry"]) - bot_message = user_message + ": " + resp - history[-1][1] = "" - for character in bot_message: - history[-1][1] += character - time.sleep(0.02) - yield history - - history[-1][1] = resp - yield history - - -def bot(history): - user_message = history[-1][0] - response = [] - - logger.debug(f"{user_message=}") - - with about_time() as atime: # type: ignore - flag = 1 - prefix = "" - then = time.time() - - logger.debug("about to generate") - - config = GenerationConfig(reset=True) - for elm in generate(user_message, config=config): - if flag == 1: - logger.debug("in the loop") - prefix = f"({time.time() - then:.2f}s) " - flag = 0 - print(prefix, end="", flush=True) - logger.debug(f"{prefix=}") - print(elm, end="", flush=True) - # logger.debug(f"{elm}") - - response.append(elm) - history[-1][1] = prefix + "".join(response) - yield history - - _ = ( - f"(time elapsed: {atime.duration_human}, " # type: ignore - f"{atime.duration/len(''.join(response)):.2f}s/char)" # type: ignore - ) - - history[-1][1] = "".join(response) + f"\n{_}" - yield history - - -def predict_api(prompt): - logger.debug(f"{prompt=}") - try: - # user_prompt = prompt - config = GenerationConfig( - temperature=0.2, - top_k=10, - top_p=0.9, - repetition_penalty=1.0, - max_new_tokens=512, # adjust as needed - seed=42, - reset=True, # reset history (cache) - stream=False, - # threads=cpu_count, - # stop=prompt_prefix[1:2], - ) - - response = generate( - prompt, - config=config, - ) - - logger.debug(f"api: {response=}") - except Exception as exc: - logger.error(exc) - response = f"{exc=}" - # bot = {"inputs": [response]} - # bot = [(prompt, response)] - - return response - - -css = """ - .importantButton { - background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important; - border: none !important; - } - .importantButton:hover { - background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important; - border: none !important; - } - .disclaimer {font-variant-caps: all-small-caps; font-size: xx-small;} - .xsmall {font-size: x-small;} -""" -etext = """In America, where cars are an important part of the national psyche, a decade ago people had suddenly started to drive less, which had not happened since the oil shocks of the 1970s. """ -examples_list = [ - ["What NFL team won the Super Bowl in the year Justin Bieber was born?"], - [ - "What NFL team won the Super Bowl in the year Justin Bieber was born? Think step by step." - ], - ["How to pick a lock? Provide detailed steps."], - -] - -logger.info("start block") - -with gr.Blocks( - title=f"{Path(model_loc).name}", - theme=gr.themes.Base(), - css=css, -) as block: - # buff_var = gr.State("") - with gr.Accordion("🎈 Info", open=False): - # gr.HTML( - # """
Duplicate and spin a CPU UPGRADE to avoid the queue
""" - # ) - gr.Markdown( - f"""
{Path(model_loc).name}
- Most examples are meant for another model. - You probably should try to test - some related prompts.""", - elem_classes="xsmall", - ) - - # chatbot = gr.Chatbot().style(height=700) # 500 - chatbot = gr.Chatbot(height=500) - - # buff = gr.Textbox(show_label=False, visible=True) - - with gr.Row(): - with gr.Column(scale=5): - msg = gr.Textbox( - label="Chat Message Box", - placeholder="Ask me anything (press Shift+Enter or click Submit to send)", - show_label=False, - # container=False, - lines=6, - max_lines=30, - show_copy_button=True, - # ).style(container=False) - ) - with gr.Column(scale=1, min_width=50): - with gr.Row(): - submit = gr.Button("Submit", elem_classes="xsmall") - stop = gr.Button("Stop", visible=True) - clear = gr.Button("Clear History", visible=True) - with gr.Row(visible=False): - with gr.Accordion("Advanced Options:", open=False): - with gr.Row(): - with gr.Column(scale=2): - system = gr.Textbox( - label="System Prompt", - value=prompt_template, - show_label=False, - container=False, - # ).style(container=False) - ) - with gr.Column(): - with gr.Row(): - change = gr.Button("Change System Prompt") - reset = gr.Button("Reset System Prompt") - - with gr.Accordion("Example Inputs", open=True): - examples = gr.Examples( - examples=examples_list, - inputs=[msg], - examples_per_page=40, - ) - - # with gr.Row(): - with gr.Accordion("Disclaimer", open=False): - _ = Path(model_loc).name - gr.Markdown( - f"Disclaimer: Lauche - AI (POWERED BY LLAMA 2) can produce factually incorrect output, and should not be relied on to produce " - "factually accurate information. Lauche - AI (POWERED BY LLAMA 2) was trained on various public datasets; while great efforts " - "have been taken to clean the pretraining data, it is possible that this model could generate lewd, " - "biased, or otherwise offensive outputs." - " - - - " - "Our Impressum: https://lauche.eu/n-impressum" - " - - - " - "Visit this space on our website: ai-app.lauche.online", - elem_classes=["disclaimer"], - ) - - msg_submit_event = msg.submit( - # fn=conversation.user_turn, - fn=user, - inputs=[msg, chatbot], - outputs=[msg, chatbot], - queue=True, - show_progress="full", - # api_name=None, - ).then(bot, chatbot, chatbot, queue=True) - submit_click_event = submit.click( - # fn=lambda x, y: ("",) + user(x, y)[1:], # clear msg - fn=user1, # clear msg - inputs=[msg, chatbot], - outputs=[msg, chatbot], - queue=True, - # queue=False, - show_progress="full", - # api_name=None, - ).then(bot, chatbot, chatbot, queue=True) - stop.click( - fn=None, - inputs=None, - outputs=None, - cancels=[msg_submit_event, submit_click_event], - queue=False, - ) - clear.click(lambda: None, None, chatbot, queue=False) - - - # block.load(update_buff, [], buff, every=1) - # block.load(update_buff, [buff_var], [buff_var, buff], every=1) - -# concurrency_count=5, max_size=20 -# max_size=36, concurrency_count=14 -# CPU cpu_count=2 16G, model 7G -# CPU UPGRADE cpu_count=8 32G, model 7G - -# does not work -_ = """ -# _ = int(psutil.virtual_memory().total / 10**9 // file_size - 1) -# concurrency_count = max(_, 1) -if psutil.cpu_count(logical=False) >= 8: - # concurrency_count = max(int(32 / file_size) - 1, 1) -else: - # concurrency_count = max(int(16 / file_size) - 1, 1) -# """ - -concurrency_count = 1 -logger.info(f"{concurrency_count=}") - -block.queue(concurrency_count=concurrency_count, max_size=5).launch(debug=True) diff --git a/spaces/Illumotion/Koboldcpp/scripts/run-all-ppl.sh b/spaces/Illumotion/Koboldcpp/scripts/run-all-ppl.sh deleted file mode 100644 index e04d61d7fe0910c60e7f8a05861c0365bad67e84..0000000000000000000000000000000000000000 --- a/spaces/Illumotion/Koboldcpp/scripts/run-all-ppl.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash - -qnt=(f16 q8_0 q6_k q5_k q5_1 q5_0 q4_k q4_1 q4_0 q3_k q2_k) -args="-ngl 999 -t 8" - -if [ -z "$1" ]; then - echo "usage: $0 [qnt] [args]" - echo "default: $0 \"${qnt[@]}\" \"${args}\"" - exit 1 -fi - -if [ ! -z "$2" ]; then - qnt=($2) -fi - -if [ ! -z "$3" ]; then - args="$3" -fi - -set -o pipefail -set -e - -model="$1" -out="../tmp/results-${model}" - -mkdir -p ${out} - -for q in ${qnt[@]}; do - time ./bin/perplexity -m ../models/${model}/ggml-model-f16.gguf -f ./wiki.test.raw ${args} 2>&1 | tee ${out}/ppl-${q}.txt -done diff --git a/spaces/JUNGU/VToonify/vtoonify/model/stylegan/op_gpu/upfirdn2d.py b/spaces/JUNGU/VToonify/vtoonify/model/stylegan/op_gpu/upfirdn2d.py deleted file mode 100644 index 3a12f15b3c2347194e3bf0fdfda736415693775f..0000000000000000000000000000000000000000 --- a/spaces/JUNGU/VToonify/vtoonify/model/stylegan/op_gpu/upfirdn2d.py +++ /dev/null @@ -1,209 +0,0 @@ -from collections import abc -import os - -import torch -from torch.nn import functional as F -from torch.autograd import Function -from torch.utils.cpp_extension import load - - -module_path = os.path.dirname(__file__) -upfirdn2d_op = load( - "upfirdn2d", - sources=[ - os.path.join(module_path, "upfirdn2d.cpp"), - os.path.join(module_path, "upfirdn2d_kernel.cu"), - ], -) - - -class UpFirDn2dBackward(Function): - @staticmethod - def forward( - ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size - ): - - up_x, up_y = up - down_x, down_y = down - g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad - - grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) - - grad_input = upfirdn2d_op.upfirdn2d( - grad_output, - grad_kernel, - down_x, - down_y, - up_x, - up_y, - g_pad_x0, - g_pad_x1, - g_pad_y0, - g_pad_y1, - ) - grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) - - ctx.save_for_backward(kernel) - - pad_x0, pad_x1, pad_y0, pad_y1 = pad - - ctx.up_x = up_x - ctx.up_y = up_y - ctx.down_x = down_x - ctx.down_y = down_y - ctx.pad_x0 = pad_x0 - ctx.pad_x1 = pad_x1 - ctx.pad_y0 = pad_y0 - ctx.pad_y1 = pad_y1 - ctx.in_size = in_size - ctx.out_size = out_size - - return grad_input - - @staticmethod - def backward(ctx, gradgrad_input): - kernel, = ctx.saved_tensors - - gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.in_size[3], 1) - - gradgrad_out = upfirdn2d_op.upfirdn2d( - gradgrad_input, - kernel, - ctx.up_x, - ctx.up_y, - ctx.down_x, - ctx.down_y, - ctx.pad_x0, - ctx.pad_x1, - ctx.pad_y0, - ctx.pad_y1, - ) - # gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.out_size[0], ctx.out_size[1], ctx.in_size[3]) - gradgrad_out = gradgrad_out.view( - ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1] - ) - - return gradgrad_out, None, None, None, None, None, None, None, None - - -class UpFirDn2d(Function): - @staticmethod - def forward(ctx, input, kernel, up, down, pad): - up_x, up_y = up - down_x, down_y = down - pad_x0, pad_x1, pad_y0, pad_y1 = pad - - kernel_h, kernel_w = kernel.shape - batch, channel, in_h, in_w = input.shape - ctx.in_size = input.shape - - input = input.reshape(-1, in_h, in_w, 1) - - ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) - - out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h + down_y) // down_y - out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w + down_x) // down_x - ctx.out_size = (out_h, out_w) - - ctx.up = (up_x, up_y) - ctx.down = (down_x, down_y) - ctx.pad = (pad_x0, pad_x1, pad_y0, pad_y1) - - g_pad_x0 = kernel_w - pad_x0 - 1 - g_pad_y0 = kernel_h - pad_y0 - 1 - g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 - g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 - - ctx.g_pad = (g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) - - out = upfirdn2d_op.upfirdn2d( - input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1 - ) - # out = out.view(major, out_h, out_w, minor) - out = out.view(-1, channel, out_h, out_w) - - return out - - @staticmethod - def backward(ctx, grad_output): - kernel, grad_kernel = ctx.saved_tensors - - grad_input = None - - if ctx.needs_input_grad[0]: - grad_input = UpFirDn2dBackward.apply( - grad_output, - kernel, - grad_kernel, - ctx.up, - ctx.down, - ctx.pad, - ctx.g_pad, - ctx.in_size, - ctx.out_size, - ) - - return grad_input, None, None, None, None - - -def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): - if not isinstance(up, abc.Iterable): - up = (up, up) - - if not isinstance(down, abc.Iterable): - down = (down, down) - - if len(pad) == 2: - pad = (pad[0], pad[1], pad[0], pad[1]) - - if input.device.type == "cpu": - out = upfirdn2d_native(input, kernel, *up, *down, *pad) - - else: - out = UpFirDn2d.apply(input, kernel, up, down, pad) - - return out - - -def upfirdn2d_native( - input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1 -): - _, channel, in_h, in_w = input.shape - input = input.reshape(-1, in_h, in_w, 1) - - _, in_h, in_w, minor = input.shape - kernel_h, kernel_w = kernel.shape - - out = input.view(-1, in_h, 1, in_w, 1, minor) - out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) - out = out.view(-1, in_h * up_y, in_w * up_x, minor) - - out = F.pad( - out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)] - ) - out = out[ - :, - max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0), - max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0), - :, - ] - - out = out.permute(0, 3, 1, 2) - out = out.reshape( - [-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1] - ) - w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) - out = F.conv2d(out, w) - out = out.reshape( - -1, - minor, - in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, - in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, - ) - out = out.permute(0, 2, 3, 1) - out = out[:, ::down_y, ::down_x, :] - - out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h + down_y) // down_y - out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w + down_x) // down_x - - return out.view(-1, channel, out_h, out_w) diff --git a/spaces/Jackflack09/diffuse-custom/diffusers/models/__init__.py b/spaces/Jackflack09/diffuse-custom/diffusers/models/__init__.py deleted file mode 100644 index 5b101d1691483ea051352216589cdf7cebfed81e..0000000000000000000000000000000000000000 --- a/spaces/Jackflack09/diffuse-custom/diffusers/models/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2022 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. - -from ..utils import is_flax_available, is_torch_available - - -if is_torch_available(): - from .attention import Transformer2DModel - from .unet_1d import UNet1DModel - from .unet_2d import UNet2DModel - from .unet_2d_condition import UNet2DConditionModel - from .vae import AutoencoderKL, VQModel - -if is_flax_available(): - from .unet_2d_condition_flax import FlaxUNet2DConditionModel - from .vae_flax import FlaxAutoencoderKL diff --git a/spaces/Jaehan/Image-Classification-Using-a-Vision-Transformer-1/README.md b/spaces/Jaehan/Image-Classification-Using-a-Vision-Transformer-1/README.md deleted file mode 100644 index e6e8990090314c408b167b66dc8387fa93a591c4..0000000000000000000000000000000000000000 --- a/spaces/Jaehan/Image-Classification-Using-a-Vision-Transformer-1/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Image Classification Using A Vision Transformer 1 -emoji: 📉 -colorFrom: purple -colorTo: green -sdk: gradio -sdk_version: 3.35.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Jashvinu/NousResearch-Redmond-Hermes-Coder/app.py b/spaces/Jashvinu/NousResearch-Redmond-Hermes-Coder/app.py deleted file mode 100644 index 9af8210592648fa2675c4bbad73a49b1f2eee87e..0000000000000000000000000000000000000000 --- a/spaces/Jashvinu/NousResearch-Redmond-Hermes-Coder/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/NousResearch/Redmond-Hermes-Coder").launch() \ No newline at end of file diff --git a/spaces/JayRaghav/Image_segmentation/app.py b/spaces/JayRaghav/Image_segmentation/app.py deleted file mode 100644 index c7298a3e889931979f2dfcc8ac0122c3e17cb985..0000000000000000000000000000000000000000 --- a/spaces/JayRaghav/Image_segmentation/app.py +++ /dev/null @@ -1,13 +0,0 @@ -import gradio as gr -from rembg import remove - -title = "Vanish Background" -description = "Remove background for any image , To use it, simply upload your image and wait. Read more at the link below of official documentation." -article = "

Github Repo

" - -def segment(image): - return remove(image) - -demo = gr.Interface(fn=segment, inputs="image", outputs="image", title=title, description=description, article=article) -demo.queue(concurrency_count=3) -demo.launch() \ No newline at end of file diff --git a/spaces/Jean-Baptiste/email_parser/app.py b/spaces/Jean-Baptiste/email_parser/app.py deleted file mode 100644 index 1001952768a84495b5575c10ce8beeca63d9f6bd..0000000000000000000000000000000000000000 --- a/spaces/Jean-Baptiste/email_parser/app.py +++ /dev/null @@ -1,138 +0,0 @@ -import os -os.system("pip uninstall -y gradio") -os.system("pip install gradio==2.7.5.2") -os.system("pip install typing-extensions --upgrade") - - -import logging, regex -import gradio -from email_parser import utils, nlp -from email_parser.doc_email import Email - -def print_highlighted_text(text, df_result, offset=0): - iter_match = regex.finditer("\s|$", text) - start_pos = 0 - list_values = [] - for match in iter_match: - word = match.string[start_pos:match.start()] - logging.debug(f"word '{word}' was found between {start_pos} and {match.start()}") - df_entity = df_result.query(f"{start_pos + offset}>=start & {start_pos + offset}<=end").head(1) - logging.debug(f"Found entites are: {df_entity}") - if len(df_entity) == 1: - entity = df_entity["entity"].values[0] - else: - entity = None - list_values.append((word, entity)) - # list_values.append((match.string[match.start():match.end()], None)) - start_pos = match.end() - return list_values - - -def display_email(text, part=1): - doc = Email(text) - list_emails = doc.list_emails - if part <= len(list_emails): - text = list_emails[int(part-1)]["body"] - header = list_emails[int(part-1)]["header"] - lang = nlp.f_detect_language(text) - - if len(header)>0: - df_results_header = nlp.f_ner(header, lang=lang) - df_results_header = Email.f_find_person_in_header(header, df_result=df_results_header) - list_words_headers = print_highlighted_text(header, df_results_header) - else: - list_words_headers = None - - df_result = nlp.f_ner(text, lang=lang) - logging.debug(f"NER results for text '{text}' are: {df_result}") - df_signature = nlp.f_detect_email_signature(text, df_ner=df_result) - if df_signature is not None and len(df_signature) > 0: - start_signature_position = df_signature["start"].values[0] - text_body = text[:start_signature_position] - text_signature = text[start_signature_position:] - list_words_signature = print_highlighted_text(text_signature, df_result, offset=start_signature_position) - else: - text_body = text - list_words_signature = None - list_words_body = print_highlighted_text(text_body, df_result) - - return None, lang, list_words_headers, list_words_body, list_words_signature - else: - return f"Email number {int(part)} was requested but only {len(list_emails)} emails was found in this thread", \ - None, None, None, None - - -utils.f_setup_logger(level_sysout=logging.INFO, level_file=logging.INFO, folder_path="logs") - - -iface = gradio.Interface(title="Parser of email", - description="Small application that can extract a specific email in a thread of email," - " highlights the entities found in the text (person, organization, date,...)" - " and extract email signature if any.", - article="*The model used to detect signature is described in detail here: " - "" - "https://medium.com/@jean-baptiste.polle/lstm-model-for-email-signature-detection-8e990384fefa" - "", - fn=display_email, - inputs=["textbox", - gradio.inputs.Number(default=1, label="Email number in thread")], - outputs=[ - gradio.outputs.Textbox(type="str", label="Error"), - gradio.outputs.Textbox(type="str", label="Language"), - gradio.outputs.HighlightedText(label="Header"), - gradio.outputs.HighlightedText(label="Body"), - gradio.outputs.HighlightedText(label="Signature")], - examples=[["""Bonjour Vincent, -Merci de m’avoir rappelé hier. -Seriez vous disponible pour un rendez vous la semaine prochaine? -Merci, -Jean-Baptiste""", 1], ["""Hello Jack, - -I hope you had nice holiday as well. -Please find attached the requested documents, - -Best Regards, -George -Vice president of Something -email: george@google.com -tel: 512-222-5555 - -On Mon, Jan 7, 2022 at 12:39 PM, Jack wrote: - -Hello George, - -I wish you a happy new year. I hope you had nice holidays. -Did you see Garry during your vacation? -Do you have the documents I requested earlier? - -Thanks, -Jack - - -""", 1] , ["""Hello Jack, - -I hope you had nice holiday as well. -Please find attached the requested documents, - -Best Regards, -George -Vice president of Something -email: george@google.com -tel: 512-222-5555 - -On Mon, Jan 7, 2022 at 12:39 PM, Jack wrote: - -Hello George, - -I wish you a happy new year. I hope you had nice holidays. -Did you see Garry during your vacation? -Do you have the documents I requested earlier? - -Thanks, -Jack - - -""", 2] ]) - - -iface.launch() \ No newline at end of file diff --git a/spaces/JoeyFoursheds/ClonerHug/infer_pack/transforms.py b/spaces/JoeyFoursheds/ClonerHug/infer_pack/transforms.py deleted file mode 100644 index a11f799e023864ff7082c1f49c0cc18351a13b47..0000000000000000000000000000000000000000 --- a/spaces/JoeyFoursheds/ClonerHug/infer_pack/transforms.py +++ /dev/null @@ -1,209 +0,0 @@ -import torch -from torch.nn import functional as F - -import numpy as np - - -DEFAULT_MIN_BIN_WIDTH = 1e-3 -DEFAULT_MIN_BIN_HEIGHT = 1e-3 -DEFAULT_MIN_DERIVATIVE = 1e-3 - - -def piecewise_rational_quadratic_transform( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails=None, - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if tails is None: - spline_fn = rational_quadratic_spline - spline_kwargs = {} - else: - spline_fn = unconstrained_rational_quadratic_spline - spline_kwargs = {"tails": tails, "tail_bound": tail_bound} - - outputs, logabsdet = spline_fn( - inputs=inputs, - unnormalized_widths=unnormalized_widths, - unnormalized_heights=unnormalized_heights, - unnormalized_derivatives=unnormalized_derivatives, - inverse=inverse, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - **spline_kwargs - ) - return outputs, logabsdet - - -def searchsorted(bin_locations, inputs, eps=1e-6): - bin_locations[..., -1] += eps - return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1 - - -def unconstrained_rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails="linear", - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) - - if tails == "linear": - unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) - constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives[..., 0] = constant - unnormalized_derivatives[..., -1] = constant - - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 - else: - raise RuntimeError("{} tails are not implemented.".format(tails)) - - ( - outputs[inside_interval_mask], - logabsdet[inside_interval_mask], - ) = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :], - inverse=inverse, - left=-tail_bound, - right=tail_bound, - bottom=-tail_bound, - top=tail_bound, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - ) - - return outputs, logabsdet - - -def rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - left=0.0, - right=1.0, - bottom=0.0, - top=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if torch.min(inputs) < left or torch.max(inputs) > right: - raise ValueError("Input to a transform is not within its domain") - - num_bins = unnormalized_widths.shape[-1] - - if min_bin_width * num_bins > 1.0: - raise ValueError("Minimal bin width too large for the number of bins") - if min_bin_height * num_bins > 1.0: - raise ValueError("Minimal bin height too large for the number of bins") - - widths = F.softmax(unnormalized_widths, dim=-1) - widths = min_bin_width + (1 - min_bin_width * num_bins) * widths - cumwidths = torch.cumsum(widths, dim=-1) - cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0) - cumwidths = (right - left) * cumwidths + left - cumwidths[..., 0] = left - cumwidths[..., -1] = right - widths = cumwidths[..., 1:] - cumwidths[..., :-1] - - derivatives = min_derivative + F.softplus(unnormalized_derivatives) - - heights = F.softmax(unnormalized_heights, dim=-1) - heights = min_bin_height + (1 - min_bin_height * num_bins) * heights - cumheights = torch.cumsum(heights, dim=-1) - cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0) - cumheights = (top - bottom) * cumheights + bottom - cumheights[..., 0] = bottom - cumheights[..., -1] = top - heights = cumheights[..., 1:] - cumheights[..., :-1] - - if inverse: - bin_idx = searchsorted(cumheights, inputs)[..., None] - else: - bin_idx = searchsorted(cumwidths, inputs)[..., None] - - input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0] - input_bin_widths = widths.gather(-1, bin_idx)[..., 0] - - input_cumheights = cumheights.gather(-1, bin_idx)[..., 0] - delta = heights / widths - input_delta = delta.gather(-1, bin_idx)[..., 0] - - input_derivatives = derivatives.gather(-1, bin_idx)[..., 0] - input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0] - - input_heights = heights.gather(-1, bin_idx)[..., 0] - - if inverse: - a = (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) + input_heights * (input_delta - input_derivatives) - b = input_heights * input_derivatives - (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) - c = -input_delta * (inputs - input_cumheights) - - discriminant = b.pow(2) - 4 * a * c - assert (discriminant >= 0).all() - - root = (2 * c) / (-b - torch.sqrt(discriminant)) - outputs = root * input_bin_widths + input_cumwidths - - theta_one_minus_theta = root * (1 - root) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * root.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - root).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, -logabsdet - else: - theta = (inputs - input_cumwidths) / input_bin_widths - theta_one_minus_theta = theta * (1 - theta) - - numerator = input_heights * ( - input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta - ) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - outputs = input_cumheights + numerator / denominator - - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * theta.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - theta).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, logabsdet diff --git a/spaces/JohnSmith9982/ChuanhuChatGPT_Beta/web_assets/html/appearance_switcher.html b/spaces/JohnSmith9982/ChuanhuChatGPT_Beta/web_assets/html/appearance_switcher.html deleted file mode 100644 index 5fbf3b09b1c39de75c400514c9d0d81c807ea6bd..0000000000000000000000000000000000000000 --- a/spaces/JohnSmith9982/ChuanhuChatGPT_Beta/web_assets/html/appearance_switcher.html +++ /dev/null @@ -1,6 +0,0 @@ -
- -
diff --git a/spaces/Jung/ep_explorer/app.py b/spaces/Jung/ep_explorer/app.py deleted file mode 100644 index 4808a67c7d547ac55fb14034afda2f89bcdfe0df..0000000000000000000000000000000000000000 --- a/spaces/Jung/ep_explorer/app.py +++ /dev/null @@ -1,355 +0,0 @@ -import pandas as pd -import numpy as np -import streamlit as st - -# import glob -# import yaml -from pathlib import Path -from collections import defaultdict - -######################################### -# Helpers Functions - -display_cols = ['image','name', 'color', 'star', 'class', 'speed', 'power', 'attack', 'defense', 'health', 'types', 'source', 'family'] - -def filter_by_1col_num(df, col_name, query, oper_flag="eq"): - ok_flag_list = [] - assert col_name in df.columns, "col_name must be valid" - - for i, val in enumerate(df[col_name]): - if oper_flag == 'ge': - flag = True if val >= query else False - elif oper_flag == 'le': - flag = True if val <= query else False - else: # default = eq - flag = True if val == query else False - - ok_flag_list.append(flag) - - assert len(ok_flag_list) == len(df) - return np.array(ok_flag_list) - -def filter_by_1col(df, col_name, query, exact_flag=False): - - def check_valid_value(query, string, exact_flag=False): - if exact_flag: - if query.lower() == string.lower(): - return True - - elif query.lower() in string.lower(): - return True - - return False - - ok_flag_list = [] - assert col_name in df.columns, "col_name must be valid" - - for i, s in enumerate(df[col_name]): - - if isinstance(s, list): - for s2 in s: - flag = check_valid_value(query, s2, exact_flag=exact_flag) - if flag: break - else: - flag = check_valid_value(query, s, exact_flag=exact_flag) - - - ok_flag_list.append(flag) - - assert len(ok_flag_list) == len(df) - return np.array(ok_flag_list) - -def display_image(url, scale=0.5): - from urllib.request import urlopen - from PIL import Image - - image = Image.open(urlopen(url)) - st.image(image.resize(( int(image.width * scale), int(image.height * scale)))) - -def display_heroes_from_df(df,display_cols=display_cols, show_df=True): - vtob = "is" if len(df)<=1 else "are" - st.write(f'There {vtob} {len(df)} heroes in the filtered list') - - if show_df: - st.dataframe(df[display_cols], - column_config={ - "image": st.column_config.ImageColumn("Avatar", help="")}, - use_container_width=True, - hide_index=True) - - for i in range(len(df)): - url = df['image'].values[i] - display_image(url) - st.write(f"***{df['name'].values[i]}*** - {df['speed'].values[i]} - {df['class'].values[i]}") - st.write(f'Attack:{df["attack"].values[i]} -- Defence:{df["defense"].values[i]} -- Health:{df["health"].values[i]}') - st.write(f"***{df['skill'].values[i]}***" ) - st.write(df['effects'].values[i]) - # for sp in df['effects'].values[i]: - # st.write(sp) - -######################################### -## Helper function for LB/CB stat analysis -def return_costume_list(df0, hero_name): - assert hero_name in df0.name.values - - if hero_name[-2:] == "C3": - return ['None', 'CB1', 'CB2', 'CB3'] - if hero_name[-2:] == "C2": - hero_name2 = hero_name[:-1] + "3" - if hero_name2 in df0.name.values: # if this hero has C3 - return ['None', 'CB1', 'CB2', 'CB3'] - else: - return ['None', 'CB1', 'CB2'] - elif hero_name[-2:] == " C": - hero_name2 = hero_name + "2" - hero_name3 = hero_name + "3" - if hero_name3 in df0.name.values: # if this hero has C2 - return ['None', 'CB1', 'CB2', 'CB3'] - elif hero_name2 in df0.name.values: # if this hero has C2 - return ['None', 'CB1', 'CB2'] - else: - return ['None', 'CB1'] - else: - hero_name1 = hero_name + " C" - hero_name2 = hero_name + " C2" - hero_name3 = hero_name + " C3" - if hero_name3 in df0.name.values: # if this hero has C2 - return ['None', 'CB1', 'CB2', 'CB3'] - elif hero_name2 in df0.name.values: # if this hero has C2 - return ['None', 'CB1', 'CB2'] - elif hero_name1 in df0.name.values: # if this hero has C2 - return ['None', 'CB1'] - else: - return ['None'] - -def get_prefix(lb_choice="None", costume_choice="None"): - prefix_1 = "Max level" - - if lb_choice != 'None': - prefix_1 = "Limit Break" - - prefix_2 = "" - if costume_choice != "None": - prefix_2 = f" {costume_choice}" # CB1 or CB2 - - prefix_3 = ":" - if lb_choice == 'LB1': - prefix_3 = " #1:" - elif lb_choice == 'LB2': - prefix_3 = " #2:" - - return prefix_1 + prefix_2 + prefix_3 - -def return_hero_stat(df0, hero_name, lb_choice="None", costume_choice="None"): - assert hero_name in df0.name.values - - display_cols_0 = ['image', 'name', 'color', 'star', 'class', 'speed',] - display_cols_1 = [] # ['power', 'attack', 'defense', 'health', ] --> to be select base one LB/Costume choice - display_cols_2 = ['Aether Power', 'source', 'family', 'types', 'skill', 'effects'] - - prefix = get_prefix(lb_choice, costume_choice) - - display_cols_1.append(f'{prefix} Power') - display_cols_1.append(f'{prefix} Attack') - display_cols_1.append(f'{prefix} Defense') - display_cols_1.append(f'{prefix} Health') - - display_cols_all = display_cols_0 + display_cols_1 + display_cols_2 - df_ret = df0[df0.name == hero_name][display_cols_all] - - df_ret = df_ret.rename(columns={f'{prefix} Power':'power', - f'{prefix} Attack':'attack', - f'{prefix} Defense':'defense', - f'{prefix} Health':'health'}) - return df_ret - -######################################### -## Load the main file (TODO: caching)= -st.set_page_config(layout="wide") -st.header(f'HeroPlan Explorer') -st.write('Powered by Heroplan.io : Thanks E&P community for continually update hero data.') - -df = pd.read_csv('heroes_ep.csv') -st.write(f'### Updated: Nov 10, 2023 -- Total heroes in HeroPlan database = {len(df)} (including Toon Costume3)') - -df_extra = pd.read_csv("heroes_ep_extra.csv") -all_name_extra = sorted(list(df_extra['name'].values)) - -######################################### - -class_values = ['None'] + list(df['class'].unique()) -star_values = ['None'] + list(df['star'].unique()) -color_values = ['None'] + list(df['color'].unique()) -speed_values = ['None'] + list(df['speed'].unique()) -source_values = ['None'] + list(df['source'].unique()) # Contain lot of typo bugs from HeroPlan - -######################################### -## Select Main Program - -with st.sidebar: - genre = st.radio( - "Choose how to explore heroes", - [":rainbow[Heroes Explorer]", "Team Simulation","***LB/CB Hero Stat*** :movie_camera:"], - captions = ["Filter only heroes with certain properties", "Co-powered by Elioty33's DataVault"]) - -######################################### -## Program 1 -if genre == ':rainbow[Heroes Explorer]': - - col1, col2, col3 = st.columns(3) - with col1: - st.header("Standard Filters:") - st.write("Tips: filter costume by typing ' C' 'C2' or 'C3' in the Name box.") - with st.expander("Filter Options"): - name_option = st.text_input(label="Name:", value="") - star_option = st.selectbox(label='Star:', options=star_values, index=0) - color_option = st.selectbox(label='Color:', options=color_values, index=0) - speed_option = st.selectbox(label='Speed:', options=speed_values, index=0) - class_option = st.selectbox(label='Class:', options=class_values, index=0) - source_option = st.selectbox(label='Origin:', options=source_values, index=0) - - special_type_option = st.text_input(label="SpecialSkill Category", value="Hit 3") - special_text_option = st.text_input(label="SpecialSkill Text", value="Dispel") - with col2: - st.header("Stat Filters") - st.write("Tips: put the **minimum** att/def/hp stat you want to filter heroes") - with st.expander("Stat Options"): - power_option = st.text_input(label="Power:", value="0") - defense_option = st.text_input(label="Defense:", value="0") - attack_option = st.text_input(label="Attack:", value="0") - health_option = st.text_input(label="Health:", value="0") - - total_dot_option = st.text_input(label="Total DoT Damage:", value="0") - dot_per_turn_option = st.text_input(label="DoT Damage Per Turn:", value="0") - with col3: - st.header("Sorted By") - st.write("Tips: you can also directly click at the column name to sort") - sort_option = st.selectbox(label='Sort by', options=display_cols[1:], index=5) # default is power - - idx_all = [] - - if name_option != '': - idx_all.append(filter_by_1col(df, 'name', name_option, exact_flag=False)) - - if star_option != 'None': - idx_all.append(filter_by_1col_num(df, 'star', star_option, oper_flag="eq")) - - if speed_option != 'None': - idx_all.append(filter_by_1col(df, 'speed', speed_option, exact_flag=True)) - - if color_option != 'None': - idx_all.append(filter_by_1col(df, 'color', color_option, exact_flag=False)) - - if class_option != 'None': - idx_all.append(filter_by_1col(df, 'class', class_option, exact_flag=False)) - - if source_option != 'None': - idx_all.append(filter_by_1col(df, 'source', source_option, exact_flag=False)) - - if power_option != "0": - power_option = int(power_option) - idx_all.append(filter_by_1col_num(df, 'power', power_option, oper_flag="ge")) - - if defense_option != "0": - defense_option = int(defense_option) - idx_all.append(filter_by_1col_num(df, 'defense', defense_option, oper_flag="ge")) - - if attack_option != "0": - attack_option = int(attack_option) - idx_all.append(filter_by_1col_num(df, 'attack', attack_option, oper_flag="ge")) - - if health_option != "0": - health_option = int(health_option) - idx_all.append(filter_by_1col_num(df, 'health', health_option, oper_flag="ge")) - - if total_dot_option != "0": - total_dot_option = int(total_dot_option) - idx_all.append(filter_by_1col_num(df, 'total_dot_damage', total_dot_option, oper_flag="ge")) - - if dot_per_turn_option != "0": - dot_per_turn_option = int(dot_per_turn_option) - idx_all.append(filter_by_1col_num(df, 'dot_damage_per_turn', dot_per_turn_option, oper_flag="ge")) - - if special_type_option != '': - idx_all.append(filter_by_1col(df, 'types', special_type_option, exact_flag=False)) - - if special_text_option != '': - idx_all.append(filter_by_1col(df, 'effects', special_text_option, exact_flag=False)) - - ######################################### - - df2 = df[np.all(idx_all,axis=0)] - - display_heroes_from_df(df2.sort_values(sort_option, ascending=False)) -######################################### -## Program 2 "Team Simulation" -elif genre == "Team Simulation": - - def choose_hero(key="Hero1"): - name_choice = st.selectbox(label='Hero Name:', options=all_name_extra, index=0, key=key+"_name") - costume_list = return_costume_list(df_extra, name_choice) - costume_choice = st.selectbox(label='Costume:', options=costume_list, index=0, key=key+"_costume") - lb_list = ['None', 'LB1', 'LB2'] - lb_choice = st.selectbox(label='Limit Break:', options=lb_list, index=0, key=key+"_lb") - - df_ret = return_hero_stat(df_extra, name_choice, lb_choice=lb_choice, costume_choice=costume_choice) - return df_ret - - def write_short_description(df_hero): - url = df_hero['image'].values[0] - display_image(url) - st.write(f'Power: {df_hero["power"].values[0]}') - st.write(f'Attack: {df_hero["attack"].values[0]}') - st.write(f'Defense: {df_hero["defense"].values[0]}') - st.write(f'Health: {df_hero["health"].values[0]}') - st.write(f'Speed: {df_hero["speed"].values[0]}') - st.write(f'Class: {df_hero["class"].values[0]}') - st.write(f'Types: {df_hero["types"].values[0]}') - - nheroes_choice_list = [2,3,4,5] - nheroes_choice = st.selectbox(label='Number of Heroes:', options=nheroes_choice_list, index=len(nheroes_choice_list)-1) - - col_list = st.columns(nheroes_choice+1) - df_hero_list = [] - total_power = 0 - for ii in range(nheroes_choice): - with col_list[ii]: - df_hero_list.append(choose_hero(key=f"Hero{ii+1}")) # 'key' in st.selectbox to differentiate widgets - write_short_description(df_hero_list[-1]) - total_power += df_hero_list[ii]['power'].values[0] - - with col_list[-1]: - txt = st.text_area("Write your note about team synergy", max_chars=1000, height = 480) - - df_hero_all5 = pd.concat(df_hero_list) - - st.write(f'======================') - st.write(f'### Total power = {total_power}') - st.write(f'======================') - - display_heroes_from_df(df_hero_all5, display_cols=df_hero_all5.columns[:-2], show_df=False) # display all except special-skill text - -######################################### -## Program 3 "Individual Stat" -else: - - - st.header("Analyze Hero LB/CB Stat (without Emblem)") - st.write("HeroPlan and DataVault are combined here. Thanks ***@Elioty33*** for his DataVault contribution") - st.write(f"Currently, there are {len(df_extra)} heroes having both data on HeroPlan and DataVault.") - st.write(f"We don't have emblem calculator here, you can go heroplan.io to do the job.") - st.write(f"***Heuristically*** Choose Sword-path can increase att 100-150, def 50-100, hp ~100 (reverse att-def for shield path)") - st.write(f"Choose HP-path can increase att 50-100, def 50-100, hp ~200") - - - name_values = sorted(list(df_extra['name'].values)) - name_choice = st.selectbox(label='Hero Name:', options=name_values, index=0) - - costume_list = return_costume_list(df_extra, name_choice) - costume_choice = st.selectbox(label='Costume:', options=costume_list, index=0) - - lb_list = ['None', 'LB1', 'LB2'] - lb_choice = st.selectbox(label='Limit Break:', options=lb_list, index=0) - - df_ret = return_hero_stat(df_extra, name_choice, lb_choice=lb_choice, costume_choice=costume_choice) - display_heroes_from_df(df_ret,display_cols=df_ret.columns[:-2]) # display all except special-skill text \ No newline at end of file diff --git a/spaces/Junity/TokaiTeio-SVC/inference/infer_tool_grad.py b/spaces/Junity/TokaiTeio-SVC/inference/infer_tool_grad.py deleted file mode 100644 index b75af49c08e2e724839828bc419792ed580809bb..0000000000000000000000000000000000000000 --- a/spaces/Junity/TokaiTeio-SVC/inference/infer_tool_grad.py +++ /dev/null @@ -1,160 +0,0 @@ -import hashlib -import json -import logging -import os -import time -from pathlib import Path -import io -import librosa -import maad -import numpy as np -from inference import slicer -import parselmouth -import soundfile -import torch -import torchaudio - -from hubert import hubert_model -import utils -from models import SynthesizerTrn -logging.getLogger('numba').setLevel(logging.WARNING) -logging.getLogger('matplotlib').setLevel(logging.WARNING) - -def resize2d_f0(x, target_len): - source = np.array(x) - source[source < 0.001] = np.nan - target = np.interp(np.arange(0, len(source) * target_len, len(source)) / target_len, np.arange(0, len(source)), - source) - res = np.nan_to_num(target) - return res - -def get_f0(x, p_len,f0_up_key=0): - - time_step = 160 / 16000 * 1000 - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - - f0 = parselmouth.Sound(x, 16000).to_pitch_ac( - time_step=time_step / 1000, voicing_threshold=0.6, - pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency'] - - pad_size=(p_len - len(f0) + 1) // 2 - if(pad_size>0 or p_len - len(f0) - pad_size>0): - f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant') - - f0 *= pow(2, f0_up_key / 12) - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (f0_mel_max - f0_mel_min) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - f0_coarse = np.rint(f0_mel).astype(np.int) - return f0_coarse, f0 - -def clean_pitch(input_pitch): - num_nan = np.sum(input_pitch == 1) - if num_nan / len(input_pitch) > 0.9: - input_pitch[input_pitch != 1] = 1 - return input_pitch - - -def plt_pitch(input_pitch): - input_pitch = input_pitch.astype(float) - input_pitch[input_pitch == 1] = np.nan - return input_pitch - - -def f0_to_pitch(ff): - f0_pitch = 69 + 12 * np.log2(ff / 440) - return f0_pitch - - -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) - - -class VitsSvc(object): - def __init__(self): - self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - self.SVCVITS = None - self.hps = None - self.speakers = None - self.hubert_soft = utils.get_hubert_model() - - def set_device(self, device): - self.device = torch.device(device) - self.hubert_soft.to(self.device) - if self.SVCVITS != None: - self.SVCVITS.to(self.device) - - def loadCheckpoint(self, path): - self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json") - self.SVCVITS = SynthesizerTrn( - self.hps.data.filter_length // 2 + 1, - self.hps.train.segment_size // self.hps.data.hop_length, - **self.hps.model) - _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", self.SVCVITS, None) - _ = self.SVCVITS.eval().to(self.device) - self.speakers = self.hps.spk - - def get_units(self, source, sr): - source = source.unsqueeze(0).to(self.device) - with torch.inference_mode(): - units = self.hubert_soft.units(source) - return units - - - def get_unit_pitch(self, in_path, tran): - source, sr = torchaudio.load(in_path) - source = torchaudio.functional.resample(source, sr, 16000) - if len(source.shape) == 2 and source.shape[1] >= 2: - source = torch.mean(source, dim=0).unsqueeze(0) - soft = self.get_units(source, sr).squeeze(0).cpu().numpy() - f0_coarse, f0 = get_f0(source.cpu().numpy()[0], soft.shape[0]*2, tran) - return soft, f0 - - def infer(self, speaker_id, tran, raw_path): - speaker_id = self.speakers[speaker_id] - sid = torch.LongTensor([int(speaker_id)]).to(self.device).unsqueeze(0) - soft, pitch = self.get_unit_pitch(raw_path, tran) - f0 = torch.FloatTensor(clean_pitch(pitch)).unsqueeze(0).to(self.device) - stn_tst = torch.FloatTensor(soft) - with torch.no_grad(): - x_tst = stn_tst.unsqueeze(0).to(self.device) - x_tst = torch.repeat_interleave(x_tst, repeats=2, dim=1).transpose(1, 2) - audio = self.SVCVITS.infer(x_tst, f0=f0, g=sid)[0,0].data.float() - return audio, audio.shape[-1] - - def inference(self,srcaudio,chara,tran,slice_db): - sampling_rate, audio = srcaudio - audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32) - if len(audio.shape) > 1: - audio = librosa.to_mono(audio.transpose(1, 0)) - if sampling_rate != 16000: - audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) - soundfile.write("tmpwav.wav", audio, 16000, format="wav") - chunks = slicer.cut("tmpwav.wav", db_thresh=slice_db) - audio_data, audio_sr = slicer.chunks2audio("tmpwav.wav", chunks) - audio = [] - for (slice_tag, data) in audio_data: - length = int(np.ceil(len(data) / audio_sr * self.hps.data.sampling_rate)) - raw_path = io.BytesIO() - soundfile.write(raw_path, data, audio_sr, format="wav") - raw_path.seek(0) - if slice_tag: - _audio = np.zeros(length) - else: - out_audio, out_sr = self.infer(chara, tran, raw_path) - _audio = out_audio.cpu().numpy() - audio.extend(list(_audio)) - audio = (np.array(audio) * 32768.0).astype('int16') - return (self.hps.data.sampling_rate,audio) diff --git a/spaces/JustinLin610/ImageBind_zeroshot_demo/models/__init__.py b/spaces/JustinLin610/ImageBind_zeroshot_demo/models/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Kalvin-5/WizardLM-WizardCoder-15B-V1.0/app.py b/spaces/Kalvin-5/WizardLM-WizardCoder-15B-V1.0/app.py deleted file mode 100644 index b950a0dc3c9037b8db001411736515bf668d4f57..0000000000000000000000000000000000000000 --- a/spaces/Kalvin-5/WizardLM-WizardCoder-15B-V1.0/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/WizardLM/WizardCoder-15B-V1.0").launch() \ No newline at end of file diff --git a/spaces/KaygNas/cut-it/src/vite-env.d.ts b/spaces/KaygNas/cut-it/src/vite-env.d.ts deleted file mode 100644 index 650e41fc573c6f3686f1bbea9a6e4912873da35f..0000000000000000000000000000000000000000 --- a/spaces/KaygNas/cut-it/src/vite-env.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// -/// -interface ImportMetaEnv { - readonly VITE_API_BASE_URL: string - readonly VITE_MOCK: boolean - readonly VITE_MODEL_ASSETS_ROOT_URL: string -} - -interface ImportMeta { - readonly env: ImportMetaEnv -} \ No newline at end of file diff --git a/spaces/KonradSzafer/HF-QA-Demo/Dockerfile b/spaces/KonradSzafer/HF-QA-Demo/Dockerfile deleted file mode 100644 index 0403c918cc1db8668a4b73e2000b104e50418f34..0000000000000000000000000000000000000000 --- a/spaces/KonradSzafer/HF-QA-Demo/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -FROM debian:bullseye-slim - -ENV DEBIAN_FRONTEND=noninteractive - -RUN apt-get -y update && \ - apt-get -y upgrade && \ - apt-get -y install git python3.11 python3-pip - -COPY requirements.txt . -RUN pip install --upgrade pip && \ - pip install --no-cache-dir -r requirements.txt - -WORKDIR /hugging-face-qa-bot -COPY . . - -RUN ls -la -EXPOSE 8000 - -ENTRYPOINT [ "python3", "-m", "api" ] # to run the api module -# ENTRYPOINT [ "python3", "-m", "discord_bot" ] # to host the bot diff --git a/spaces/KyanChen/BuildingExtraction/README.md b/spaces/KyanChen/BuildingExtraction/README.md deleted file mode 100644 index fcb7b8d04a3f6474487d74be574b7fc37b27099e..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/BuildingExtraction/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: BuildingExtraction -emoji: 🚀 -colorFrom: blue -colorTo: green -sdk: gradio -sdk_version: 3.0.20 -app_file: App_main.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/LanguageBind/LanguageBind/languagebind/thermal/modeling_thermal.py b/spaces/LanguageBind/LanguageBind/languagebind/thermal/modeling_thermal.py deleted file mode 100644 index f0323b3351a4eed0165a8b7a1e8cc610ea0669ca..0000000000000000000000000000000000000000 --- a/spaces/LanguageBind/LanguageBind/languagebind/thermal/modeling_thermal.py +++ /dev/null @@ -1,1030 +0,0 @@ -import math -from typing import Optional, Tuple, Union - -import torch -from einops import rearrange -from peft import LoraConfig, get_peft_model -from torch import nn -from torch.nn import functional as F -from transformers import PreTrainedModel, add_start_docstrings -from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling -from transformers.models.clip.modeling_clip import CLIPMLP, CLIPAttention, CLIPTextEmbeddings, CLIPVisionEmbeddings, \ - CLIPVisionModelWithProjection, CLIPTextModelWithProjection, _expand_mask, CLIPOutput, clip_loss -from transformers.utils import add_start_docstrings_to_model_forward, replace_return_docstrings - -from .configuration_thermal import LanguageBindThermalConfig, CLIPVisionConfig, CLIPTextConfig - - - -class PatchDropout(nn.Module): - """ - https://arxiv.org/abs/2212.00794 - """ - - def __init__(self, prob, exclude_first_token=True): - super().__init__() - assert 0 <= prob < 1. - self.prob = prob - self.exclude_first_token = exclude_first_token # exclude CLS token - - def forward(self, x, B, T): - if not self.training or self.prob == 0.: - return x - - if self.exclude_first_token: - cls_tokens, x = x[:, :1], x[:, 1:] - else: - cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1]) - - batch = x.size()[0] - num_tokens = x.size()[1] - - batch_indices = torch.arange(batch) - batch_indices = batch_indices[..., None] - - keep_prob = 1 - self.prob - num_patches_keep = max(1, int(num_tokens * keep_prob)) - - if T == 1: - rand = torch.randn(batch, num_tokens) - patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices - else: - rand = torch.randn(B, num_tokens) - patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices - patch_indices_keep = patch_indices_keep.unsqueeze(1).repeat(1, T, 1) - patch_indices_keep = rearrange(patch_indices_keep, 'b t n -> (b t) n') - - - x = x[batch_indices, patch_indices_keep] - - if self.exclude_first_token: - x = torch.cat((cls_tokens, x), dim=1) - - return x - -class CLIPEncoderLayer(nn.Module): - def __init__(self, config: LanguageBindThermalConfig): - super().__init__() - self.embed_dim = config.hidden_size - self.self_attn = CLIPAttention(config) - self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) - self.mlp = CLIPMLP(config) - self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) - - self.add_time_attn = config.add_time_attn - if self.add_time_attn: - self.t = config.num_frames - self.temporal_embedding = nn.Parameter(torch.zeros(1, config.num_frames, config.hidden_size)) - nn.init.normal_(self.temporal_embedding, std=config.hidden_size ** -0.5) - - self.embed_dim = config.hidden_size - self.temporal_attn = CLIPAttention(config) - self.temporal_layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) - self.temporal_mlp = CLIPMLP(config) - self.temporal_layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) - - def forward( - self, - hidden_states: torch.Tensor, - attention_mask: torch.Tensor, - causal_attention_mask: torch.Tensor, - output_attentions: Optional[bool] = False, - ) -> Tuple[torch.FloatTensor]: - """ - Args: - hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` - attention_mask (`torch.FloatTensor`): attention mask of size - `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. - `(config.encoder_attention_heads,)`. - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under - returned tensors for more detail. - """ - - - if self.add_time_attn: - bt, n, d = hidden_states.shape - t = self.t - - # time embed - if t != 1: - n = hidden_states.shape[1] - hidden_states = rearrange(hidden_states, '(b t) n d -> (b n) t d', t=t) - hidden_states = hidden_states + self.temporal_embedding[:, :t, :] - hidden_states = rearrange(hidden_states, '(b n) t d -> (b t) n d', n=n) - - # time attn - residual = hidden_states - hidden_states = rearrange(hidden_states, '(b t) n d -> (b n) t d', t=t) - # hidden_states = self.layer_norm1(hidden_states) # share layernorm - hidden_states = self.temporal_layer_norm1(hidden_states) - hidden_states, attn_weights = self.temporal_attn( - hidden_states=hidden_states, - attention_mask=attention_mask, - causal_attention_mask=causal_attention_mask, - output_attentions=output_attentions, - ) - hidden_states = residual + rearrange(hidden_states, '(b n) t d -> (b t) n d', n=n) - - residual = hidden_states - hidden_states = rearrange(hidden_states, '(b t) n d -> (b n) t d', t=t) - # hidden_states = self.layer_norm2(hidden_states) # share layernorm - hidden_states = self.temporal_layer_norm2(hidden_states) - hidden_states = self.temporal_mlp(hidden_states) - hidden_states = residual + rearrange(hidden_states, '(b n) t d -> (b t) n d', n=n) - - # spatial attn - residual = hidden_states - - hidden_states = self.layer_norm1(hidden_states) - hidden_states, attn_weights = self.self_attn( - hidden_states=hidden_states, - attention_mask=attention_mask, - causal_attention_mask=causal_attention_mask, - output_attentions=output_attentions, - ) - hidden_states = residual + hidden_states - - residual = hidden_states - hidden_states = self.layer_norm2(hidden_states) - hidden_states = self.mlp(hidden_states) - hidden_states = residual + hidden_states - - outputs = (hidden_states,) - - if output_attentions: - outputs += (attn_weights,) - - return outputs - - - - - - - - - -class CLIPPreTrainedModel(PreTrainedModel): - """ - An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained - models. - """ - - config_class = LanguageBindThermalConfig - base_model_prefix = "clip" - supports_gradient_checkpointing = True - _keys_to_ignore_on_load_missing = [r"position_ids"] - - def _init_weights(self, module): - """Initialize the weights""" - factor = self.config.initializer_factor - if isinstance(module, CLIPTextEmbeddings): - module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02) - module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02) - elif isinstance(module, CLIPVisionEmbeddings): - factor = self.config.initializer_factor - nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor) - nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor) - nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor) - elif isinstance(module, CLIPAttention): - factor = self.config.initializer_factor - in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor - out_proj_std = (module.embed_dim**-0.5) * factor - nn.init.normal_(module.q_proj.weight, std=in_proj_std) - nn.init.normal_(module.k_proj.weight, std=in_proj_std) - nn.init.normal_(module.v_proj.weight, std=in_proj_std) - nn.init.normal_(module.out_proj.weight, std=out_proj_std) - elif isinstance(module, CLIPMLP): - factor = self.config.initializer_factor - in_proj_std = ( - (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor - ) - fc_std = (2 * module.config.hidden_size) ** -0.5 * factor - nn.init.normal_(module.fc1.weight, std=fc_std) - nn.init.normal_(module.fc2.weight, std=in_proj_std) - elif isinstance(module, LanguageBindThermal): - nn.init.normal_( - module.text_projection.weight, - std=module.text_embed_dim**-0.5 * self.config.initializer_factor, - ) - nn.init.normal_( - module.visual_projection.weight, - std=module.vision_embed_dim**-0.5 * self.config.initializer_factor, - ) - elif isinstance(module, CLIPVisionModelWithProjection): - nn.init.normal_( - module.visual_projection.weight, - std=self.config.hidden_size**-0.5 * self.config.initializer_factor, - ) - elif isinstance(module, CLIPTextModelWithProjection): - nn.init.normal_( - module.text_projection.weight, - std=self.config.hidden_size**-0.5 * self.config.initializer_factor, - ) - - if isinstance(module, nn.LayerNorm): - module.bias.data.zero_() - module.weight.data.fill_(1.0) - if isinstance(module, nn.Linear) and module.bias is not None: - module.bias.data.zero_() - - def _set_gradient_checkpointing(self, module, value=False): - if isinstance(module, CLIPEncoder): - module.gradient_checkpointing = value - - -CLIP_START_DOCSTRING = r""" - This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the - library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads - etc.) - - This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. - Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage - and behavior. - - Parameters: - config ([`CLIPConfig`]): Model configuration class with all the parameters of the model. - Initializing with a config file does not load the weights associated with the model, only the - configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. -""" - -CLIP_TEXT_INPUTS_DOCSTRING = r""" - Args: - input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): - Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide - it. - - Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and - [`PreTrainedTokenizer.__call__`] for details. - - [What are input IDs?](../glossary#input-ids) - attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): - Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): - Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, - config.max_position_embeddings - 1]`. - - [What are position IDs?](../glossary#position-ids) - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned - tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for - more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. -""" - -CLIP_VISION_INPUTS_DOCSTRING = r""" - Args: - pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): - Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using - [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details. - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned - tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for - more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. -""" - -CLIP_INPUTS_DOCSTRING = r""" - Args: - input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): - Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide - it. - - Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and - [`PreTrainedTokenizer.__call__`] for details. - - [What are input IDs?](../glossary#input-ids) - attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): - Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): - Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, - config.max_position_embeddings - 1]`. - - [What are position IDs?](../glossary#position-ids) - pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): - Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using - [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details. - return_loss (`bool`, *optional*): - Whether or not to return the contrastive loss. - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned - tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for - more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. -""" - - -class CLIPEncoder(nn.Module): - """ - Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a - [`CLIPEncoderLayer`]. - - Args: - config: CLIPConfig - """ - - def __init__(self, config: LanguageBindThermalConfig): - super().__init__() - self.config = config - self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)]) - self.gradient_checkpointing = False - - def forward( - self, - inputs_embeds, - attention_mask: Optional[torch.Tensor] = None, - causal_attention_mask: Optional[torch.Tensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutput]: - r""" - Args: - inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): - Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. - This is useful if you want more control over how to convert `input_ids` indices into associated vectors - than the model's internal embedding lookup matrix. - attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): - Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): - Causal mask for the text model. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under - returned tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors - for more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. - """ - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - encoder_states = () if output_hidden_states else None - all_attentions = () if output_attentions else None - - hidden_states = inputs_embeds - for idx, encoder_layer in enumerate(self.layers): - if output_hidden_states: - encoder_states = encoder_states + (hidden_states,) - if self.gradient_checkpointing and self.training: - - def create_custom_forward(module): - def custom_forward(*inputs): - return module(*inputs, output_attentions) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(encoder_layer), - hidden_states, - attention_mask, - causal_attention_mask, - ) - else: - layer_outputs = encoder_layer( - hidden_states, - attention_mask, - causal_attention_mask, - output_attentions=output_attentions, - ) - - hidden_states = layer_outputs[0] - - if output_attentions: - all_attentions = all_attentions + (layer_outputs[1],) - - if output_hidden_states: - encoder_states = encoder_states + (hidden_states,) - - if not return_dict: - return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) - return BaseModelOutput( - last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions - ) - - -# Copied from transformers.models.bart.modeling_bart._make_causal_mask -def _make_causal_mask( - input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 -): - """ - Make causal mask used for bi-directional self-attention. - """ - bsz, tgt_len = input_ids_shape - mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) - mask_cond = torch.arange(mask.size(-1), device=device) - mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) - mask = mask.to(dtype) - - if past_key_values_length > 0: - mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) - return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) - - -class CLIPTextTransformer(nn.Module): - def __init__(self, config: CLIPTextConfig): - super().__init__() - self.config = config - embed_dim = config.hidden_size - self.embeddings = CLIPTextEmbeddings(config) - self.encoder = CLIPEncoder(config) - self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) - - @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING) - @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig) - def forward( - self, - input_ids: Optional[torch.Tensor] = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.Tensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutputWithPooling]: - r""" - Returns: - - """ - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - if input_ids is None: - raise ValueError("You have to specify input_ids") - - input_shape = input_ids.size() - input_ids = input_ids.view(-1, input_shape[-1]) - - hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids) - - # CLIP's text model uses causal mask, prepare it here. - # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324 - causal_attention_mask = _make_causal_mask(input_shape, hidden_states.dtype, device=hidden_states.device) - # expand attention_mask - if attention_mask is not None: - # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] - attention_mask = _expand_mask(attention_mask, hidden_states.dtype) - - encoder_outputs = self.encoder( - inputs_embeds=hidden_states, - attention_mask=attention_mask, - causal_attention_mask=causal_attention_mask, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - last_hidden_state = encoder_outputs[0] - last_hidden_state = self.final_layer_norm(last_hidden_state) - - # text_embeds.shape = [batch_size, sequence_length, transformer.width] - # take features from the eot embedding (eot_token is the highest number in each sequence) - # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14 - pooled_output = last_hidden_state[ - torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device), - input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1), - ] - - if not return_dict: - return (last_hidden_state, pooled_output) + encoder_outputs[1:] - - return BaseModelOutputWithPooling( - last_hidden_state=last_hidden_state, - pooler_output=pooled_output, - hidden_states=encoder_outputs.hidden_states, - attentions=encoder_outputs.attentions, - ) - - -@add_start_docstrings( - """The text model from CLIP without any head or projection on top.""", - CLIP_START_DOCSTRING, -) -class CLIPTextModel(CLIPPreTrainedModel): - config_class = CLIPTextConfig - - _no_split_modules = ["CLIPEncoderLayer"] - - def __init__(self, config: CLIPTextConfig): - super().__init__(config) - self.text_model = CLIPTextTransformer(config) - # Initialize weights and apply final processing - self.post_init() - - def get_input_embeddings(self) -> nn.Module: - return self.text_model.embeddings.token_embedding - - def set_input_embeddings(self, value): - self.text_model.embeddings.token_embedding = value - - @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING) - @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig) - def forward( - self, - input_ids: Optional[torch.Tensor] = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.Tensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutputWithPooling]: - r""" - Returns: - - Examples: - - ```python - >>> from transformers import AutoTokenizer, CLIPTextModel - - >>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32") - >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32") - - >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") - - >>> outputs = model(**inputs) - >>> last_hidden_state = outputs.last_hidden_state - >>> pooled_output = outputs.pooler_output # pooled (EOS token) states - ```""" - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - return self.text_model( - input_ids=input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - -class CLIPVisionTransformer(nn.Module): - def __init__(self, config: CLIPVisionConfig): - super().__init__() - self.config = config - embed_dim = config.hidden_size - - self.embeddings = CLIPVisionEmbeddings(config) - self.patch_dropout = PatchDropout(config.force_patch_dropout) - self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) - self.encoder = CLIPEncoder(config) - self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) - - @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING) - @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig) - def forward( - self, - pixel_values: Optional[torch.FloatTensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutputWithPooling]: - r""" - Returns: - - """ - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - if pixel_values is None: - raise ValueError("You have to specify pixel_values") - ###################################### - if len(pixel_values.shape) == 7: - b_new, pair_new, T, bs_new, channel_new, h_new, w_new = pixel_values.shape - # print(pixel_values.shape) - B = b_new * pair_new * bs_new - pixel_values = pixel_values.reshape(B*T, channel_new, h_new, w_new) - - elif len(pixel_values.shape) == 5: - B, _, T, _, _ = pixel_values.shape - # print(pixel_values.shape) - pixel_values = rearrange(pixel_values, 'b c t h w -> (b t) c h w') - else: - # print(pixel_values.shape) - B, _, _, _ = pixel_values.shape - T = 1 - ########################### - hidden_states = self.embeddings(pixel_values) - - hidden_states = self.patch_dropout(hidden_states, B, T) ############################################## - - hidden_states = self.pre_layrnorm(hidden_states) - - encoder_outputs = self.encoder( - inputs_embeds=hidden_states, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - last_hidden_state = encoder_outputs[0] - pooled_output = last_hidden_state[:, 0, :] - pooled_output = self.post_layernorm(pooled_output) - - pooled_output = pooled_output.reshape(B, T, -1).mean(1) ################################ - - if not return_dict: - return (last_hidden_state, pooled_output) + encoder_outputs[1:] - - return BaseModelOutputWithPooling( - last_hidden_state=last_hidden_state, - pooler_output=pooled_output, - hidden_states=encoder_outputs.hidden_states, - attentions=encoder_outputs.attentions, - ) - - -@add_start_docstrings( - """The vision model from CLIP without any head or projection on top.""", - CLIP_START_DOCSTRING, -) -class CLIPVisionModel(CLIPPreTrainedModel): - config_class = CLIPVisionConfig - main_input_name = "pixel_values" - - def __init__(self, config: CLIPVisionConfig): - super().__init__(config) - self.vision_model = CLIPVisionTransformer(config) - # Initialize weights and apply final processing - self.post_init() - - def get_input_embeddings(self) -> nn.Module: - return self.vision_model.embeddings.patch_embedding - - @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING) - @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig) - def forward( - self, - pixel_values: Optional[torch.FloatTensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutputWithPooling]: - r""" - Returns: - - Examples: - - ```python - >>> from PIL import Image - >>> import requests - >>> from transformers import AutoProcessor, CLIPVisionModel - - >>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32") - >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") - - >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" - >>> image = Image.open(requests.get(url, stream=True).raw) - - >>> inputs = processor(images=image, return_tensors="pt") - - >>> outputs = model(**inputs) - >>> last_hidden_state = outputs.last_hidden_state - >>> pooled_output = outputs.pooler_output # pooled CLS states - ```""" - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - return self.vision_model( - pixel_values=pixel_values, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - -@add_start_docstrings(CLIP_START_DOCSTRING) -class LanguageBindThermal(CLIPPreTrainedModel): - config_class = LanguageBindThermalConfig - - def __init__(self, config: LanguageBindThermalConfig): - super().__init__(config) - - if not isinstance(config.text_config, CLIPTextConfig): - raise ValueError( - "config.text_config is expected to be of type CLIPTextConfig but is of type" - f" {type(config.text_config)}." - ) - - if not isinstance(config.vision_config, CLIPVisionConfig): - raise ValueError( - "config.vision_config is expected to be of type CLIPVisionConfig but is of type" - f" {type(config.vision_config)}." - ) - - text_config = config.text_config - vision_config = config.vision_config - self.add_time_attn = vision_config.add_time_attn - self.lora_r = vision_config.lora_r - self.lora_alpha = vision_config.lora_alpha - self.lora_dropout = vision_config.lora_dropout - - self.projection_dim = config.projection_dim - self.text_embed_dim = text_config.hidden_size - self.vision_embed_dim = vision_config.hidden_size - - self.text_model = CLIPTextTransformer(text_config) - self.vision_model = CLIPVisionTransformer(vision_config) - - self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False) - self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False) - self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value)) - - # Initialize weights and apply final processing - self.post_init() - self.convert_to_lora() - self.resize_pos(self.vision_model.embeddings, vision_config) - - def convert_to_lora(self): - if self.lora_r == 0: - return - if self.add_time_attn: - target_modules = ["temporal_attn.k_proj", "temporal_attn.v_proj", - "temporal_attn.q_proj", "temporal_attn.out_proj", - "temporal_mlp.fc1", "temporal_mlp.fc2"] - else: - target_modules = ["k_proj", "v_proj", "q_proj", "out_proj"] - config = LoraConfig( - r=self.lora_r, # 16 - lora_alpha=self.lora_alpha, # 16 - target_modules=target_modules, # self_attn.out_proj - lora_dropout=self.lora_dropout, # 0.1 - bias="none", - modules_to_save=[], - ) - self.vision_model.encoder.is_gradient_checkpointing = False - self.vision_model.encoder = get_peft_model(self.vision_model.encoder, config) - - def resize_pos(self, m, vision_config): - # convert embedding - if vision_config.num_mel_bins!=0 and vision_config.target_length!=0: - m.image_size = [vision_config.num_mel_bins, vision_config.target_length] - m.config.image_size = [m.image_size, m.image_size] if isinstance(m.image_size, int) else m.image_size - # pos resize - old_pos_embed_state_dict = m.position_embedding.state_dict() - old_pos_embed = old_pos_embed_state_dict['weight'] - dtype = old_pos_embed.dtype - grid_size = [m.config.image_size[0] // m.patch_size, m.config.image_size[1] // m.patch_size] - extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more) - new_seq_len = grid_size[0] * grid_size[1] + extra_tokens - if new_seq_len == old_pos_embed.shape[0]: - # m.to(args.device) - return - - m.num_patches = grid_size[0] * grid_size[1] - m.num_positions = m.num_patches + 1 - m.register_buffer("position_ids", torch.arange(m.num_positions).expand((1, -1))) - new_position_embedding = nn.Embedding(m.num_positions, m.embed_dim) - - if extra_tokens: - pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:] - else: - pos_emb_tok, pos_emb_img = None, old_pos_embed - old_grid_size = [int(math.sqrt(len(pos_emb_img)))] * 2 - - # if is_master(args): - # logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size) - pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) - pos_emb_img = F.interpolate( - pos_emb_img, - size=grid_size, - mode='bicubic', - antialias=True, - align_corners=False, - ) - pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0] - if pos_emb_tok is not None: - new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) - else: - new_pos_embed = pos_emb_img - old_pos_embed_state_dict['weight'] = new_pos_embed.to(dtype) - m.position_embedding = new_position_embedding - m.position_embedding.load_state_dict(old_pos_embed_state_dict) - - # m.to(args.device) - - @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING) - def get_text_features( - self, - input_ids: Optional[torch.Tensor] = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.Tensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> torch.FloatTensor: - r""" - Returns: - text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by - applying the projection layer to the pooled output of [`CLIPTextModel`]. - - Examples: - - ```python - >>> from transformers import AutoTokenizer, CLIPModel - - >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") - >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32") - - >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") - >>> text_features = model.get_text_features(**inputs) - ```""" - # Use CLIP model's config for some fields (if specified) instead of those of vision & text components. - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - text_outputs = self.text_model( - input_ids=input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - pooled_output = text_outputs[1] - text_features = self.text_projection(pooled_output) - - return text_features - - @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING) - def get_image_features( - self, - pixel_values: Optional[torch.FloatTensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> torch.FloatTensor: - r""" - Returns: - image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by - applying the projection layer to the pooled output of [`CLIPVisionModel`]. - - Examples: - - ```python - >>> from PIL import Image - >>> import requests - >>> from transformers import AutoProcessor, CLIPModel - - >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") - >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") - - >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" - >>> image = Image.open(requests.get(url, stream=True).raw) - - >>> inputs = processor(images=image, return_tensors="pt") - - >>> image_features = model.get_image_features(**inputs) - ```""" - # Use CLIP model's config for some fields (if specified) instead of those of vision & text components. - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - vision_outputs = self.vision_model( - pixel_values=pixel_values, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - pooled_output = vision_outputs[1] # pooled_output - image_features = self.visual_projection(pooled_output) - - return image_features - - @add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING) - @replace_return_docstrings(output_type=CLIPOutput, config_class=LanguageBindThermalConfig) - def forward( - self, - input_ids: Optional[torch.LongTensor] = None, - pixel_values: Optional[torch.FloatTensor] = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - return_loss: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, CLIPOutput]: - r""" - Returns: - - Examples: - - ```python - >>> from PIL import Image - >>> import requests - >>> from transformers import AutoProcessor, CLIPModel - - >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") - >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") - - >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" - >>> image = Image.open(requests.get(url, stream=True).raw) - - >>> inputs = processor( - ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True - ... ) - - >>> outputs = model(**inputs) - >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score - >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities - ```""" - # Use CLIP model's config for some fields (if specified) instead of those of vision & text components. - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - vision_outputs = self.vision_model( - pixel_values=pixel_values, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - text_outputs = self.text_model( - input_ids=input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - image_embeds = vision_outputs[1] - image_embeds = self.visual_projection(image_embeds) - - text_embeds = text_outputs[1] - text_embeds = self.text_projection(text_embeds) - - # normalized features - image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True) - text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True) - - # cosine similarity as logits - logit_scale = self.logit_scale.exp() - logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale - logits_per_image = logits_per_text.t() - - loss = None - if return_loss: - loss = clip_loss(logits_per_text) - - if not return_dict: - output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs) - return ((loss,) + output) if loss is not None else output - - return CLIPOutput( - loss=loss, - logits_per_image=logits_per_image, - logits_per_text=logits_per_text, - text_embeds=text_embeds, - image_embeds=image_embeds, - text_model_output=text_outputs, - vision_model_output=vision_outputs, - ) \ No newline at end of file diff --git a/spaces/LanguageBind/LanguageBind/open_clip/hf_configs.py b/spaces/LanguageBind/LanguageBind/open_clip/hf_configs.py deleted file mode 100644 index 13c9bfd8c660eac59f1fbc1912b9fccc9c0c625a..0000000000000000000000000000000000000000 --- a/spaces/LanguageBind/LanguageBind/open_clip/hf_configs.py +++ /dev/null @@ -1,56 +0,0 @@ -# HF architecture dict: -arch_dict = { - # https://huggingface.co/docs/transformers/model_doc/roberta#roberta - "roberta": { - "config_names": { - "context_length": "max_position_embeddings", - "vocab_size": "vocab_size", - "width": "hidden_size", - "heads": "num_attention_heads", - "layers": "num_hidden_layers", - "layer_attr": "layer", - "token_embeddings_attr": "embeddings" - }, - "pooler": "mean_pooler", - }, - # https://huggingface.co/docs/transformers/model_doc/xlm-roberta#transformers.XLMRobertaConfig - "xlm-roberta": { - "config_names": { - "context_length": "max_position_embeddings", - "vocab_size": "vocab_size", - "width": "hidden_size", - "heads": "num_attention_heads", - "layers": "num_hidden_layers", - "layer_attr": "layer", - "token_embeddings_attr": "embeddings" - }, - "pooler": "mean_pooler", - }, - # https://huggingface.co/docs/transformers/model_doc/mt5#mt5 - "mt5": { - "config_names": { - # unlimited seqlen - # https://github.com/google-research/text-to-text-transfer-transformer/issues/273 - # https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/models/t5/modeling_t5.py#L374 - "context_length": "", - "vocab_size": "vocab_size", - "width": "d_model", - "heads": "num_heads", - "layers": "num_layers", - "layer_attr": "block", - "token_embeddings_attr": "embed_tokens" - }, - "pooler": "mean_pooler", - }, - # https://huggingface.co/docs/transformers/model_doc/bert - "bert": { - "config_names": { - "context_length": "max_position_embeddings", - "vocab_size": "vocab_size", - "width": "hidden_size", - "heads": "num_attention_heads", - "layers": "num_hidden_layers", - }, - "pooler": "cls_pooler", - }, -} diff --git a/spaces/LaynzKunz/Model-RCV/rmvpe.py b/spaces/LaynzKunz/Model-RCV/rmvpe.py deleted file mode 100644 index 3ad346141340e03bdbaa20121e1ed435bb3da57a..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Model-RCV/rmvpe.py +++ /dev/null @@ -1,432 +0,0 @@ -import sys, torch, numpy as np, traceback, pdb -import torch.nn as nn -from time import time as ttime -import torch.nn.functional as F - - -class BiGRU(nn.Module): - def __init__(self, input_features, hidden_features, num_layers): - super(BiGRU, self).__init__() - self.gru = nn.GRU( - input_features, - hidden_features, - num_layers=num_layers, - batch_first=True, - bidirectional=True, - ) - - def forward(self, x): - return self.gru(x)[0] - - -class ConvBlockRes(nn.Module): - def __init__(self, in_channels, out_channels, momentum=0.01): - super(ConvBlockRes, self).__init__() - self.conv = nn.Sequential( - nn.Conv2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=(1, 1), - padding=(1, 1), - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - nn.Conv2d( - in_channels=out_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=(1, 1), - padding=(1, 1), - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - ) - if in_channels != out_channels: - self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1)) - self.is_shortcut = True - else: - self.is_shortcut = False - - def forward(self, x): - if self.is_shortcut: - return self.conv(x) + self.shortcut(x) - else: - return self.conv(x) + x - - -class Encoder(nn.Module): - def __init__( - self, - in_channels, - in_size, - n_encoders, - kernel_size, - n_blocks, - out_channels=16, - momentum=0.01, - ): - super(Encoder, self).__init__() - self.n_encoders = n_encoders - self.bn = nn.BatchNorm2d(in_channels, momentum=momentum) - self.layers = nn.ModuleList() - self.latent_channels = [] - for i in range(self.n_encoders): - self.layers.append( - ResEncoderBlock( - in_channels, out_channels, kernel_size, n_blocks, momentum=momentum - ) - ) - self.latent_channels.append([out_channels, in_size]) - in_channels = out_channels - out_channels *= 2 - in_size //= 2 - self.out_size = in_size - self.out_channel = out_channels - - def forward(self, x): - concat_tensors = [] - x = self.bn(x) - for i in range(self.n_encoders): - _, x = self.layers[i](x) - concat_tensors.append(_) - return x, concat_tensors - - -class ResEncoderBlock(nn.Module): - def __init__( - self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01 - ): - super(ResEncoderBlock, self).__init__() - self.n_blocks = n_blocks - self.conv = nn.ModuleList() - self.conv.append(ConvBlockRes(in_channels, out_channels, momentum)) - for i in range(n_blocks - 1): - self.conv.append(ConvBlockRes(out_channels, out_channels, momentum)) - self.kernel_size = kernel_size - if self.kernel_size is not None: - self.pool = nn.AvgPool2d(kernel_size=kernel_size) - - def forward(self, x): - for i in range(self.n_blocks): - x = self.conv[i](x) - if self.kernel_size is not None: - return x, self.pool(x) - else: - return x - - -class Intermediate(nn.Module): # - def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01): - super(Intermediate, self).__init__() - self.n_inters = n_inters - self.layers = nn.ModuleList() - self.layers.append( - ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum) - ) - for i in range(self.n_inters - 1): - self.layers.append( - ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum) - ) - - def forward(self, x): - for i in range(self.n_inters): - x = self.layers[i](x) - return x - - -class ResDecoderBlock(nn.Module): - def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01): - super(ResDecoderBlock, self).__init__() - out_padding = (0, 1) if stride == (1, 2) else (1, 1) - self.n_blocks = n_blocks - self.conv1 = nn.Sequential( - nn.ConvTranspose2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=stride, - padding=(1, 1), - output_padding=out_padding, - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - ) - self.conv2 = nn.ModuleList() - self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum)) - for i in range(n_blocks - 1): - self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum)) - - def forward(self, x, concat_tensor): - x = self.conv1(x) - x = torch.cat((x, concat_tensor), dim=1) - for i in range(self.n_blocks): - x = self.conv2[i](x) - return x - - -class Decoder(nn.Module): - def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01): - super(Decoder, self).__init__() - self.layers = nn.ModuleList() - self.n_decoders = n_decoders - for i in range(self.n_decoders): - out_channels = in_channels // 2 - self.layers.append( - ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum) - ) - in_channels = out_channels - - def forward(self, x, concat_tensors): - for i in range(self.n_decoders): - x = self.layers[i](x, concat_tensors[-1 - i]) - return x - - -class DeepUnet(nn.Module): - def __init__( - self, - kernel_size, - n_blocks, - en_de_layers=5, - inter_layers=4, - in_channels=1, - en_out_channels=16, - ): - super(DeepUnet, self).__init__() - self.encoder = Encoder( - in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels - ) - self.intermediate = Intermediate( - self.encoder.out_channel // 2, - self.encoder.out_channel, - inter_layers, - n_blocks, - ) - self.decoder = Decoder( - self.encoder.out_channel, en_de_layers, kernel_size, n_blocks - ) - - def forward(self, x): - x, concat_tensors = self.encoder(x) - x = self.intermediate(x) - x = self.decoder(x, concat_tensors) - return x - - -class E2E(nn.Module): - def __init__( - self, - n_blocks, - n_gru, - kernel_size, - en_de_layers=5, - inter_layers=4, - in_channels=1, - en_out_channels=16, - ): - super(E2E, self).__init__() - self.unet = DeepUnet( - kernel_size, - n_blocks, - en_de_layers, - inter_layers, - in_channels, - en_out_channels, - ) - self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1)) - if n_gru: - self.fc = nn.Sequential( - BiGRU(3 * 128, 256, n_gru), - nn.Linear(512, 360), - nn.Dropout(0.25), - nn.Sigmoid(), - ) - else: - self.fc = nn.Sequential( - nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid() - ) - - def forward(self, mel): - mel = mel.transpose(-1, -2).unsqueeze(1) - x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2) - x = self.fc(x) - return x - - -from librosa.filters import mel - - -class MelSpectrogram(torch.nn.Module): - def __init__( - self, - is_half, - n_mel_channels, - sampling_rate, - win_length, - hop_length, - n_fft=None, - mel_fmin=0, - mel_fmax=None, - clamp=1e-5, - ): - super().__init__() - n_fft = win_length if n_fft is None else n_fft - self.hann_window = {} - mel_basis = mel( - sr=sampling_rate, - n_fft=n_fft, - n_mels=n_mel_channels, - fmin=mel_fmin, - fmax=mel_fmax, - htk=True, - ) - mel_basis = torch.from_numpy(mel_basis).float() - self.register_buffer("mel_basis", mel_basis) - self.n_fft = win_length if n_fft is None else n_fft - self.hop_length = hop_length - self.win_length = win_length - self.sampling_rate = sampling_rate - self.n_mel_channels = n_mel_channels - self.clamp = clamp - self.is_half = is_half - - def forward(self, audio, keyshift=0, speed=1, center=True): - factor = 2 ** (keyshift / 12) - n_fft_new = int(np.round(self.n_fft * factor)) - win_length_new = int(np.round(self.win_length * factor)) - hop_length_new = int(np.round(self.hop_length * speed)) - keyshift_key = str(keyshift) + "_" + str(audio.device) - if keyshift_key not in self.hann_window: - self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to( - audio.device - ) - fft = torch.stft( - audio, - n_fft=n_fft_new, - hop_length=hop_length_new, - win_length=win_length_new, - window=self.hann_window[keyshift_key], - center=center, - return_complex=True, - ) - magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2)) - if keyshift != 0: - size = self.n_fft // 2 + 1 - resize = magnitude.size(1) - if resize < size: - magnitude = F.pad(magnitude, (0, 0, 0, size - resize)) - magnitude = magnitude[:, :size, :] * self.win_length / win_length_new - mel_output = torch.matmul(self.mel_basis, magnitude) - if self.is_half == True: - mel_output = mel_output.half() - log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp)) - return log_mel_spec - - -class RMVPE: - def __init__(self, model_path, is_half, device=None): - self.resample_kernel = {} - model = E2E(4, 1, (2, 2)) - ckpt = torch.load(model_path, map_location="cpu") - model.load_state_dict(ckpt) - model.eval() - if is_half == True: - model = model.half() - self.model = model - self.resample_kernel = {} - self.is_half = is_half - if device is None: - device = "cuda" if torch.cuda.is_available() else "cpu" - self.device = device - self.mel_extractor = MelSpectrogram( - is_half, 128, 16000, 1024, 160, None, 30, 8000 - ).to(device) - self.model = self.model.to(device) - cents_mapping = 20 * np.arange(360) + 1997.3794084376191 - self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368 - - def mel2hidden(self, mel): - with torch.no_grad(): - n_frames = mel.shape[-1] - mel = F.pad( - mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect" - ) - hidden = self.model(mel) - return hidden[:, :n_frames] - - def decode(self, hidden, thred=0.03): - cents_pred = self.to_local_average_cents(hidden, thred=thred) - f0 = 10 * (2 ** (cents_pred / 1200)) - f0[f0 == 10] = 0 - # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred]) - return f0 - - def infer_from_audio(self, audio, thred=0.03): - audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0) - # torch.cuda.synchronize() - # t0=ttime() - mel = self.mel_extractor(audio, center=True) - # torch.cuda.synchronize() - # t1=ttime() - hidden = self.mel2hidden(mel) - # torch.cuda.synchronize() - # t2=ttime() - hidden = hidden.squeeze(0).cpu().numpy() - if self.is_half == True: - hidden = hidden.astype("float32") - f0 = self.decode(hidden, thred=thred) - # torch.cuda.synchronize() - # t3=ttime() - # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0)) - return f0 - - def to_local_average_cents(self, salience, thred=0.05): - # t0 = ttime() - center = np.argmax(salience, axis=1) # 帧长#index - salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368 - # t1 = ttime() - center += 4 - todo_salience = [] - todo_cents_mapping = [] - starts = center - 4 - ends = center + 5 - for idx in range(salience.shape[0]): - todo_salience.append(salience[:, starts[idx] : ends[idx]][idx]) - todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]]) - # t2 = ttime() - todo_salience = np.array(todo_salience) # 帧长,9 - todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9 - product_sum = np.sum(todo_salience * todo_cents_mapping, 1) - weight_sum = np.sum(todo_salience, 1) # 帧长 - devided = product_sum / weight_sum # 帧长 - # t3 = ttime() - maxx = np.max(salience, axis=1) # 帧长 - devided[maxx <= thred] = 0 - # t4 = ttime() - # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3)) - return devided - - -# if __name__ == '__main__': -# audio, sampling_rate = sf.read("卢本伟语录~1.wav") -# if len(audio.shape) > 1: -# audio = librosa.to_mono(audio.transpose(1, 0)) -# audio_bak = audio.copy() -# if sampling_rate != 16000: -# audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) -# model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt" -# thred = 0.03 # 0.01 -# device = 'cuda' if torch.cuda.is_available() else 'cpu' -# rmvpe = RMVPE(model_path,is_half=False, device=device) -# t0=ttime() -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# t1=ttime() -# print(f0.shape,t1-t0) diff --git a/spaces/LaynzKunz/RCVAICOVER/src/infer_pack/attentions.py b/spaces/LaynzKunz/RCVAICOVER/src/infer_pack/attentions.py deleted file mode 100644 index 77cb63ffccf3e33badf22d50862a64ba517b487f..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/RCVAICOVER/src/infer_pack/attentions.py +++ /dev/null @@ -1,417 +0,0 @@ -import copy -import math -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - -from infer_pack import commons -from infer_pack import modules -from infer_pack.modules import LayerNorm - - -class Encoder(nn.Module): - def __init__( - self, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size=1, - p_dropout=0.0, - window_size=10, - **kwargs - ): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append( - MultiHeadAttention( - hidden_channels, - hidden_channels, - n_heads, - p_dropout=p_dropout, - window_size=window_size, - ) - ) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append( - FFN( - hidden_channels, - hidden_channels, - filter_channels, - kernel_size, - p_dropout=p_dropout, - ) - ) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__( - self, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size=1, - p_dropout=0.0, - proximal_bias=False, - proximal_init=True, - **kwargs - ): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append( - MultiHeadAttention( - hidden_channels, - hidden_channels, - n_heads, - p_dropout=p_dropout, - proximal_bias=proximal_bias, - proximal_init=proximal_init, - ) - ) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append( - MultiHeadAttention( - hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout - ) - ) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append( - FFN( - hidden_channels, - hidden_channels, - filter_channels, - kernel_size, - p_dropout=p_dropout, - causal=True, - ) - ) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( - device=x.device, dtype=x.dtype - ) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__( - self, - channels, - out_channels, - n_heads, - p_dropout=0.0, - window_size=None, - heads_share=True, - block_length=None, - proximal_bias=False, - proximal_init=False, - ): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels**-0.5 - self.emb_rel_k = nn.Parameter( - torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) - * rel_stddev - ) - self.emb_rel_v = nn.Parameter( - torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) - * rel_stddev - ) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1)) - if self.window_size is not None: - assert ( - t_s == t_t - ), "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys( - query / math.sqrt(self.k_channels), key_relative_embeddings - ) - scores_local = self._relative_position_to_absolute_position(rel_logits) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to( - device=scores.device, dtype=scores.dtype - ) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - assert ( - t_s == t_t - ), "Local attention is only available for self-attention." - block_mask = ( - torch.ones_like(scores) - .triu(-self.block_length) - .tril(self.block_length) - ) - scores = scores.masked_fill(block_mask == 0, -1e4) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings( - self.emb_rel_v, t_s - ) - output = output + self._matmul_with_relative_values( - relative_weights, value_relative_embeddings - ) - output = ( - output.transpose(2, 3).contiguous().view(b, d, t_t) - ) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]), - ) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[ - :, slice_start_position:slice_end_position - ] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad( - x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]) - ) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[ - :, :, :length, length - 1 : - ] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad( - x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]) - ) - x_flat = x.view([batch, heads, length**2 + length * (length - 1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__( - self, - in_channels, - out_channels, - filter_channels, - kernel_size, - p_dropout=0.0, - activation=None, - causal=False, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - self.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(x * x_mask)) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/Littlehongman/CLIPGPT-ImageCaptioner/Dockerfile b/spaces/Littlehongman/CLIPGPT-ImageCaptioner/Dockerfile deleted file mode 100644 index 8c593c38e1b84f326ad9ce3ea61379d6a8207b15..0000000000000000000000000000000000000000 --- a/spaces/Littlehongman/CLIPGPT-ImageCaptioner/Dockerfile +++ /dev/null @@ -1,24 +0,0 @@ -FROM python:3.8.9 - -WORKDIR /app - -COPY ./requirements.txt /app/requirements.txt -COPY ./packages.txt /app/packages.txt - -RUN apt-get update && xargs -r -a /app/packages.txt apt-get install -y && rm -rf /var/lib/apt/lists/* -RUN pip3 install --no-cache-dir -r /app/requirements.txt - -# User -RUN useradd -m -u 1000 user -USER user -ENV HOME /home/user -ENV PATH $HOME/.local/bin:$PATH - -WORKDIR $HOME -RUN mkdir app -WORKDIR $HOME/app -COPY . $HOME/app - -RUN echo "hello world" -EXPOSE 8501 -CMD streamlit run app.py \ No newline at end of file diff --git a/spaces/Liu-LAB/GPT-academic/crazy_functions/latex_fns/latex_actions.py b/spaces/Liu-LAB/GPT-academic/crazy_functions/latex_fns/latex_actions.py deleted file mode 100644 index c59bc31d4b445f69ac58b1e84db789cc4bbe4b43..0000000000000000000000000000000000000000 --- a/spaces/Liu-LAB/GPT-academic/crazy_functions/latex_fns/latex_actions.py +++ /dev/null @@ -1,447 +0,0 @@ -from toolbox import update_ui, update_ui_lastest_msg # 刷新Gradio前端界面 -from toolbox import zip_folder, objdump, objload, promote_file_to_downloadzone -from .latex_toolbox import PRESERVE, TRANSFORM -from .latex_toolbox import set_forbidden_text, set_forbidden_text_begin_end, set_forbidden_text_careful_brace -from .latex_toolbox import reverse_forbidden_text_careful_brace, reverse_forbidden_text, convert_to_linklist, post_process -from .latex_toolbox import fix_content, find_main_tex_file, merge_tex_files, compile_latex_with_timeout - -import os, shutil -import re -import numpy as np - -pj = os.path.join - - -def split_subprocess(txt, project_folder, return_dict, opts): - """ - break down latex file to a linked list, - each node use a preserve flag to indicate whether it should - be proccessed by GPT. - """ - text = txt - mask = np.zeros(len(txt), dtype=np.uint8) + TRANSFORM - - # 吸收title与作者以上的部分 - text, mask = set_forbidden_text(text, mask, r"^(.*?)\\maketitle", re.DOTALL) - text, mask = set_forbidden_text(text, mask, r"^(.*?)\\begin{document}", re.DOTALL) - # 吸收iffalse注释 - text, mask = set_forbidden_text(text, mask, r"\\iffalse(.*?)\\fi", re.DOTALL) - # 吸收在42行以内的begin-end组合 - text, mask = set_forbidden_text_begin_end(text, mask, r"\\begin\{([a-z\*]*)\}(.*?)\\end\{\1\}", re.DOTALL, limit_n_lines=42) - # 吸收匿名公式 - text, mask = set_forbidden_text(text, mask, [ r"\$\$([^$]+)\$\$", r"\\\[.*?\\\]" ], re.DOTALL) - # 吸收其他杂项 - text, mask = set_forbidden_text(text, mask, [ r"\\section\{(.*?)\}", r"\\section\*\{(.*?)\}", r"\\subsection\{(.*?)\}", r"\\subsubsection\{(.*?)\}" ]) - text, mask = set_forbidden_text(text, mask, [ r"\\bibliography\{(.*?)\}", r"\\bibliographystyle\{(.*?)\}" ]) - text, mask = set_forbidden_text(text, mask, r"\\begin\{thebibliography\}.*?\\end\{thebibliography\}", re.DOTALL) - text, mask = set_forbidden_text(text, mask, r"\\begin\{lstlisting\}(.*?)\\end\{lstlisting\}", re.DOTALL) - text, mask = set_forbidden_text(text, mask, r"\\begin\{wraptable\}(.*?)\\end\{wraptable\}", re.DOTALL) - text, mask = set_forbidden_text(text, mask, r"\\begin\{algorithm\}(.*?)\\end\{algorithm\}", re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{wrapfigure\}(.*?)\\end\{wrapfigure\}", r"\\begin\{wrapfigure\*\}(.*?)\\end\{wrapfigure\*\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{figure\}(.*?)\\end\{figure\}", r"\\begin\{figure\*\}(.*?)\\end\{figure\*\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{multline\}(.*?)\\end\{multline\}", r"\\begin\{multline\*\}(.*?)\\end\{multline\*\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{table\}(.*?)\\end\{table\}", r"\\begin\{table\*\}(.*?)\\end\{table\*\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{minipage\}(.*?)\\end\{minipage\}", r"\\begin\{minipage\*\}(.*?)\\end\{minipage\*\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{align\*\}(.*?)\\end\{align\*\}", r"\\begin\{align\}(.*?)\\end\{align\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\begin\{equation\}(.*?)\\end\{equation\}", r"\\begin\{equation\*\}(.*?)\\end\{equation\*\}"], re.DOTALL) - text, mask = set_forbidden_text(text, mask, [r"\\includepdf\[(.*?)\]\{(.*?)\}", r"\\clearpage", r"\\newpage", r"\\appendix", r"\\tableofcontents", r"\\include\{(.*?)\}"]) - text, mask = set_forbidden_text(text, mask, [r"\\vspace\{(.*?)\}", r"\\hspace\{(.*?)\}", r"\\label\{(.*?)\}", r"\\begin\{(.*?)\}", r"\\end\{(.*?)\}", r"\\item "]) - text, mask = set_forbidden_text_careful_brace(text, mask, r"\\hl\{(.*?)\}", re.DOTALL) - # reverse 操作必须放在最后 - text, mask = reverse_forbidden_text_careful_brace(text, mask, r"\\caption\{(.*?)\}", re.DOTALL, forbid_wrapper=True) - text, mask = reverse_forbidden_text_careful_brace(text, mask, r"\\abstract\{(.*?)\}", re.DOTALL, forbid_wrapper=True) - text, mask = reverse_forbidden_text(text, mask, r"\\begin\{abstract\}(.*?)\\end\{abstract\}", re.DOTALL, forbid_wrapper=True) - root = convert_to_linklist(text, mask) - - # 最后一步处理,增强稳健性 - root = post_process(root) - - # 输出html调试文件,用红色标注处保留区(PRESERVE),用黑色标注转换区(TRANSFORM) - with open(pj(project_folder, 'debug_log.html'), 'w', encoding='utf8') as f: - segment_parts_for_gpt = [] - nodes = [] - node = root - while True: - nodes.append(node) - show_html = node.string.replace('\n','
') - if not node.preserve: - segment_parts_for_gpt.append(node.string) - f.write(f'

#{node.range}{show_html}#

') - else: - f.write(f'

{show_html}

') - node = node.next - if node is None: break - - for n in nodes: n.next = None # break - return_dict['nodes'] = nodes - return_dict['segment_parts_for_gpt'] = segment_parts_for_gpt - return return_dict - -class LatexPaperSplit(): - """ - break down latex file to a linked list, - each node use a preserve flag to indicate whether it should - be proccessed by GPT. - """ - def __init__(self) -> None: - self.nodes = None - self.msg = "*{\\scriptsize\\textbf{警告:该PDF由GPT-Academic开源项目调用大语言模型+Latex翻译插件一键生成," + \ - "版权归原文作者所有。翻译内容可靠性无保障,请仔细鉴别并以原文为准。" + \ - "项目Github地址 \\url{https://github.com/binary-husky/gpt_academic/}。" - # 请您不要删除或修改这行警告,除非您是论文的原作者(如果您是论文原作者,欢迎加REAME中的QQ联系开发者) - self.msg_declare = "为了防止大语言模型的意外谬误产生扩散影响,禁止移除或修改此警告。}}\\\\" - - - def merge_result(self, arr, mode, msg, buggy_lines=[], buggy_line_surgery_n_lines=10): - """ - Merge the result after the GPT process completed - """ - result_string = "" - node_cnt = 0 - line_cnt = 0 - - for node in self.nodes: - if node.preserve: - line_cnt += node.string.count('\n') - result_string += node.string - else: - translated_txt = fix_content(arr[node_cnt], node.string) - begin_line = line_cnt - end_line = line_cnt + translated_txt.count('\n') - - # reverse translation if any error - if any([begin_line-buggy_line_surgery_n_lines <= b_line <= end_line+buggy_line_surgery_n_lines for b_line in buggy_lines]): - translated_txt = node.string - - result_string += translated_txt - node_cnt += 1 - line_cnt += translated_txt.count('\n') - - if mode == 'translate_zh': - pattern = re.compile(r'\\begin\{abstract\}.*\n') - match = pattern.search(result_string) - if not match: - # match \abstract{xxxx} - pattern_compile = re.compile(r"\\abstract\{(.*?)\}", flags=re.DOTALL) - match = pattern_compile.search(result_string) - position = match.regs[1][0] - else: - # match \begin{abstract}xxxx\end{abstract} - position = match.end() - result_string = result_string[:position] + self.msg + msg + self.msg_declare + result_string[position:] - return result_string - - - def split(self, txt, project_folder, opts): - """ - break down latex file to a linked list, - each node use a preserve flag to indicate whether it should - be proccessed by GPT. - P.S. use multiprocessing to avoid timeout error - """ - import multiprocessing - manager = multiprocessing.Manager() - return_dict = manager.dict() - p = multiprocessing.Process( - target=split_subprocess, - args=(txt, project_folder, return_dict, opts)) - p.start() - p.join() - p.close() - self.nodes = return_dict['nodes'] - self.sp = return_dict['segment_parts_for_gpt'] - return self.sp - - -class LatexPaperFileGroup(): - """ - use tokenizer to break down text according to max_token_limit - """ - def __init__(self): - self.file_paths = [] - self.file_contents = [] - self.sp_file_contents = [] - self.sp_file_index = [] - self.sp_file_tag = [] - - # count_token - from request_llm.bridge_all import model_info - enc = model_info["gpt-3.5-turbo"]['tokenizer'] - def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) - self.get_token_num = get_token_num - - def run_file_split(self, max_token_limit=1900): - """ - use tokenizer to break down text according to max_token_limit - """ - for index, file_content in enumerate(self.file_contents): - if self.get_token_num(file_content) < max_token_limit: - self.sp_file_contents.append(file_content) - self.sp_file_index.append(index) - self.sp_file_tag.append(self.file_paths[index]) - else: - from ..crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf - segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit) - for j, segment in enumerate(segments): - self.sp_file_contents.append(segment) - self.sp_file_index.append(index) - self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.tex") - print('Segmentation: done') - - def merge_result(self): - self.file_result = ["" for _ in range(len(self.file_paths))] - for r, k in zip(self.sp_file_result, self.sp_file_index): - self.file_result[k] += r - - def write_result(self): - manifest = [] - for path, res in zip(self.file_paths, self.file_result): - with open(path + '.polish.tex', 'w', encoding='utf8') as f: - manifest.append(path + '.polish.tex') - f.write(res) - return manifest - - -def Latex精细分解与转化(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, mode='proofread', switch_prompt=None, opts=[]): - import time, os, re - from ..crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency - from .latex_actions import LatexPaperFileGroup, LatexPaperSplit - - # <-------- 寻找主tex文件 ----------> - maintex = find_main_tex_file(file_manifest, mode) - chatbot.append((f"定位主Latex文件", f'[Local Message] 分析结果:该项目的Latex主文件是{maintex}, 如果分析错误, 请立即终止程序, 删除或修改歧义文件, 然后重试。主程序即将开始, 请稍候。')) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - time.sleep(3) - - # <-------- 读取Latex文件, 将多文件tex工程融合为一个巨型tex ----------> - main_tex_basename = os.path.basename(maintex) - assert main_tex_basename.endswith('.tex') - main_tex_basename_bare = main_tex_basename[:-4] - may_exist_bbl = pj(project_folder, f'{main_tex_basename_bare}.bbl') - if os.path.exists(may_exist_bbl): - shutil.copyfile(may_exist_bbl, pj(project_folder, f'merge.bbl')) - shutil.copyfile(may_exist_bbl, pj(project_folder, f'merge_{mode}.bbl')) - shutil.copyfile(may_exist_bbl, pj(project_folder, f'merge_diff.bbl')) - - with open(maintex, 'r', encoding='utf-8', errors='replace') as f: - content = f.read() - merged_content = merge_tex_files(project_folder, content, mode) - - with open(project_folder + '/merge.tex', 'w', encoding='utf-8', errors='replace') as f: - f.write(merged_content) - - # <-------- 精细切分latex文件 ----------> - chatbot.append((f"Latex文件融合完成", f'[Local Message] 正在精细切分latex文件,这需要一段时间计算,文档越长耗时越长,请耐心等待。')) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - lps = LatexPaperSplit() - res = lps.split(merged_content, project_folder, opts) # 消耗时间的函数 - - # <-------- 拆分过长的latex片段 ----------> - pfg = LatexPaperFileGroup() - for index, r in enumerate(res): - pfg.file_paths.append('segment-' + str(index)) - pfg.file_contents.append(r) - - pfg.run_file_split(max_token_limit=1024) - n_split = len(pfg.sp_file_contents) - - # <-------- 根据需要切换prompt ----------> - inputs_array, sys_prompt_array = switch_prompt(pfg, mode) - inputs_show_user_array = [f"{mode} {f}" for f in pfg.sp_file_tag] - - if os.path.exists(pj(project_folder,'temp.pkl')): - - # <-------- 【仅调试】如果存在调试缓存文件,则跳过GPT请求环节 ----------> - pfg = objload(file=pj(project_folder,'temp.pkl')) - - else: - # <-------- gpt 多线程请求 ----------> - gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( - inputs_array=inputs_array, - inputs_show_user_array=inputs_show_user_array, - llm_kwargs=llm_kwargs, - chatbot=chatbot, - history_array=[[""] for _ in range(n_split)], - sys_prompt_array=sys_prompt_array, - # max_workers=5, # 并行任务数量限制, 最多同时执行5个, 其他的排队等待 - scroller_max_len = 40 - ) - - # <-------- 文本碎片重组为完整的tex片段 ----------> - pfg.sp_file_result = [] - for i_say, gpt_say, orig_content in zip(gpt_response_collection[0::2], gpt_response_collection[1::2], pfg.sp_file_contents): - pfg.sp_file_result.append(gpt_say) - pfg.merge_result() - - # <-------- 临时存储用于调试 ----------> - pfg.get_token_num = None - objdump(pfg, file=pj(project_folder,'temp.pkl')) - - write_html(pfg.sp_file_contents, pfg.sp_file_result, chatbot=chatbot, project_folder=project_folder) - - # <-------- 写出文件 ----------> - msg = f"当前大语言模型: {llm_kwargs['llm_model']},当前语言模型温度设定: {llm_kwargs['temperature']}。" - final_tex = lps.merge_result(pfg.file_result, mode, msg) - objdump((lps, pfg.file_result, mode, msg), file=pj(project_folder,'merge_result.pkl')) - - with open(project_folder + f'/merge_{mode}.tex', 'w', encoding='utf-8', errors='replace') as f: - if mode != 'translate_zh' or "binary" in final_tex: f.write(final_tex) - - - # <-------- 整理结果, 退出 ----------> - chatbot.append((f"完成了吗?", 'GPT结果已输出, 即将编译PDF')) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # <-------- 返回 ----------> - return project_folder + f'/merge_{mode}.tex' - - -def remove_buggy_lines(file_path, log_path, tex_name, tex_name_pure, n_fix, work_folder_modified, fixed_line=[]): - try: - with open(log_path, 'r', encoding='utf-8', errors='replace') as f: - log = f.read() - import re - buggy_lines = re.findall(tex_name+':([0-9]{1,5}):', log) - buggy_lines = [int(l) for l in buggy_lines] - buggy_lines = sorted(buggy_lines) - buggy_line = buggy_lines[0]-1 - print("reversing tex line that has errors", buggy_line) - - # 重组,逆转出错的段落 - if buggy_line not in fixed_line: - fixed_line.append(buggy_line) - - lps, file_result, mode, msg = objload(file=pj(work_folder_modified,'merge_result.pkl')) - final_tex = lps.merge_result(file_result, mode, msg, buggy_lines=fixed_line, buggy_line_surgery_n_lines=5*n_fix) - - with open(pj(work_folder_modified, f"{tex_name_pure}_fix_{n_fix}.tex"), 'w', encoding='utf-8', errors='replace') as f: - f.write(final_tex) - - return True, f"{tex_name_pure}_fix_{n_fix}", buggy_lines - except: - print("Fatal error occurred, but we cannot identify error, please download zip, read latex log, and compile manually.") - return False, -1, [-1] - - -def 编译Latex(chatbot, history, main_file_original, main_file_modified, work_folder_original, work_folder_modified, work_folder, mode='default'): - import os, time - n_fix = 1 - fixed_line = [] - max_try = 32 - chatbot.append([f"正在编译PDF文档", f'编译已经开始。当前工作路径为{work_folder},如果程序停顿5分钟以上,请直接去该路径下取回翻译结果,或者重启之后再度尝试 ...']); yield from update_ui(chatbot=chatbot, history=history) - chatbot.append([f"正在编译PDF文档", '...']); yield from update_ui(chatbot=chatbot, history=history); time.sleep(1); chatbot[-1] = list(chatbot[-1]) # 刷新界面 - yield from update_ui_lastest_msg('编译已经开始...', chatbot, history) # 刷新Gradio前端界面 - - while True: - import os - may_exist_bbl = pj(work_folder_modified, f'merge.bbl') - target_bbl = pj(work_folder_modified, f'{main_file_modified}.bbl') - if os.path.exists(may_exist_bbl) and not os.path.exists(target_bbl): - shutil.copyfile(may_exist_bbl, target_bbl) - - # https://stackoverflow.com/questions/738755/dont-make-me-manually-abort-a-latex-compile-when-theres-an-error - yield from update_ui_lastest_msg(f'尝试第 {n_fix}/{max_try} 次编译, 编译原始PDF ...', chatbot, history) # 刷新Gradio前端界面 - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error {main_file_original}.tex', work_folder_original) - - yield from update_ui_lastest_msg(f'尝试第 {n_fix}/{max_try} 次编译, 编译转化后的PDF ...', chatbot, history) # 刷新Gradio前端界面 - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error {main_file_modified}.tex', work_folder_modified) - - if ok and os.path.exists(pj(work_folder_modified, f'{main_file_modified}.pdf')): - # 只有第二步成功,才能继续下面的步骤 - yield from update_ui_lastest_msg(f'尝试第 {n_fix}/{max_try} 次编译, 编译BibTex ...', chatbot, history) # 刷新Gradio前端界面 - if not os.path.exists(pj(work_folder_original, f'{main_file_original}.bbl')): - ok = compile_latex_with_timeout(f'bibtex {main_file_original}.aux', work_folder_original) - if not os.path.exists(pj(work_folder_modified, f'{main_file_modified}.bbl')): - ok = compile_latex_with_timeout(f'bibtex {main_file_modified}.aux', work_folder_modified) - - yield from update_ui_lastest_msg(f'尝试第 {n_fix}/{max_try} 次编译, 编译文献交叉引用 ...', chatbot, history) # 刷新Gradio前端界面 - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error {main_file_original}.tex', work_folder_original) - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error {main_file_modified}.tex', work_folder_modified) - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error {main_file_original}.tex', work_folder_original) - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error {main_file_modified}.tex', work_folder_modified) - - if mode!='translate_zh': - yield from update_ui_lastest_msg(f'尝试第 {n_fix}/{max_try} 次编译, 使用latexdiff生成论文转化前后对比 ...', chatbot, history) # 刷新Gradio前端界面 - print( f'latexdiff --encoding=utf8 --append-safecmd=subfile {work_folder_original}/{main_file_original}.tex {work_folder_modified}/{main_file_modified}.tex --flatten > {work_folder}/merge_diff.tex') - ok = compile_latex_with_timeout(f'latexdiff --encoding=utf8 --append-safecmd=subfile {work_folder_original}/{main_file_original}.tex {work_folder_modified}/{main_file_modified}.tex --flatten > {work_folder}/merge_diff.tex') - - yield from update_ui_lastest_msg(f'尝试第 {n_fix}/{max_try} 次编译, 正在编译对比PDF ...', chatbot, history) # 刷新Gradio前端界面 - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error merge_diff.tex', work_folder) - ok = compile_latex_with_timeout(f'bibtex merge_diff.aux', work_folder) - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error merge_diff.tex', work_folder) - ok = compile_latex_with_timeout(f'pdflatex -interaction=batchmode -file-line-error merge_diff.tex', work_folder) - - # <---------- 检查结果 -----------> - results_ = "" - original_pdf_success = os.path.exists(pj(work_folder_original, f'{main_file_original}.pdf')) - modified_pdf_success = os.path.exists(pj(work_folder_modified, f'{main_file_modified}.pdf')) - diff_pdf_success = os.path.exists(pj(work_folder, f'merge_diff.pdf')) - results_ += f"原始PDF编译是否成功: {original_pdf_success};" - results_ += f"转化PDF编译是否成功: {modified_pdf_success};" - results_ += f"对比PDF编译是否成功: {diff_pdf_success};" - yield from update_ui_lastest_msg(f'第{n_fix}编译结束:
{results_}...', chatbot, history) # 刷新Gradio前端界面 - - if diff_pdf_success: - result_pdf = pj(work_folder_modified, f'merge_diff.pdf') # get pdf path - promote_file_to_downloadzone(result_pdf, rename_file=None, chatbot=chatbot) # promote file to web UI - if modified_pdf_success: - yield from update_ui_lastest_msg(f'转化PDF编译已经成功, 即将退出 ...', chatbot, history) # 刷新Gradio前端界面 - result_pdf = pj(work_folder_modified, f'{main_file_modified}.pdf') # get pdf path - origin_pdf = pj(work_folder_original, f'{main_file_original}.pdf') # get pdf path - if os.path.exists(pj(work_folder, '..', 'translation')): - shutil.copyfile(result_pdf, pj(work_folder, '..', 'translation', 'translate_zh.pdf')) - promote_file_to_downloadzone(result_pdf, rename_file=None, chatbot=chatbot) # promote file to web UI - # 将两个PDF拼接 - if original_pdf_success: - try: - from .latex_toolbox import merge_pdfs - concat_pdf = pj(work_folder_modified, f'comparison.pdf') - merge_pdfs(origin_pdf, result_pdf, concat_pdf) - promote_file_to_downloadzone(concat_pdf, rename_file=None, chatbot=chatbot) # promote file to web UI - except Exception as e: - pass - return True # 成功啦 - else: - if n_fix>=max_try: break - n_fix += 1 - can_retry, main_file_modified, buggy_lines = remove_buggy_lines( - file_path=pj(work_folder_modified, f'{main_file_modified}.tex'), - log_path=pj(work_folder_modified, f'{main_file_modified}.log'), - tex_name=f'{main_file_modified}.tex', - tex_name_pure=f'{main_file_modified}', - n_fix=n_fix, - work_folder_modified=work_folder_modified, - fixed_line=fixed_line - ) - yield from update_ui_lastest_msg(f'由于最为关键的转化PDF编译失败, 将根据报错信息修正tex源文件并重试, 当前报错的latex代码处于第{buggy_lines}行 ...', chatbot, history) # 刷新Gradio前端界面 - if not can_retry: break - - return False # 失败啦 - - -def write_html(sp_file_contents, sp_file_result, chatbot, project_folder): - # write html - try: - import shutil - from ..crazy_utils import construct_html - from toolbox import gen_time_str - ch = construct_html() - orig = "" - trans = "" - final = [] - for c,r in zip(sp_file_contents, sp_file_result): - final.append(c) - final.append(r) - for i, k in enumerate(final): - if i%2==0: - orig = k - if i%2==1: - trans = k - ch.add_row(a=orig, b=trans) - create_report_file_name = f"{gen_time_str()}.trans.html" - ch.save_file(create_report_file_name) - shutil.copyfile(pj('./gpt_log/', create_report_file_name), pj(project_folder, create_report_file_name)) - promote_file_to_downloadzone(file=f'./gpt_log/{create_report_file_name}', chatbot=chatbot) - except: - from toolbox import trimmed_format_exc - print('writing html result failed:', trimmed_format_exc()) diff --git a/spaces/Loren/Streamlit_OCR_comparator/configs/textdet/dbnet/dbnet_r18_fpnc_100k_iters_synthtext.py b/spaces/Loren/Streamlit_OCR_comparator/configs/textdet/dbnet/dbnet_r18_fpnc_100k_iters_synthtext.py deleted file mode 100644 index 78a2bbbf87405a052690546681db127bd93ff738..0000000000000000000000000000000000000000 --- a/spaces/Loren/Streamlit_OCR_comparator/configs/textdet/dbnet/dbnet_r18_fpnc_100k_iters_synthtext.py +++ /dev/null @@ -1,59 +0,0 @@ -_base_ = [ - '../../_base_/default_runtime.py', - '../../_base_/schedules/schedule_sgd_100k_iters.py', - '../../_base_/det_models/dbnet_r18_fpnc.py', - '../../_base_/det_datasets/synthtext.py', - '../../_base_/det_pipelines/dbnet_pipeline.py' -] - -train_list = {{_base_.train_list}} -test_list = {{_base_.test_list}} - -img_norm_cfg = dict( - mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) -train_pipeline_r18 = [ - dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), - dict( - type='LoadTextAnnotations', - with_bbox=True, - with_mask=True, - poly2mask=False), - dict(type='ColorJitter', brightness=32.0 / 255, saturation=0.5), - dict(type='Normalize', **img_norm_cfg), - dict( - type='ImgAug', - args=[['Fliplr', 0.5], - dict(cls='Affine', rotate=[-10, 10]), ['Resize', [0.5, 3.0]]], - clip_invalid_ploys=False), - dict(type='EastRandomCrop', target_size=(640, 640)), - dict(type='DBNetTargets', shrink_ratio=0.4), - dict(type='Pad', size_divisor=32), - dict( - type='CustomFormatBundle', - keys=['gt_shrink', 'gt_shrink_mask', 'gt_thr', 'gt_thr_mask'], - visualize=dict(flag=False, boundary_key='gt_shrink')), - dict( - type='Collect', - keys=['img', 'gt_shrink', 'gt_shrink_mask', 'gt_thr', 'gt_thr_mask']) -] -test_pipeline_1333_736 = {{_base_.test_pipeline_1333_736}} - -data = dict( - samples_per_gpu=16, - workers_per_gpu=8, - val_dataloader=dict(samples_per_gpu=1), - test_dataloader=dict(samples_per_gpu=1), - train=dict( - type='UniformConcatDataset', - datasets=train_list, - pipeline=train_pipeline_r18), - val=dict( - type='UniformConcatDataset', - datasets=test_list, - pipeline=test_pipeline_1333_736), - test=dict( - type='UniformConcatDataset', - datasets=test_list, - pipeline=test_pipeline_1333_736)) - -evaluation = dict(interval=999999, metric='hmean-iou') # do not evaluate diff --git a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/util/configuration.py b/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/util/configuration.py deleted file mode 100644 index 890956b989ef9b2055b1faea7a850d335488a20d..0000000000000000000000000000000000000000 --- a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/util/configuration.py +++ /dev/null @@ -1,135 +0,0 @@ -from argparse import ArgumentParser - - -def none_or_default(x, default): - return x if x is not None else default - -class Configuration(): - def parse(self, unknown_arg_ok=False): - parser = ArgumentParser() - - # Enable torch.backends.cudnn.benchmark -- Faster in some cases, test in your own environment - parser.add_argument('--benchmark', action='store_true') - parser.add_argument('--no_amp', action='store_true') - - # Data parameters - parser.add_argument('--static_root', help='Static training data root', default='../static') - parser.add_argument('--bl_root', help='Blender training data root', default='../BL30K') - parser.add_argument('--yv_root', help='YouTubeVOS data root', default='../YouTube') - parser.add_argument('--davis_root', help='DAVIS data root', default='../DAVIS') - parser.add_argument('--num_workers', help='Total number of dataloader workers across all GPUs processes', type=int, default=16) - - parser.add_argument('--key_dim', default=64, type=int) - parser.add_argument('--value_dim', default=512, type=int) - parser.add_argument('--hidden_dim', default=64, help='Set to =0 to disable', type=int) - - parser.add_argument('--deep_update_prob', default=0.2, type=float) - - parser.add_argument('--stages', help='Training stage (0-static images, 1-Blender dataset, 2-DAVIS+YouTubeVOS)', default='02') - - """ - Stage-specific learning parameters - Batch sizes are effective -- you don't have to scale them when you scale the number processes - """ - # Stage 0, static images - parser.add_argument('--s0_batch_size', default=16, type=int) - parser.add_argument('--s0_iterations', default=150000, type=int) - parser.add_argument('--s0_finetune', default=0, type=int) - parser.add_argument('--s0_steps', nargs="*", default=[], type=int) - parser.add_argument('--s0_lr', help='Initial learning rate', default=1e-5, type=float) - parser.add_argument('--s0_num_ref_frames', default=2, type=int) - parser.add_argument('--s0_num_frames', default=3, type=int) - parser.add_argument('--s0_start_warm', default=20000, type=int) - parser.add_argument('--s0_end_warm', default=70000, type=int) - - # Stage 1, BL30K - parser.add_argument('--s1_batch_size', default=8, type=int) - parser.add_argument('--s1_iterations', default=250000, type=int) - # fine-tune means fewer augmentations to train the sensory memory - parser.add_argument('--s1_finetune', default=0, type=int) - parser.add_argument('--s1_steps', nargs="*", default=[200000], type=int) - parser.add_argument('--s1_lr', help='Initial learning rate', default=1e-5, type=float) - parser.add_argument('--s1_num_ref_frames', default=3, type=int) - parser.add_argument('--s1_num_frames', default=8, type=int) - parser.add_argument('--s1_start_warm', default=20000, type=int) - parser.add_argument('--s1_end_warm', default=70000, type=int) - - # Stage 2, DAVIS+YoutubeVOS, longer - parser.add_argument('--s2_batch_size', default=8, type=int) - parser.add_argument('--s2_iterations', default=150000, type=int) - # fine-tune means fewer augmentations to train the sensory memory - parser.add_argument('--s2_finetune', default=10000, type=int) - parser.add_argument('--s2_steps', nargs="*", default=[120000], type=int) - parser.add_argument('--s2_lr', help='Initial learning rate', default=1e-5, type=float) - parser.add_argument('--s2_num_ref_frames', default=3, type=int) - parser.add_argument('--s2_num_frames', default=8, type=int) - parser.add_argument('--s2_start_warm', default=20000, type=int) - parser.add_argument('--s2_end_warm', default=70000, type=int) - - # Stage 3, DAVIS+YoutubeVOS, shorter - parser.add_argument('--s3_batch_size', default=8, type=int) - parser.add_argument('--s3_iterations', default=100000, type=int) - # fine-tune means fewer augmentations to train the sensory memory - parser.add_argument('--s3_finetune', default=10000, type=int) - parser.add_argument('--s3_steps', nargs="*", default=[80000], type=int) - parser.add_argument('--s3_lr', help='Initial learning rate', default=1e-5, type=float) - parser.add_argument('--s3_num_ref_frames', default=3, type=int) - parser.add_argument('--s3_num_frames', default=8, type=int) - parser.add_argument('--s3_start_warm', default=20000, type=int) - parser.add_argument('--s3_end_warm', default=70000, type=int) - - parser.add_argument('--gamma', help='LR := LR*gamma at every decay step', default=0.1, type=float) - parser.add_argument('--weight_decay', default=0.05, type=float) - - # Loading - parser.add_argument('--load_network', help='Path to pretrained network weight only') - parser.add_argument('--load_checkpoint', help='Path to the checkpoint file, including network, optimizer and such') - - # Logging information - parser.add_argument('--log_text_interval', default=100, type=int) - parser.add_argument('--log_image_interval', default=1000, type=int) - parser.add_argument('--save_network_interval', default=25000, type=int) - parser.add_argument('--save_checkpoint_interval', default=50000, type=int) - parser.add_argument('--exp_id', help='Experiment UNIQUE id, use NULL to disable logging to tensorboard', default='NULL') - parser.add_argument('--debug', help='Debug mode which logs information more often', action='store_true') - - # # Multiprocessing parameters, not set by users - # parser.add_argument('--local_rank', default=0, type=int, help='Local rank of this process') - - if unknown_arg_ok: - args, _ = parser.parse_known_args() - self.args = vars(args) - else: - self.args = vars(parser.parse_args()) - - self.args['amp'] = not self.args['no_amp'] - - # check if the stages are valid - stage_to_perform = list(self.args['stages']) - for s in stage_to_perform: - if s not in ['0', '1', '2', '3']: - raise NotImplementedError - - def get_stage_parameters(self, stage): - parameters = { - 'batch_size': self.args['s%s_batch_size'%stage], - 'iterations': self.args['s%s_iterations'%stage], - 'finetune': self.args['s%s_finetune'%stage], - 'steps': self.args['s%s_steps'%stage], - 'lr': self.args['s%s_lr'%stage], - 'num_ref_frames': self.args['s%s_num_ref_frames'%stage], - 'num_frames': self.args['s%s_num_frames'%stage], - 'start_warm': self.args['s%s_start_warm'%stage], - 'end_warm': self.args['s%s_end_warm'%stage], - } - - return parameters - - def __getitem__(self, key): - return self.args[key] - - def __setitem__(self, key, value): - self.args[key] = value - - def __str__(self): - return str(self.args) diff --git a/spaces/Mountchicken/MAERec-Gradio/configs/textrecog/abinet/abinet_10e_union14m.py b/spaces/Mountchicken/MAERec-Gradio/configs/textrecog/abinet/abinet_10e_union14m.py deleted file mode 100644 index 18961901eea0aa12341127e427e73a8eed208d9e..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/configs/textrecog/abinet/abinet_10e_union14m.py +++ /dev/null @@ -1,118 +0,0 @@ -_base_ = [ - '../_base_/datasets/union14m_train.py', - '../_base_/datasets/union14m_benchmark.py', - '../_base_/datasets/cute80.py', - '../_base_/datasets/iiit5k.py', - '../_base_/datasets/svt.py', - '../_base_/datasets/svtp.py', - '../_base_/datasets/icdar2013.py', - '../_base_/datasets/icdar2015.py', - '../_base_/default_runtime.py', - '../_base_/schedules/schedule_adamw_cos_10e.py', - '_base_abinet.py', -] - -load_from = 'https://download.openmmlab.com/mmocr/textrecog/abinet/abinet_pretrain-45deac15.pth' # noqa - -_base_.pop('model') -dictionary = dict( - type='Dictionary', - dict_file= # noqa - '{{ fileDirname }}/../../../dicts/english_digits_symbols_space.txt', - with_padding=True, - with_unknown=True, - same_start_end=True, - with_start=True, - with_end=True) - -model = dict( - type='ABINet', - backbone=dict(type='ResNetABI'), - encoder=dict( - type='ABIEncoder', - n_layers=3, - n_head=8, - d_model=512, - d_inner=2048, - dropout=0.1, - max_len=8 * 32, - ), - decoder=dict( - type='ABIFuser', - vision_decoder=dict( - type='ABIVisionDecoder', - in_channels=512, - num_channels=64, - attn_height=8, - attn_width=32, - attn_mode='nearest', - init_cfg=dict(type='Xavier', layer='Conv2d')), - module_loss=dict(type='ABIModuleLoss'), - postprocessor=dict(type='AttentionPostprocessor'), - dictionary=dictionary, - max_seq_len=26, - ), - data_preprocessor=dict( - type='TextRecogDataPreprocessor', - mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375])) - -# dataset settings -train_list = [ - _base_.union14m_challenging, _base_.union14m_hard, _base_.union14m_medium, - _base_.union14m_normal, _base_.union14m_easy -] -val_list = [ - _base_.cute80_textrecog_test, _base_.iiit5k_textrecog_test, - _base_.svt_textrecog_test, _base_.svtp_textrecog_test, - _base_.icdar2013_textrecog_test, _base_.icdar2015_textrecog_test -] -test_list = [ - _base_.union14m_benchmark_artistic, - _base_.union14m_benchmark_multi_oriented, - _base_.union14m_benchmark_contextless, - _base_.union14m_benchmark_curve, - _base_.union14m_benchmark_incomplete, - _base_.union14m_benchmark_incomplete_ori, - _base_.union14m_benchmark_multi_words, - _base_.union14m_benchmark_salient, - _base_.union14m_benchmark_general, -] - -train_dataset = dict( - type='ConcatDataset', datasets=train_list, pipeline=_base_.train_pipeline) -test_dataset = dict( - type='ConcatDataset', datasets=test_list, pipeline=_base_.test_pipeline) -val_dataset = dict( - type='ConcatDataset', datasets=val_list, pipeline=_base_.test_pipeline) - -train_dataloader = dict( - batch_size=128, - num_workers=24, - persistent_workers=True, - sampler=dict(type='DefaultSampler', shuffle=True), - dataset=train_dataset) - -test_dataloader = dict( - batch_size=128, - num_workers=4, - persistent_workers=True, - drop_last=False, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=test_dataset) - -val_dataloader = dict( - batch_size=128, - num_workers=4, - persistent_workers=True, - pin_memory=True, - drop_last=False, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=val_dataset) - -val_evaluator = dict( - dataset_prefixes=['CUTE80', 'IIIT5K', 'SVT', 'SVTP', 'IC13', 'IC15']) -test_evaluator = dict(dataset_prefixes=[ - 'artistic', 'multi-oriented', 'contextless', 'curve', 'incomplete', - 'incomplete-ori', 'multi-words', 'salient', 'general' -]) diff --git a/spaces/NATSpeech/PortaSpeech/mfa_usr/run_mfa_train_align.sh b/spaces/NATSpeech/PortaSpeech/mfa_usr/run_mfa_train_align.sh deleted file mode 100644 index ed3d8265f2d4dbfd83d7314d8aad734bc20ea657..0000000000000000000000000000000000000000 --- a/spaces/NATSpeech/PortaSpeech/mfa_usr/run_mfa_train_align.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -set -e - -NUM_JOB=${NUM_JOB:-36} -echo "| Training MFA using ${NUM_JOB} cores." -BASE_DIR=data/processed/$CORPUS -MODEL_NAME=${MODEL_NAME:-"mfa_model"} -PRETRAIN_MODEL_NAME=${PRETRAIN_MODEL_NAME:-"mfa_model_pretrain"} -MFA_INPUTS=${MFA_INPUTS:-"mfa_inputs"} -MFA_OUTPUTS=${MFA_OUTPUTS:-"mfa_outputs"} -MFA_CMD=${MFA_CMD:-"train"} -rm -rf $BASE_DIR/mfa_outputs_tmp -if [ "$MFA_CMD" = "train" ]; then - mfa train $BASE_DIR/$MFA_INPUTS $BASE_DIR/mfa_dict.txt $BASE_DIR/mfa_outputs_tmp -t $BASE_DIR/mfa_tmp -o $BASE_DIR/$MODEL_NAME.zip --clean -j $NUM_JOB --config_path mfa_usr/mfa_train_config.yaml -elif [ "$MFA_CMD" = "adapt" ]; then - python mfa_usr/mfa.py adapt \ - $BASE_DIR/$MFA_INPUTS \ - $BASE_DIR/mfa_dict.txt \ - $BASE_DIR/$PRETRAIN_MODEL_NAME.zip \ - $BASE_DIR/$MODEL_NAME.zip \ - $BASE_DIR/mfa_outputs_tmp \ - -t $BASE_DIR/mfa_tmp --clean -j $NUM_JOB -fi -rm -rf $BASE_DIR/mfa_tmp $BASE_DIR/$MFA_OUTPUTS -mkdir -p $BASE_DIR/$MFA_OUTPUTS -find $BASE_DIR/mfa_outputs_tmp -regex ".*\.TextGrid" -print0 | xargs -0 -i mv {} $BASE_DIR/$MFA_OUTPUTS/ -if [ -e "$BASE_DIR/mfa_outputs_tmp/unaligned.txt" ]; then - cp $BASE_DIR/mfa_outputs_tmp/unaligned.txt $BASE_DIR/ -fi -rm -rf $BASE_DIR/mfa_outputs_tmp \ No newline at end of file diff --git a/spaces/NCTCMumbai/NCTC/models/official/nlp/bert/run_pretraining.py b/spaces/NCTCMumbai/NCTC/models/official/nlp/bert/run_pretraining.py deleted file mode 100644 index 44a18fea0ce9d79bea61294e91f0ac00c2ea45e6..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/nlp/bert/run_pretraining.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright 2019 The TensorFlow 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. -# ============================================================================== -"""Run masked LM/next sentence pre-training for BERT in TF 2.x.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -from absl import app -from absl import flags -from absl import logging -import gin -import tensorflow as tf -from official.modeling import performance -from official.nlp import optimization -from official.nlp.bert import bert_models -from official.nlp.bert import common_flags -from official.nlp.bert import configs -from official.nlp.bert import input_pipeline -from official.nlp.bert import model_training_utils -from official.utils.misc import distribution_utils - - -flags.DEFINE_string('input_files', None, - 'File path to retrieve training data for pre-training.') -# Model training specific flags. -flags.DEFINE_integer( - 'max_seq_length', 128, - 'The maximum total input sequence length after WordPiece tokenization. ' - 'Sequences longer than this will be truncated, and sequences shorter ' - 'than this will be padded.') -flags.DEFINE_integer('max_predictions_per_seq', 20, - 'Maximum predictions per sequence_output.') -flags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.') -flags.DEFINE_integer('num_steps_per_epoch', 1000, - 'Total number of training steps to run per epoch.') -flags.DEFINE_float('warmup_steps', 10000, - 'Warmup steps for Adam weight decay optimizer.') -flags.DEFINE_bool('use_next_sentence_label', True, - 'Whether to use next sentence label to compute final loss.') -flags.DEFINE_bool('train_summary_interval', 0, 'Step interval for training ' - 'summaries. If the value is a negative number, ' - 'then training summaries are not enabled.') - -common_flags.define_common_bert_flags() - -FLAGS = flags.FLAGS - - -def get_pretrain_dataset_fn(input_file_pattern, seq_length, - max_predictions_per_seq, global_batch_size, - use_next_sentence_label=True): - """Returns input dataset from input file string.""" - def _dataset_fn(ctx=None): - """Returns tf.data.Dataset for distributed BERT pretraining.""" - input_patterns = input_file_pattern.split(',') - batch_size = ctx.get_per_replica_batch_size(global_batch_size) - train_dataset = input_pipeline.create_pretrain_dataset( - input_patterns, - seq_length, - max_predictions_per_seq, - batch_size, - is_training=True, - input_pipeline_context=ctx, - use_next_sentence_label=use_next_sentence_label) - return train_dataset - - return _dataset_fn - - -def get_loss_fn(): - """Returns loss function for BERT pretraining.""" - - def _bert_pretrain_loss_fn(unused_labels, losses, **unused_args): - return tf.reduce_mean(losses) - - return _bert_pretrain_loss_fn - - -def run_customized_training(strategy, - bert_config, - init_checkpoint, - max_seq_length, - max_predictions_per_seq, - model_dir, - steps_per_epoch, - steps_per_loop, - epochs, - initial_lr, - warmup_steps, - end_lr, - optimizer_type, - input_files, - train_batch_size, - use_next_sentence_label=True, - train_summary_interval=0, - custom_callbacks=None): - """Run BERT pretrain model training using low-level API.""" - - train_input_fn = get_pretrain_dataset_fn(input_files, max_seq_length, - max_predictions_per_seq, - train_batch_size, - use_next_sentence_label) - - def _get_pretrain_model(): - """Gets a pretraining model.""" - pretrain_model, core_model = bert_models.pretrain_model( - bert_config, max_seq_length, max_predictions_per_seq, - use_next_sentence_label=use_next_sentence_label) - optimizer = optimization.create_optimizer( - initial_lr, steps_per_epoch * epochs, warmup_steps, - end_lr, optimizer_type) - pretrain_model.optimizer = performance.configure_optimizer( - optimizer, - use_float16=common_flags.use_float16(), - use_graph_rewrite=common_flags.use_graph_rewrite()) - return pretrain_model, core_model - - trained_model = model_training_utils.run_customized_training_loop( - strategy=strategy, - model_fn=_get_pretrain_model, - loss_fn=get_loss_fn(), - scale_loss=FLAGS.scale_loss, - model_dir=model_dir, - init_checkpoint=init_checkpoint, - train_input_fn=train_input_fn, - steps_per_epoch=steps_per_epoch, - steps_per_loop=steps_per_loop, - epochs=epochs, - sub_model_export_name='pretrained/bert_model', - train_summary_interval=train_summary_interval, - custom_callbacks=custom_callbacks) - - return trained_model - - -def run_bert_pretrain(strategy, custom_callbacks=None): - """Runs BERT pre-training.""" - - bert_config = configs.BertConfig.from_json_file(FLAGS.bert_config_file) - if not strategy: - raise ValueError('Distribution strategy is not specified.') - - # Runs customized training loop. - logging.info('Training using customized training loop TF 2.0 with distributed' - 'strategy.') - - performance.set_mixed_precision_policy(common_flags.dtype()) - - return run_customized_training( - strategy, - bert_config, - FLAGS.init_checkpoint, # Used to initialize only the BERT submodel. - FLAGS.max_seq_length, - FLAGS.max_predictions_per_seq, - FLAGS.model_dir, - FLAGS.num_steps_per_epoch, - FLAGS.steps_per_loop, - FLAGS.num_train_epochs, - FLAGS.learning_rate, - FLAGS.warmup_steps, - FLAGS.end_lr, - FLAGS.optimizer_type, - FLAGS.input_files, - FLAGS.train_batch_size, - FLAGS.use_next_sentence_label, - FLAGS.train_summary_interval, - custom_callbacks=custom_callbacks) - - -def main(_): - gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param) - if not FLAGS.model_dir: - FLAGS.model_dir = '/tmp/bert20/' - strategy = distribution_utils.get_distribution_strategy( - distribution_strategy=FLAGS.distribution_strategy, - num_gpus=FLAGS.num_gpus, - tpu_address=FLAGS.tpu) - if strategy: - print('***** Number of cores used : ', strategy.num_replicas_in_sync) - - run_bert_pretrain(strategy) - - -if __name__ == '__main__': - app.run(main) diff --git a/spaces/NCTCMumbai/NCTC/models/official/nlp/transformer/translate.py b/spaces/NCTCMumbai/NCTC/models/official/nlp/transformer/translate.py deleted file mode 100644 index 1f92504142e08918a972dff10c422a58fcfbbd04..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/nlp/transformer/translate.py +++ /dev/null @@ -1,199 +0,0 @@ -# Copyright 2018 The TensorFlow 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. -# ============================================================================== -"""Translate text or files using trained transformer model.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -from absl import logging -import numpy as np -import tensorflow as tf - -from official.nlp.transformer.utils import tokenizer - -_EXTRA_DECODE_LENGTH = 100 -_BEAM_SIZE = 4 -_ALPHA = 0.6 - - -def _get_sorted_inputs(filename): - """Read and sort lines from the file sorted by decreasing length. - - Args: - filename: String name of file to read inputs from. - Returns: - Sorted list of inputs, and dictionary mapping original index->sorted index - of each element. - """ - with tf.io.gfile.GFile(filename) as f: - records = f.read().split("\n") - inputs = [record.strip() for record in records] - if not inputs[-1]: - inputs.pop() - - input_lens = [(i, len(line.split())) for i, line in enumerate(inputs)] - sorted_input_lens = sorted(input_lens, key=lambda x: x[1], reverse=True) - - sorted_inputs = [None] * len(sorted_input_lens) - sorted_keys = [0] * len(sorted_input_lens) - for i, (index, _) in enumerate(sorted_input_lens): - sorted_inputs[i] = inputs[index] - sorted_keys[index] = i - return sorted_inputs, sorted_keys - - -def _encode_and_add_eos(line, subtokenizer): - """Encode line with subtokenizer, and add EOS id to the end.""" - return subtokenizer.encode(line) + [tokenizer.EOS_ID] - - -def _trim_and_decode(ids, subtokenizer): - """Trim EOS and PAD tokens from ids, and decode to return a string.""" - try: - index = list(ids).index(tokenizer.EOS_ID) - return subtokenizer.decode(ids[:index]) - except ValueError: # No EOS found in sequence - return subtokenizer.decode(ids) - - -def translate_file(model, - params, - subtokenizer, - input_file, - output_file=None, - print_all_translations=True, - distribution_strategy=None): - """Translate lines in file, and save to output file if specified. - - Args: - model: A Keras model, used to generate the translations. - params: A dictionary, containing the translation related parameters. - subtokenizer: A subtokenizer object, used for encoding and decoding source - and translated lines. - input_file: A file containing lines to translate. - output_file: A file that stores the generated translations. - print_all_translations: A bool. If true, all translations are printed to - stdout. - distribution_strategy: A distribution strategy, used to perform inference - directly with tf.function instead of Keras model.predict(). - - Raises: - ValueError: if output file is invalid. - """ - batch_size = params["decode_batch_size"] - - # Read and sort inputs by length. Keep dictionary (original index-->new index - # in sorted list) to write translations in the original order. - sorted_inputs, sorted_keys = _get_sorted_inputs(input_file) - total_samples = len(sorted_inputs) - num_decode_batches = (total_samples - 1) // batch_size + 1 - - def input_generator(): - """Yield encoded strings from sorted_inputs.""" - for i in range(num_decode_batches): - lines = [ - sorted_inputs[j + i * batch_size] - for j in range(batch_size) - if j + i * batch_size < total_samples - ] - lines = [_encode_and_add_eos(l, subtokenizer) for l in lines] - if distribution_strategy: - for j in range(batch_size - len(lines)): - lines.append([tokenizer.EOS_ID]) - batch = tf.keras.preprocessing.sequence.pad_sequences( - lines, - maxlen=params["decode_max_length"], - dtype="int32", - padding="post") - logging.info("Decoding batch %d out of %d.", i, num_decode_batches) - yield batch - - @tf.function - def predict_step(inputs): - """Decoding step function for TPU runs.""" - - def _step_fn(inputs): - """Per replica step function.""" - tag = inputs[0] - val_inputs = inputs[1] - val_outputs, _ = model([val_inputs], training=False) - return tag, val_outputs - - return distribution_strategy.run(_step_fn, args=(inputs,)) - - translations = [] - if distribution_strategy: - num_replicas = distribution_strategy.num_replicas_in_sync - local_batch_size = params["decode_batch_size"] // num_replicas - for i, text in enumerate(input_generator()): - if distribution_strategy: - text = np.reshape(text, [num_replicas, local_batch_size, -1]) - # Add tag to the input of each replica with the reordering logic after - # outputs, to ensure the output order matches the input order. - text = tf.constant(text) - - @tf.function - def text_as_per_replica(): - replica_context = tf.distribute.get_replica_context() - replica_id = replica_context.replica_id_in_sync_group - return replica_id, text[replica_id] - - text = distribution_strategy.run(text_as_per_replica) - outputs = distribution_strategy.experimental_local_results( - predict_step(text)) - tags, unordered_val_outputs = outputs[0] - tags = [tag.numpy() for tag in tags._values] - unordered_val_outputs = [ - val_output.numpy() for val_output in unordered_val_outputs._values] - # pylint: enable=protected-access - val_outputs = [None] * len(tags) - for k in range(len(tags)): - val_outputs[tags[k]] = unordered_val_outputs[k] - val_outputs = np.reshape(val_outputs, [params["decode_batch_size"], -1]) - else: - val_outputs, _ = model.predict(text) - - length = len(val_outputs) - for j in range(length): - if j + i * batch_size < total_samples: - translation = _trim_and_decode(val_outputs[j], subtokenizer) - translations.append(translation) - if print_all_translations: - logging.info("Translating:\n\tInput: %s\n\tOutput: %s", - sorted_inputs[j + i * batch_size], translation) - - # Write translations in the order they appeared in the original file. - if output_file is not None: - if tf.io.gfile.isdir(output_file): - raise ValueError("File output is a directory, will not save outputs to " - "file.") - logging.info("Writing to file %s", output_file) - with tf.compat.v1.gfile.Open(output_file, "w") as f: - for i in sorted_keys: - f.write("%s\n" % translations[i]) - - -def translate_from_text(model, subtokenizer, txt): - encoded_txt = _encode_and_add_eos(txt, subtokenizer) - result = model.predict(encoded_txt) - outputs = result["outputs"] - logging.info("Original: \"%s\"", txt) - translate_from_input(outputs, subtokenizer) - - -def translate_from_input(outputs, subtokenizer): - translation = _trim_and_decode(outputs, subtokenizer) - logging.info("Translation: \"%s\"", translation) diff --git a/spaces/NCTCMumbai/NCTC/models/research/brain_coder/single_task/results_lib_test.py b/spaces/NCTCMumbai/NCTC/models/research/brain_coder/single_task/results_lib_test.py deleted file mode 100644 index 6fe838d74d6a3bdea4c3b219a4d3ceea4385a97e..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/research/brain_coder/single_task/results_lib_test.py +++ /dev/null @@ -1,84 +0,0 @@ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -"""Tests for results_lib.""" - -import contextlib -import os -import shutil -import tempfile -from six.moves import xrange -import tensorflow as tf - -from single_task import results_lib # brain coder - - -@contextlib.contextmanager -def temporary_directory(suffix='', prefix='tmp', base_path=None): - """A context manager to create a temporary directory and clean up on exit. - - The parameters are the same ones expected by tempfile.mkdtemp. - The directory will be securely and atomically created. - Everything under it will be removed when exiting the context. - - Args: - suffix: optional suffix. - prefix: options prefix. - base_path: the base path under which to create the temporary directory. - Yields: - The absolute path of the new temporary directory. - """ - temp_dir_path = tempfile.mkdtemp(suffix, prefix, base_path) - try: - yield temp_dir_path - finally: - try: - shutil.rmtree(temp_dir_path) - except OSError as e: - if e.message == 'Cannot call rmtree on a symbolic link': - # Interesting synthetic exception made up by shutil.rmtree. - # Means we received a symlink from mkdtemp. - # Also means must clean up the symlink instead. - os.unlink(temp_dir_path) - else: - raise - - -def freeze(dictionary): - """Convert dict to hashable frozenset.""" - return frozenset(dictionary.iteritems()) - - -class ResultsLibTest(tf.test.TestCase): - - def testResults(self): - with temporary_directory() as logdir: - results_obj = results_lib.Results(logdir) - self.assertEqual(results_obj.read_this_shard(), []) - results_obj.append( - {'foo': 1.5, 'bar': 2.5, 'baz': 0}) - results_obj.append( - {'foo': 5.5, 'bar': -1, 'baz': 2}) - self.assertEqual( - results_obj.read_this_shard(), - [{'foo': 1.5, 'bar': 2.5, 'baz': 0}, - {'foo': 5.5, 'bar': -1, 'baz': 2}]) - - def testShardedResults(self): - with temporary_directory() as logdir: - n = 4 # Number of shards. - results_objs = [ - results_lib.Results(logdir, shard_id=i) for i in xrange(n)] - for i, robj in enumerate(results_objs): - robj.append({'foo': i, 'bar': 1 + i * 2}) - results_list, _ = results_objs[0].read_all() - - # Check results. Order does not matter here. - self.assertEqual( - set(freeze(r) for r in results_list), - set(freeze({'foo': i, 'bar': 1 + i * 2}) for i in xrange(n))) - - -if __name__ == '__main__': - tf.test.main() diff --git a/spaces/NiuTaipu/moe-tts-test01/monotonic_align/__init__.py b/spaces/NiuTaipu/moe-tts-test01/monotonic_align/__init__.py deleted file mode 100644 index 40b6f64aa116c74cac2f6a33444c9eeea2fdb38c..0000000000000000000000000000000000000000 --- a/spaces/NiuTaipu/moe-tts-test01/monotonic_align/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -from numpy import zeros, int32, float32 -from torch import from_numpy - -from .core import maximum_path_jit - - -def maximum_path(neg_cent, mask): - """ numba optimized version. - neg_cent: [b, t_t, t_s] - mask: [b, t_t, t_s] - """ - device = neg_cent.device - dtype = neg_cent.dtype - neg_cent = neg_cent.data.cpu().numpy().astype(float32) - path = zeros(neg_cent.shape, dtype=int32) - - t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(int32) - t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(int32) - maximum_path_jit(path, neg_cent, t_t_max, t_s_max) - return from_numpy(path).to(device=device, dtype=dtype) - diff --git a/spaces/Nyari/Super-Resolution-Anime-Diffusion/RealESRGANv030/docs/Training.md b/spaces/Nyari/Super-Resolution-Anime-Diffusion/RealESRGANv030/docs/Training.md deleted file mode 100644 index 77da5ea5763f7a6ab291ebc28afb13be37df3f50..0000000000000000000000000000000000000000 --- a/spaces/Nyari/Super-Resolution-Anime-Diffusion/RealESRGANv030/docs/Training.md +++ /dev/null @@ -1,271 +0,0 @@ -# :computer: How to Train/Finetune Real-ESRGAN - -- [Train Real-ESRGAN](#train-real-esrgan) - - [Overview](#overview) - - [Dataset Preparation](#dataset-preparation) - - [Train Real-ESRNet](#Train-Real-ESRNet) - - [Train Real-ESRGAN](#Train-Real-ESRGAN) -- [Finetune Real-ESRGAN on your own dataset](#Finetune-Real-ESRGAN-on-your-own-dataset) - - [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly) - - [Use paired training data](#use-your-own-paired-data) - -[English](Training.md) **|** [简体中文](Training_CN.md) - -## Train Real-ESRGAN - -### Overview - -The training has been divided into two stages. These two stages have the same data synthesis process and training pipeline, except for the loss functions. Specifically, - -1. We first train Real-ESRNet with L1 loss from the pre-trained model ESRGAN. -1. We then use the trained Real-ESRNet model as an initialization of the generator, and train the Real-ESRGAN with a combination of L1 loss, perceptual loss and GAN loss. - -### Dataset Preparation - -We use DF2K (DIV2K and Flickr2K) + OST datasets for our training. Only HR images are required.
-You can download from : - -1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip -2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar -3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip - -Here are steps for data preparation. - -#### Step 1: [Optional] Generate multi-scale images - -For the DF2K dataset, we use a multi-scale strategy, *i.e.*, we downsample HR images to obtain several Ground-Truth images with different scales.
-You can use the [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) script to generate multi-scale images.
-Note that this step can be omitted if you just want to have a fast try. - -```bash -python scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale -``` - -#### Step 2: [Optional] Crop to sub-images - -We then crop DF2K images into sub-images for faster IO and processing.
-This step is optional if your IO is enough or your disk space is limited. - -You can use the [scripts/extract_subimages.py](scripts/extract_subimages.py) script. Here is the example: - -```bash - python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200 -``` - -#### Step 3: Prepare a txt for meta information - -You need to prepare a txt file containing the image paths. The following are some examples in `meta_info_DF2Kmultiscale+OST_sub.txt` (As different users may have different sub-images partitions, this file is not suitable for your purpose and you need to prepare your own txt file): - -```txt -DF2K_HR_sub/000001_s001.png -DF2K_HR_sub/000001_s002.png -DF2K_HR_sub/000001_s003.png -... -``` - -You can use the [scripts/generate_meta_info.py](scripts/generate_meta_info.py) script to generate the txt file.
-You can merge several folders into one meta_info txt. Here is the example: - -```bash - python scripts/generate_meta_info.py --input datasets/DF2K/DF2K_HR datasets/DF2K/DF2K_multiscale --root datasets/DF2K datasets/DF2K --meta_info datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt -``` - -### Train Real-ESRNet - -1. Download pre-trained model [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) into `experiments/pretrained_models`. - ```bash - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models - ``` -1. Modify the content in the option file `options/train_realesrnet_x4plus.yml` accordingly: - ```yml - train: - name: DF2K+OST - type: RealESRGANDataset - dataroot_gt: datasets/DF2K # modify to the root path of your folder - meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt - io_backend: - type: disk - ``` -1. If you want to perform validation during training, uncomment those lines and modify accordingly: - ```yml - # Uncomment these for validation - # val: - # name: validation - # type: PairedImageDataset - # dataroot_gt: path_to_gt - # dataroot_lq: path_to_lq - # io_backend: - # type: disk - - ... - - # Uncomment these for validation - # validation settings - # val: - # val_freq: !!float 5e3 - # save_img: True - - # metrics: - # psnr: # metric name, can be arbitrary - # type: calculate_psnr - # crop_border: 4 - # test_y_channel: false - ``` -1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug - ``` - - Train with **a single GPU** in the *debug* mode: - ```bash - python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug - ``` -1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --auto_resume - ``` - - Train with **a single GPU**: - ```bash - python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume - ``` - -### Train Real-ESRGAN - -1. After the training of Real-ESRNet, you now have the file `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth`. If you need to specify the pre-trained path to other files, modify the `pretrain_network_g` value in the option file `train_realesrgan_x4plus.yml`. -1. Modify the option file `train_realesrgan_x4plus.yml` accordingly. Most modifications are similar to those listed above. -1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug - ``` - - Train with **a single GPU** in the *debug* mode: - ```bash - python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug - ``` -1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. - ```bash - CUDA_VISIBLE_DEVICES=0,1,2,3 \ - python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --auto_resume - ``` - - Train with **a single GPU**: - ```bash - python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume - ``` - -## Finetune Real-ESRGAN on your own dataset - -You can finetune Real-ESRGAN on your own dataset. Typically, the fine-tuning process can be divided into two cases: - -1. [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly) -1. [Use your own **paired** data](#Use-paired-training-data) - -### Generate degraded images on the fly - -Only high-resolution images are required. The low-quality images are generated with the degradation process described in Real-ESRGAN during training. - -**1. Prepare dataset** - -See [this section](#dataset-preparation) for more details. - -**2. Download pre-trained models** - -Download pre-trained models into `experiments/pretrained_models`. - -- *RealESRGAN_x4plus.pth*: - ```bash - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models - ``` - -- *RealESRGAN_x4plus_netD.pth*: - ```bash - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models - ``` - -**3. Finetune** - -Modify [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) accordingly, especially the `datasets` part: - -```yml -train: - name: DF2K+OST - type: RealESRGANDataset - dataroot_gt: datasets/DF2K # modify to the root path of your folder - meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt - io_backend: - type: disk -``` - -We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. - -```bash -CUDA_VISIBLE_DEVICES=0,1,2,3 \ -python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume -``` - -Finetune with **a single GPU**: -```bash -python realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume -``` - -### Use your own paired data - -You can also finetune RealESRGAN with your own paired data. It is more similar to fine-tuning ESRGAN. - -**1. Prepare dataset** - -Assume that you already have two folders: - -- **gt folder** (Ground-truth, high-resolution images): *datasets/DF2K/DIV2K_train_HR_sub* -- **lq folder** (Low quality, low-resolution images): *datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub* - -Then, you can prepare the meta_info txt file using the script [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py): - -```bash -python scripts/generate_meta_info_pairdata.py --input datasets/DF2K/DIV2K_train_HR_sub datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub --meta_info datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt -``` - -**2. Download pre-trained models** - -Download pre-trained models into `experiments/pretrained_models`. - -- *RealESRGAN_x4plus.pth* - ```bash - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models - ``` - -- *RealESRGAN_x4plus_netD.pth* - ```bash - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models - ``` - -**3. Finetune** - -Modify [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) accordingly, especially the `datasets` part: - -```yml -train: - name: DIV2K - type: RealESRGANPairedDataset - dataroot_gt: datasets/DF2K # modify to the root path of your folder - dataroot_lq: datasets/DF2K # modify to the root path of your folder - meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt # modify to your own generate meta info txt - io_backend: - type: disk -``` - -We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. - -```bash -CUDA_VISIBLE_DEVICES=0,1,2,3 \ -python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --launcher pytorch --auto_resume -``` - -Finetune with **a single GPU**: -```bash -python realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume -``` diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/rxf/__init__.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/rxf/__init__.py deleted file mode 100644 index b24cb6b797b4159c9862bab1f882ee6ae95614ab..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/rxf/__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 rxf_src # noqa diff --git a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/adaptive_span/adaptive_span_model.py b/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/adaptive_span/adaptive_span_model.py deleted file mode 100644 index d96c95b85dbcf29e9384cc6d8d9630d2489991b2..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/adaptive_span/adaptive_span_model.py +++ /dev/null @@ -1,263 +0,0 @@ -# Copyright (c) Facebook, Inc. and its 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 math - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from fairseq.modules.layer_norm import LayerNorm - -from .adaptive_span_attention import AdaptiveSpan - -# Size notations: -# B = batch_size, H = d_model, M = block_size, L = attn_span - - -def _skew(X, pad_value): - """shift every row 1 step to right""" - # X = B x M x L - B, M, L = X.size() - X = F.pad(X, (0, M + 1), value=pad_value) # B x M x (L+M+1) - X = X.view(B, -1) # B x ML+MM+M - X = X[:, :-M] # B x ML+MM - X = X.view(B, M, M + L) # B x M x L+M - return X - - -def _unskew(X): - """reverse _skew operation""" - # X = B x M x L+M - B, M, L = X.size() - L -= M - X = X.view(B, -1) # B x ML+MM - X = F.pad(X, (0, M)) # B x ML+MM+M - X = X.view(B, M, M + L + 1) # B x M x L+M+1 - X = X[:, :, :L] # B x M x L - return X - - -class SeqAttention(nn.Module): - """Sequential self-attention layer. - Each token will attend to its previous fixed number of steps. - Note that attention doesn't include the current step itself. - """ - - def __init__(self, d_model, n_head, attn_span, dropout, adapt_span_layer, **kargs): - nn.Module.__init__(self) - self.dropout = nn.Dropout(dropout) - self.d_model = d_model # size of a single head - self.attn_span = attn_span - self.adaptive_span = AdaptiveSpan( - attn_span=attn_span, - n_head=n_head, - adapt_span_layer=adapt_span_layer, - **kargs - ) - - def forward(self, query, key, value, key_pe): - # query size = B x M x H - # key, value sizes = B x (M+L) x H - - key, value, key_pe = self.adaptive_span.trim_memory(query, key, value, key_pe) - - # compute attention from context - # B x M (dest) x (M+L) (src) - attn_cont = torch.matmul(query, key.transpose(-1, -2)) - attn_cont = _unskew(attn_cont) # B x M x L - - # compute the effect of position embedding - attn_pos = torch.matmul(query, key_pe) # B x M x L_pos - attn = attn_cont + attn_pos - - attn = attn / math.sqrt(self.d_model) # B x M X L_pos - - attn = F.softmax(attn.float(), dim=-1).type_as(attn) - - # trim attention lengths according to the learned span - attn = self.adaptive_span(attn) - - attn = self.dropout(attn) # B x M X L_pos - - attn_cont = _skew(attn, 0) # B x M X (L+M) - out = torch.matmul(attn_cont, value) # B x M x H - return out - - def get_cache_size(self): - return self.adaptive_span.get_cache_size() - - -class MultiHeadSeqAttention(nn.Module): - def __init__(self, d_model, n_head, **kargs): - nn.Module.__init__(self) - assert d_model % n_head == 0 - self.n_head = n_head - self.head_dim = d_model // n_head - self.attn = SeqAttention(d_model=self.head_dim, n_head=n_head, **kargs) - self.proj_query = nn.Linear(d_model, d_model, bias=False) - nn.init.xavier_normal_(self.proj_query.weight) - self.proj_out = nn.Linear(d_model, d_model, bias=False) - nn.init.xavier_normal_(self.proj_out.weight) - self.proj_val = nn.Linear(d_model, d_model, bias=False) - nn.init.xavier_normal_(self.proj_val.weight) - self.proj_key = nn.Linear(d_model, d_model, bias=False) - nn.init.xavier_normal_(self.proj_key.weight) - - def head_reshape(self, x): - K = self.n_head - D = self.head_dim - x = x.view(x.size()[:-1] + (K, D)) # B x (M+L) x K x D - x = x.transpose(1, 2).contiguous() # B x K x (M+L) x D - x = x.view(-1, x.size(-2), x.size(-1)) # B_K x (M+L) x D - return x - - def forward(self, query, key, value, key_pe): - B = query.size(0) - K = self.n_head - D = self.head_dim - M = query.size(1) - - query = self.proj_query(query) - query = self.head_reshape(query) - value = self.proj_val(value) - value = self.head_reshape(value) - key = self.proj_key(key) - key = self.head_reshape(key) - - out = self.attn(query, key, value, key_pe) # B_K x M x D - out = out.view(B, K, M, D) # B x K x M x D - out = out.transpose(1, 2).contiguous() # B x M x K x D - out = out.view(B, M, -1) # B x M x K_D - out = self.proj_out(out) - return out - - -class FeedForwardLayer(nn.Module): - def __init__(self, d_model, d_inner, dropout, **kargs): - nn.Module.__init__(self) - self.fc1 = nn.Linear(d_model, d_inner) - self.fc2 = nn.Linear(d_inner, d_model) - nn.init.xavier_uniform_(self.fc1.weight) - nn.init.xavier_uniform_(self.fc2.weight) - self.dropout = nn.Dropout(dropout) - - def forward(self, h): - h1 = F.relu(self.fc1(h)) - h1 = self.dropout(h1) - h2 = self.fc2(h1) - return h2 - - -class TransformerSeqLayer(nn.Module): - def __init__(self, d_model, **kargs): - nn.Module.__init__(self) - self.attn = MultiHeadSeqAttention(d_model=d_model, **kargs) - self.norm1 = LayerNorm(d_model) - self.ff = FeedForwardLayer(d_model=d_model, **kargs) - self.norm2 = LayerNorm(d_model) - - def forward(self, h, h_cache, key_pe): - # h = B x M x H - # h_cache = B x L x H - h_all = torch.cat([h_cache, h], dim=1) # B x (M+L) x H - attn_out = self.attn(h, h_all, h_all, key_pe) - h = self.norm1(h + attn_out) # B x M x H - if self.ff is not None: - ff_out = self.ff(h) - out = self.norm2(h + ff_out) # B x M x H - else: - out = h - return out - - def get_cache_size(self): - return self.attn.attn.get_cache_size() - - -class TransformerSeq(nn.Module): - def __init__( - self, - vocab_size, - d_model, - n_head, - n_layer, - attn_span, - emb_dropout, - aux_loss_scaler, - adapt_span_layer, - **kargs - ): - nn.Module.__init__(self) - # token embeddings - self.in_emb = nn.Embedding(vocab_size, d_model) - nn.init.normal_(self.in_emb.weight, mean=0, std=d_model ** -0.5) - self.out_emb = nn.Linear(d_model, vocab_size) - self.aux_loss_scaler = aux_loss_scaler - if emb_dropout > 0: - self.emb_dropout = nn.Dropout(emb_dropout) - else: - self.emb_dropout = None - # position embeddings - self.key_pe = nn.Parameter(torch.randn(1, d_model // n_head, attn_span)) - - self.layers = nn.ModuleList() - self.layers.extend( - TransformerSeqLayer( - d_model=d_model, - n_head=n_head, - attn_span=attn_span, - adapt_span_layer=adapt_span_layer, - **kargs - ) - for _ in range(n_layer) - ) - - def forward(self, x, h_cache, target=None): - # x size = B x M - block_size = x.size(1) - h = self.in_emb(x) # B x M x H - if self.emb_dropout is not None: - h = self.emb_dropout(h) - - h_cache_next = [] - for l, layer in enumerate(self.layers): - cache_size = layer.attn.attn.get_cache_size() - if cache_size > block_size: - h_cache_next_l = torch.cat( - [h_cache[l][:, -cache_size + block_size :, :], h], dim=1 - ).detach() - else: - h_cache_next_l = h[:, -cache_size:, :].detach() - h_cache_next.append(h_cache_next_l) - h = layer(h, h_cache[l], self.key_pe) # B x M x H - - if self.emb_dropout is not None: - h = self.emb_dropout(h) - - out = F.log_softmax(self.out_emb(h).float(), dim=-1).type_as(h) - dummy_loss = None - - return out, h_cache_next, dummy_loss - - def get_aux_loss(self): - loss = 0.0 - for layer in self.layers: - loss += layer.attn.attn.adaptive_span.get_loss() - return self.aux_loss_scaler * loss - - def get_current_max_span(self): - max_span = 0.0 - for layer in self.layers: - max_span = max( - max_span, layer.attn.attn.adaptive_span.get_current_max_span() - ) - return max_span - - def get_current_avg_span(self): - avg_span = 0.0 - for layer in self.layers: - avg_span += layer.attn.attn.adaptive_span.get_current_avg_span() - return avg_span / len(self.layers) diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_synthesis/preprocessing/__init__.py b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_synthesis/preprocessing/__init__.py deleted file mode 100644 index 6264236915a7269a4d920ee8213004374dd86a9a..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/speech_synthesis/preprocessing/__init__.py +++ /dev/null @@ -1,4 +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. diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/detectron2/modeling/mmdet_wrapper.py b/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/detectron2/modeling/mmdet_wrapper.py deleted file mode 100644 index 386e92960511a782f48ec9350d19c3851e43849f..0000000000000000000000000000000000000000 --- a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/third_party/CenterNet2/detectron2/modeling/mmdet_wrapper.py +++ /dev/null @@ -1,274 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import itertools -import logging -import numpy as np -from collections import OrderedDict -from collections.abc import Mapping -from typing import Dict, List, Optional, Tuple, Union -import torch -from omegaconf import DictConfig, OmegaConf -from torch import Tensor, nn - -from detectron2.layers import ShapeSpec -from detectron2.structures import BitMasks, Boxes, ImageList, Instances -from detectron2.utils.events import get_event_storage - -from .backbone import Backbone - -logger = logging.getLogger(__name__) - - -def _to_container(cfg): - """ - mmdet will assert the type of dict/list. - So convert omegaconf objects to dict/list. - """ - if isinstance(cfg, DictConfig): - cfg = OmegaConf.to_container(cfg, resolve=True) - from mmcv.utils import ConfigDict - - return ConfigDict(cfg) - - -class MMDetBackbone(Backbone): - """ - Wrapper of mmdetection backbones to use in detectron2. - - mmdet backbones produce list/tuple of tensors, while detectron2 backbones - produce a dict of tensors. This class wraps the given backbone to produce - output in detectron2's convention, so it can be used in place of detectron2 - backbones. - """ - - def __init__( - self, - backbone: Union[nn.Module, Mapping], - neck: Union[nn.Module, Mapping, None] = None, - *, - output_shapes: List[ShapeSpec], - output_names: Optional[List[str]] = None, - ): - """ - Args: - backbone: either a backbone module or a mmdet config dict that defines a - backbone. The backbone takes a 4D image tensor and returns a - sequence of tensors. - neck: either a backbone module or a mmdet config dict that defines a - neck. The neck takes outputs of backbone and returns a - sequence of tensors. If None, no neck is used. - pretrained_backbone: defines the backbone weights that can be loaded by - mmdet, such as "torchvision://resnet50". - output_shapes: shape for every output of the backbone (or neck, if given). - stride and channels are often needed. - output_names: names for every output of the backbone (or neck, if given). - By default, will use "out0", "out1", ... - """ - super().__init__() - if isinstance(backbone, Mapping): - from mmdet.models import build_backbone - - backbone = build_backbone(_to_container(backbone)) - self.backbone = backbone - - if isinstance(neck, Mapping): - from mmdet.models import build_neck - - neck = build_neck(_to_container(neck)) - self.neck = neck - - # "Neck" weights, if any, are part of neck itself. This is the interface - # of mmdet so we follow it. Reference: - # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/two_stage.py - logger.info("Initializing mmdet backbone weights...") - self.backbone.init_weights() - # train() in mmdet modules is non-trivial, and has to be explicitly - # called. Reference: - # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/backbones/resnet.py - self.backbone.train() - if self.neck is not None: - logger.info("Initializing mmdet neck weights ...") - if isinstance(self.neck, nn.Sequential): - for m in self.neck: - m.init_weights() - else: - self.neck.init_weights() - self.neck.train() - - self._output_shapes = output_shapes - if not output_names: - output_names = [f"out{i}" for i in range(len(output_shapes))] - self._output_names = output_names - - def forward(self, x) -> Dict[str, Tensor]: - outs = self.backbone(x) - if self.neck is not None: - outs = self.neck(outs) - assert isinstance( - outs, (list, tuple) - ), "mmdet backbone should return a list/tuple of tensors!" - if len(outs) != len(self._output_shapes): - raise ValueError( - "Length of output_shapes does not match outputs from the mmdet backbone: " - f"{len(outs)} != {len(self._output_shapes)}" - ) - return {k: v for k, v in zip(self._output_names, outs)} - - def output_shape(self) -> Dict[str, ShapeSpec]: - return {k: v for k, v in zip(self._output_names, self._output_shapes)} - - -class MMDetDetector(nn.Module): - """ - Wrapper of a mmdetection detector model, for detection and instance segmentation. - Input/output formats of this class follow detectron2's convention, so a - mmdetection model can be trained and evaluated in detectron2. - """ - - def __init__( - self, - detector: Union[nn.Module, Mapping], - *, - # Default is 32 regardless of model: - # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets - size_divisibility=32, - pixel_mean: Tuple[float], - pixel_std: Tuple[float], - ): - """ - Args: - detector: a mmdet detector, or a mmdet config dict that defines a detector. - size_divisibility: pad input images to multiple of this number - pixel_mean: per-channel mean to normalize input image - pixel_std: per-channel stddev to normalize input image - """ - super().__init__() - if isinstance(detector, Mapping): - from mmdet.models import build_detector - - detector = build_detector(_to_container(detector)) - self.detector = detector - self.size_divisibility = size_divisibility - - self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False) - self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False) - assert ( - self.pixel_mean.shape == self.pixel_std.shape - ), f"{self.pixel_mean} and {self.pixel_std} have different shapes!" - - def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]): - images = [x["image"].to(self.device) for x in batched_inputs] - images = [(x - self.pixel_mean) / self.pixel_std for x in images] - images = ImageList.from_tensors(images, size_divisibility=self.size_divisibility).tensor - metas = [] - rescale = {"height" in x for x in batched_inputs} - if len(rescale) != 1: - raise ValueError("Some inputs have original height/width, but some don't!") - rescale = list(rescale)[0] - output_shapes = [] - for input in batched_inputs: - meta = {} - c, h, w = input["image"].shape - meta["img_shape"] = meta["ori_shape"] = (h, w, c) - if rescale: - scale_factor = np.array( - [w / input["width"], h / input["height"]] * 2, dtype="float32" - ) - ori_shape = (input["height"], input["width"]) - output_shapes.append(ori_shape) - meta["ori_shape"] = ori_shape + (c,) - else: - scale_factor = 1.0 - output_shapes.append((h, w)) - meta["scale_factor"] = scale_factor - meta["flip"] = False - padh, padw = images.shape[-2:] - meta["pad_shape"] = (padh, padw, c) - metas.append(meta) - - if self.training: - gt_instances = [x["instances"].to(self.device) for x in batched_inputs] - if gt_instances[0].has("gt_masks"): - from mmdet.core import PolygonMasks as mm_PolygonMasks, BitmapMasks as mm_BitMasks - - def convert_mask(m, shape): - # mmdet mask format - if isinstance(m, BitMasks): - return mm_BitMasks(m.tensor.cpu().numpy(), shape[0], shape[1]) - else: - return mm_PolygonMasks(m.polygons, shape[0], shape[1]) - - gt_masks = [convert_mask(x.gt_masks, x.image_size) for x in gt_instances] - losses_and_metrics = self.detector.forward_train( - images, - metas, - [x.gt_boxes.tensor for x in gt_instances], - [x.gt_classes for x in gt_instances], - gt_masks=gt_masks, - ) - else: - losses_and_metrics = self.detector.forward_train( - images, - metas, - [x.gt_boxes.tensor for x in gt_instances], - [x.gt_classes for x in gt_instances], - ) - return _parse_losses(losses_and_metrics) - else: - results = self.detector.simple_test(images, metas, rescale=rescale) - results = [ - {"instances": _convert_mmdet_result(r, shape)} - for r, shape in zip(results, output_shapes) - ] - return results - - @property - def device(self): - return self.pixel_mean.device - - -# Reference: show_result() in -# https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py -def _convert_mmdet_result(result, shape: Tuple[int, int]) -> Instances: - if isinstance(result, tuple): - bbox_result, segm_result = result - if isinstance(segm_result, tuple): - segm_result = segm_result[0] - else: - bbox_result, segm_result = result, None - - bboxes = torch.from_numpy(np.vstack(bbox_result)) # Nx5 - bboxes, scores = bboxes[:, :4], bboxes[:, -1] - labels = [ - torch.full((bbox.shape[0],), i, dtype=torch.int32) for i, bbox in enumerate(bbox_result) - ] - labels = torch.cat(labels) - inst = Instances(shape) - inst.pred_boxes = Boxes(bboxes) - inst.scores = scores - inst.pred_classes = labels - - if segm_result is not None and len(labels) > 0: - segm_result = list(itertools.chain(*segm_result)) - segm_result = [torch.from_numpy(x) if isinstance(x, np.ndarray) else x for x in segm_result] - segm_result = torch.stack(segm_result, dim=0) - inst.pred_masks = segm_result - return inst - - -# reference: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py -def _parse_losses(losses: Dict[str, Tensor]) -> Dict[str, Tensor]: - log_vars = OrderedDict() - for loss_name, loss_value in losses.items(): - if isinstance(loss_value, torch.Tensor): - log_vars[loss_name] = loss_value.mean() - elif isinstance(loss_value, list): - log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value) - else: - raise TypeError(f"{loss_name} is not a tensor or list of tensors") - - if "loss" not in loss_name: - # put metrics to storage; don't return them - storage = get_event_storage() - value = log_vars.pop(loss_name).cpu().item() - storage.put_scalar(loss_name, value) - return log_vars diff --git a/spaces/OpenMotionLab/MotionGPT/mGPT/utils/easyconvert.py b/spaces/OpenMotionLab/MotionGPT/mGPT/utils/easyconvert.py deleted file mode 100644 index 248073783ec412b9089b195d61df94e6754a6bfe..0000000000000000000000000000000000000000 --- a/spaces/OpenMotionLab/MotionGPT/mGPT/utils/easyconvert.py +++ /dev/null @@ -1,84 +0,0 @@ -from .geometry_tools import * - - -def rep_to_rep(oldtype, newtype, rotations): - if newtype in ["matrix"]: - return to_matrix(oldtype, rotations) - - if oldtype in ["rotvec", "axisangle"]: - return axis_angle_to(newtype, rotations) - elif oldtype in ["matrix"]: - return matrix_to(newtype, rotations) - else: - raise NotImplementedError("Only rotvec and matrix are supported.") - -def nfeats_of(rottype): - if rottype in ["rotvec", "axisangle"]: - return 3 - elif rottype in ["rotquat", "quaternion"]: - return 4 - elif rottype in ["rot6d", "6drot", "rotation6d"]: - return 6 - elif rottype in ["rotmat"]: - return 9 - else: - return TypeError("This rotation type doesn't have features.") - - -def axis_angle_to(newtype, rotations): - if newtype in ["matrix"]: - rotations = axis_angle_to_matrix(rotations) - return rotations - elif newtype in ["rotmat"]: - rotations = axis_angle_to_matrix(rotations) - rotations = matrix_to("rotmat", rotations) - return rotations - elif newtype in ["rot6d", "6drot", "rotation6d"]: - rotations = axis_angle_to_matrix(rotations) - rotations = matrix_to("rot6d", rotations) - return rotations - elif newtype in ["rotquat", "quaternion"]: - rotations = axis_angle_to_quaternion(rotations) - return rotations - elif newtype in ["rotvec", "axisangle"]: - return rotations - else: - raise NotImplementedError - - -def matrix_to(newtype, rotations): - if newtype in ["matrix"]: - return rotations - if newtype in ["rotmat"]: - rotations = rotations.reshape((*rotations.shape[:-2], 9)) - return rotations - elif newtype in ["rot6d", "6drot", "rotation6d"]: - rotations = matrix_to_rotation_6d(rotations) - return rotations - elif newtype in ["rotquat", "quaternion"]: - rotations = matrix_to_quaternion(rotations) - return rotations - elif newtype in ["rotvec", "axisangle"]: - rotations = matrix_to_axis_angle(rotations) - return rotations - else: - raise NotImplementedError - - -def to_matrix(oldtype, rotations): - if oldtype in ["matrix"]: - return rotations - if oldtype in ["rotmat"]: - rotations = rotations.reshape((*rotations.shape[:-2], 3, 3)) - return rotations - elif oldtype in ["rot6d", "6drot", "rotation6d"]: - rotations = rotation_6d_to_matrix(rotations) - return rotations - elif oldtype in ["rotquat", "quaternion"]: - rotations = quaternion_to_matrix(rotations) - return rotations - elif oldtype in ["rotvec", "axisangle"]: - rotations = axis_angle_to_matrix(rotations) - return rotations - else: - raise NotImplementedError diff --git a/spaces/OpenMotionLab/MotionGPT/pyrender/pyrender/scene.py b/spaces/OpenMotionLab/MotionGPT/pyrender/pyrender/scene.py deleted file mode 100644 index 2fe057ec66f52f2dd9c1363aacf72a7c6cec4e6c..0000000000000000000000000000000000000000 --- a/spaces/OpenMotionLab/MotionGPT/pyrender/pyrender/scene.py +++ /dev/null @@ -1,585 +0,0 @@ -"""Scenes, conforming to the glTF 2.0 standards as specified in -https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-scene - -Author: Matthew Matl -""" -import numpy as np -import networkx as nx -import trimesh - -from .mesh import Mesh -from .camera import Camera -from .light import Light, PointLight, DirectionalLight, SpotLight -from .node import Node -from .utils import format_color_vector - - -class Scene(object): - """A hierarchical scene graph. - - Parameters - ---------- - nodes : list of :class:`Node` - The set of all nodes in the scene. - bg_color : (4,) float, optional - Background color of scene. - ambient_light : (3,) float, optional - Color of ambient light. Defaults to no ambient light. - name : str, optional - The user-defined name of this object. - """ - - def __init__(self, - nodes=None, - bg_color=None, - ambient_light=None, - name=None): - - if bg_color is None: - bg_color = np.ones(4) - else: - bg_color = format_color_vector(bg_color, 4) - - if ambient_light is None: - ambient_light = np.zeros(3) - - if nodes is None: - nodes = set() - self._nodes = set() # Will be added at the end of this function - - self.bg_color = bg_color - self.ambient_light = ambient_light - self.name = name - - self._name_to_nodes = {} - self._obj_to_nodes = {} - self._obj_name_to_nodes = {} - self._mesh_nodes = set() - self._point_light_nodes = set() - self._spot_light_nodes = set() - self._directional_light_nodes = set() - self._camera_nodes = set() - self._main_camera_node = None - self._bounds = None - - # Transform tree - self._digraph = nx.DiGraph() - self._digraph.add_node('world') - self._path_cache = {} - - # Find root nodes and add them - if len(nodes) > 0: - node_parent_map = {n: None for n in nodes} - for node in nodes: - for child in node.children: - if node_parent_map[child] is not None: - raise ValueError('Nodes may not have more than ' - 'one parent') - node_parent_map[child] = node - for node in node_parent_map: - if node_parent_map[node] is None: - self.add_node(node) - - @property - def name(self): - """str : The user-defined name of this object. - """ - return self._name - - @name.setter - def name(self, value): - if value is not None: - value = str(value) - self._name = value - - @property - def nodes(self): - """set of :class:`Node` : Set of nodes in the scene. - """ - return self._nodes - - @property - def bg_color(self): - """(3,) float : The scene background color. - """ - return self._bg_color - - @bg_color.setter - def bg_color(self, value): - if value is None: - value = np.ones(4) - else: - value = format_color_vector(value, 4) - self._bg_color = value - - @property - def ambient_light(self): - """(3,) float : The ambient light in the scene. - """ - return self._ambient_light - - @ambient_light.setter - def ambient_light(self, value): - if value is None: - value = np.zeros(3) - else: - value = format_color_vector(value, 3) - self._ambient_light = value - - @property - def meshes(self): - """set of :class:`Mesh` : The meshes in the scene. - """ - return set([n.mesh for n in self.mesh_nodes]) - - @property - def mesh_nodes(self): - """set of :class:`Node` : The nodes containing meshes. - """ - return self._mesh_nodes - - @property - def lights(self): - """set of :class:`Light` : The lights in the scene. - """ - return self.point_lights | self.spot_lights | self.directional_lights - - @property - def light_nodes(self): - """set of :class:`Node` : The nodes containing lights. - """ - return (self.point_light_nodes | self.spot_light_nodes | - self.directional_light_nodes) - - @property - def point_lights(self): - """set of :class:`PointLight` : The point lights in the scene. - """ - return set([n.light for n in self.point_light_nodes]) - - @property - def point_light_nodes(self): - """set of :class:`Node` : The nodes containing point lights. - """ - return self._point_light_nodes - - @property - def spot_lights(self): - """set of :class:`SpotLight` : The spot lights in the scene. - """ - return set([n.light for n in self.spot_light_nodes]) - - @property - def spot_light_nodes(self): - """set of :class:`Node` : The nodes containing spot lights. - """ - return self._spot_light_nodes - - @property - def directional_lights(self): - """set of :class:`DirectionalLight` : The directional lights in - the scene. - """ - return set([n.light for n in self.directional_light_nodes]) - - @property - def directional_light_nodes(self): - """set of :class:`Node` : The nodes containing directional lights. - """ - return self._directional_light_nodes - - @property - def cameras(self): - """set of :class:`Camera` : The cameras in the scene. - """ - return set([n.camera for n in self.camera_nodes]) - - @property - def camera_nodes(self): - """set of :class:`Node` : The nodes containing cameras in the scene. - """ - return self._camera_nodes - - @property - def main_camera_node(self): - """set of :class:`Node` : The node containing the main camera in the - scene. - """ - return self._main_camera_node - - @main_camera_node.setter - def main_camera_node(self, value): - if value not in self.nodes: - raise ValueError('New main camera node must already be in scene') - self._main_camera_node = value - - @property - def bounds(self): - """(2,3) float : The axis-aligned bounds of the scene. - """ - if self._bounds is None: - # Compute corners - corners = [] - for mesh_node in self.mesh_nodes: - mesh = mesh_node.mesh - pose = self.get_pose(mesh_node) - corners_local = trimesh.bounds.corners(mesh.bounds) - corners_world = pose[:3,:3].dot(corners_local.T).T + pose[:3,3] - corners.append(corners_world) - if len(corners) == 0: - self._bounds = np.zeros((2,3)) - else: - corners = np.vstack(corners) - self._bounds = np.array([np.min(corners, axis=0), - np.max(corners, axis=0)]) - return self._bounds - - @property - def centroid(self): - """(3,) float : The centroid of the scene's axis-aligned bounding box - (AABB). - """ - return np.mean(self.bounds, axis=0) - - @property - def extents(self): - """(3,) float : The lengths of the axes of the scene's AABB. - """ - return np.diff(self.bounds, axis=0).reshape(-1) - - @property - def scale(self): - """(3,) float : The length of the diagonal of the scene's AABB. - """ - return np.linalg.norm(self.extents) - - def add(self, obj, name=None, pose=None, - parent_node=None, parent_name=None): - """Add an object (mesh, light, or camera) to the scene. - - Parameters - ---------- - obj : :class:`Mesh`, :class:`Light`, or :class:`Camera` - The object to add to the scene. - name : str - A name for the new node to be created. - pose : (4,4) float - The local pose of this node relative to its parent node. - parent_node : :class:`Node` - The parent of this Node. If None, the new node is a root node. - parent_name : str - The name of the parent node, can be specified instead of - `parent_node`. - - Returns - ------- - node : :class:`Node` - The newly-created and inserted node. - """ - if isinstance(obj, Mesh): - node = Node(name=name, matrix=pose, mesh=obj) - elif isinstance(obj, Light): - node = Node(name=name, matrix=pose, light=obj) - elif isinstance(obj, Camera): - node = Node(name=name, matrix=pose, camera=obj) - else: - raise TypeError('Unrecognized object type') - - if parent_node is None and parent_name is not None: - parent_nodes = self.get_nodes(name=parent_name) - if len(parent_nodes) == 0: - raise ValueError('No parent node with name {} found' - .format(parent_name)) - elif len(parent_nodes) > 1: - raise ValueError('More than one parent node with name {} found' - .format(parent_name)) - parent_node = list(parent_nodes)[0] - - self.add_node(node, parent_node=parent_node) - - return node - - def get_nodes(self, node=None, name=None, obj=None, obj_name=None): - """Search for existing nodes. Only nodes matching all specified - parameters is returned, or None if no such node exists. - - Parameters - ---------- - node : :class:`Node`, optional - If present, returns this node if it is in the scene. - name : str - A name for the Node. - obj : :class:`Mesh`, :class:`Light`, or :class:`Camera` - An object that is attached to the node. - obj_name : str - The name of an object that is attached to the node. - - Returns - ------- - nodes : set of :class:`.Node` - The nodes that match all query terms. - """ - if node is not None: - if node in self.nodes: - return set([node]) - else: - return set() - nodes = set(self.nodes) - if name is not None: - matches = set() - if name in self._name_to_nodes: - matches = self._name_to_nodes[name] - nodes = nodes & matches - if obj is not None: - matches = set() - if obj in self._obj_to_nodes: - matches = self._obj_to_nodes[obj] - nodes = nodes & matches - if obj_name is not None: - matches = set() - if obj_name in self._obj_name_to_nodes: - matches = self._obj_name_to_nodes[obj_name] - nodes = nodes & matches - - return nodes - - def add_node(self, node, parent_node=None): - """Add a Node to the scene. - - Parameters - ---------- - node : :class:`Node` - The node to be added. - parent_node : :class:`Node` - The parent of this Node. If None, the new node is a root node. - """ - if node in self.nodes: - raise ValueError('Node already in scene') - self.nodes.add(node) - - # Add node to sets - if node.name is not None: - if node.name not in self._name_to_nodes: - self._name_to_nodes[node.name] = set() - self._name_to_nodes[node.name].add(node) - for obj in [node.mesh, node.camera, node.light]: - if obj is not None: - if obj not in self._obj_to_nodes: - self._obj_to_nodes[obj] = set() - self._obj_to_nodes[obj].add(node) - if obj.name is not None: - if obj.name not in self._obj_name_to_nodes: - self._obj_name_to_nodes[obj.name] = set() - self._obj_name_to_nodes[obj.name].add(node) - if node.mesh is not None: - self._mesh_nodes.add(node) - if node.light is not None: - if isinstance(node.light, PointLight): - self._point_light_nodes.add(node) - if isinstance(node.light, SpotLight): - self._spot_light_nodes.add(node) - if isinstance(node.light, DirectionalLight): - self._directional_light_nodes.add(node) - if node.camera is not None: - self._camera_nodes.add(node) - if self._main_camera_node is None: - self._main_camera_node = node - - if parent_node is None: - parent_node = 'world' - elif parent_node not in self.nodes: - raise ValueError('Parent node must already be in scene') - elif node not in parent_node.children: - parent_node.children.append(node) - - # Create node in graph - self._digraph.add_node(node) - self._digraph.add_edge(node, parent_node) - - # Iterate over children - for child in node.children: - self.add_node(child, node) - - self._path_cache = {} - self._bounds = None - - def has_node(self, node): - """Check if a node is already in the scene. - - Parameters - ---------- - node : :class:`Node` - The node to be checked. - - Returns - ------- - has_node : bool - True if the node is already in the scene and false otherwise. - """ - return node in self.nodes - - def remove_node(self, node): - """Remove a node and all its children from the scene. - - Parameters - ---------- - node : :class:`Node` - The node to be removed. - """ - # Disconnect self from parent who is staying in the graph - parent = list(self._digraph.neighbors(node))[0] - self._remove_node(node) - if isinstance(parent, Node): - parent.children.remove(node) - self._path_cache = {} - self._bounds = None - - def get_pose(self, node): - """Get the world-frame pose of a node in the scene. - - Parameters - ---------- - node : :class:`Node` - The node to find the pose of. - - Returns - ------- - pose : (4,4) float - The transform matrix for this node. - """ - if node not in self.nodes: - raise ValueError('Node must already be in scene') - if node in self._path_cache: - path = self._path_cache[node] - else: - # Get path from from_frame to to_frame - path = nx.shortest_path(self._digraph, node, 'world') - self._path_cache[node] = path - - # Traverse from from_node to to_node - pose = np.eye(4) - for n in path[:-1]: - pose = np.dot(n.matrix, pose) - - return pose - - def set_pose(self, node, pose): - """Set the local-frame pose of a node in the scene. - - Parameters - ---------- - node : :class:`Node` - The node to set the pose of. - pose : (4,4) float - The pose to set the node to. - """ - if node not in self.nodes: - raise ValueError('Node must already be in scene') - node._matrix = pose - if node.mesh is not None: - self._bounds = None - - def clear(self): - """Clear out all nodes to form an empty scene. - """ - self._nodes = set() - - self._name_to_nodes = {} - self._obj_to_nodes = {} - self._obj_name_to_nodes = {} - self._mesh_nodes = set() - self._point_light_nodes = set() - self._spot_light_nodes = set() - self._directional_light_nodes = set() - self._camera_nodes = set() - self._main_camera_node = None - self._bounds = None - - # Transform tree - self._digraph = nx.DiGraph() - self._digraph.add_node('world') - self._path_cache = {} - - def _remove_node(self, node): - """Remove a node and all its children from the scene. - - Parameters - ---------- - node : :class:`Node` - The node to be removed. - """ - - # Remove self from nodes - self.nodes.remove(node) - - # Remove children - for child in node.children: - self._remove_node(child) - - # Remove self from the graph - self._digraph.remove_node(node) - - # Remove from maps - if node.name in self._name_to_nodes: - self._name_to_nodes[node.name].remove(node) - if len(self._name_to_nodes[node.name]) == 0: - self._name_to_nodes.pop(node.name) - for obj in [node.mesh, node.camera, node.light]: - if obj is None: - continue - self._obj_to_nodes[obj].remove(node) - if len(self._obj_to_nodes[obj]) == 0: - self._obj_to_nodes.pop(obj) - if obj.name is not None: - self._obj_name_to_nodes[obj.name].remove(node) - if len(self._obj_name_to_nodes[obj.name]) == 0: - self._obj_name_to_nodes.pop(obj.name) - if node.mesh is not None: - self._mesh_nodes.remove(node) - if node.light is not None: - if isinstance(node.light, PointLight): - self._point_light_nodes.remove(node) - if isinstance(node.light, SpotLight): - self._spot_light_nodes.remove(node) - if isinstance(node.light, DirectionalLight): - self._directional_light_nodes.remove(node) - if node.camera is not None: - self._camera_nodes.remove(node) - if self._main_camera_node == node: - if len(self._camera_nodes) > 0: - self._main_camera_node = next(iter(self._camera_nodes)) - else: - self._main_camera_node = None - - @staticmethod - def from_trimesh_scene(trimesh_scene, - bg_color=None, ambient_light=None): - """Create a :class:`.Scene` from a :class:`trimesh.scene.scene.Scene`. - - Parameters - ---------- - trimesh_scene : :class:`trimesh.scene.scene.Scene` - Scene with :class:~`trimesh.base.Trimesh` objects. - bg_color : (4,) float - Background color for the created scene. - ambient_light : (3,) float or None - Ambient light in the scene. - - Returns - ------- - scene_pr : :class:`Scene` - A scene containing the same geometry as the trimesh scene. - """ - # convert trimesh geometries to pyrender geometries - geometries = {name: Mesh.from_trimesh(geom) - for name, geom in trimesh_scene.geometry.items()} - - # create the pyrender scene object - scene_pr = Scene(bg_color=bg_color, ambient_light=ambient_light) - - # add every node with geometry to the pyrender scene - for node in trimesh_scene.graph.nodes_geometry: - pose, geom_name = trimesh_scene.graph[node] - scene_pr.add(geometries[geom_name], pose=pose) - - return scene_pr diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/cnn/vgg.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/cnn/vgg.py deleted file mode 100644 index 8778b649561a45a9652b1a15a26c2d171e58f3e1..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/cnn/vgg.py +++ /dev/null @@ -1,175 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import logging - -import torch.nn as nn - -from .utils import constant_init, kaiming_init, normal_init - - -def conv3x3(in_planes, out_planes, dilation=1): - """3x3 convolution with padding.""" - return nn.Conv2d( - in_planes, - out_planes, - kernel_size=3, - padding=dilation, - dilation=dilation) - - -def make_vgg_layer(inplanes, - planes, - num_blocks, - dilation=1, - with_bn=False, - ceil_mode=False): - layers = [] - for _ in range(num_blocks): - layers.append(conv3x3(inplanes, planes, dilation)) - if with_bn: - layers.append(nn.BatchNorm2d(planes)) - layers.append(nn.ReLU(inplace=True)) - inplanes = planes - layers.append(nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=ceil_mode)) - - return layers - - -class VGG(nn.Module): - """VGG backbone. - - Args: - depth (int): Depth of vgg, from {11, 13, 16, 19}. - with_bn (bool): Use BatchNorm or not. - num_classes (int): number of classes for classification. - num_stages (int): VGG stages, normally 5. - dilations (Sequence[int]): Dilation of each stage. - out_indices (Sequence[int]): Output from which stages. - frozen_stages (int): Stages to be frozen (all param fixed). -1 means - not freezing any parameters. - bn_eval (bool): Whether to set BN layers as eval mode, namely, freeze - running stats (mean and var). - bn_frozen (bool): Whether to freeze weight and bias of BN layers. - """ - - arch_settings = { - 11: (1, 1, 2, 2, 2), - 13: (2, 2, 2, 2, 2), - 16: (2, 2, 3, 3, 3), - 19: (2, 2, 4, 4, 4) - } - - def __init__(self, - depth, - with_bn=False, - num_classes=-1, - num_stages=5, - dilations=(1, 1, 1, 1, 1), - out_indices=(0, 1, 2, 3, 4), - frozen_stages=-1, - bn_eval=True, - bn_frozen=False, - ceil_mode=False, - with_last_pool=True): - super(VGG, self).__init__() - if depth not in self.arch_settings: - raise KeyError(f'invalid depth {depth} for vgg') - assert num_stages >= 1 and num_stages <= 5 - stage_blocks = self.arch_settings[depth] - self.stage_blocks = stage_blocks[:num_stages] - assert len(dilations) == num_stages - assert max(out_indices) <= num_stages - - self.num_classes = num_classes - self.out_indices = out_indices - self.frozen_stages = frozen_stages - self.bn_eval = bn_eval - self.bn_frozen = bn_frozen - - self.inplanes = 3 - start_idx = 0 - vgg_layers = [] - self.range_sub_modules = [] - for i, num_blocks in enumerate(self.stage_blocks): - num_modules = num_blocks * (2 + with_bn) + 1 - end_idx = start_idx + num_modules - dilation = dilations[i] - planes = 64 * 2**i if i < 4 else 512 - vgg_layer = make_vgg_layer( - self.inplanes, - planes, - num_blocks, - dilation=dilation, - with_bn=with_bn, - ceil_mode=ceil_mode) - vgg_layers.extend(vgg_layer) - self.inplanes = planes - self.range_sub_modules.append([start_idx, end_idx]) - start_idx = end_idx - if not with_last_pool: - vgg_layers.pop(-1) - self.range_sub_modules[-1][1] -= 1 - self.module_name = 'features' - self.add_module(self.module_name, nn.Sequential(*vgg_layers)) - - if self.num_classes > 0: - self.classifier = nn.Sequential( - nn.Linear(512 * 7 * 7, 4096), - nn.ReLU(True), - nn.Dropout(), - nn.Linear(4096, 4096), - nn.ReLU(True), - nn.Dropout(), - nn.Linear(4096, num_classes), - ) - - def init_weights(self, pretrained=None): - if isinstance(pretrained, str): - logger = logging.getLogger() - from ..runner import load_checkpoint - load_checkpoint(self, pretrained, strict=False, logger=logger) - elif pretrained is None: - for m in self.modules(): - if isinstance(m, nn.Conv2d): - kaiming_init(m) - elif isinstance(m, nn.BatchNorm2d): - constant_init(m, 1) - elif isinstance(m, nn.Linear): - normal_init(m, std=0.01) - else: - raise TypeError('pretrained must be a str or None') - - def forward(self, x): - outs = [] - vgg_layers = getattr(self, self.module_name) - for i in range(len(self.stage_blocks)): - for j in range(*self.range_sub_modules[i]): - vgg_layer = vgg_layers[j] - x = vgg_layer(x) - if i in self.out_indices: - outs.append(x) - if self.num_classes > 0: - x = x.view(x.size(0), -1) - x = self.classifier(x) - outs.append(x) - if len(outs) == 1: - return outs[0] - else: - return tuple(outs) - - def train(self, mode=True): - super(VGG, self).train(mode) - if self.bn_eval: - for m in self.modules(): - if isinstance(m, nn.BatchNorm2d): - m.eval() - if self.bn_frozen: - for params in m.parameters(): - params.requires_grad = False - vgg_layers = getattr(self, self.module_name) - if mode and self.frozen_stages >= 0: - for i in range(self.frozen_stages): - for j in range(*self.range_sub_modules[i]): - mod = vgg_layers[j] - mod.eval() - for param in mod.parameters(): - param.requires_grad = False diff --git a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/ice-9/lineio.go b/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/ice-9/lineio.go deleted file mode 100644 index 0e7e67a10f9b74557f581e812901e118361d6d4a..0000000000000000000000000000000000000000 Binary files a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/ice-9/lineio.go and /dev/null differ diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/configs/_base_/models/emanet_r50-d8.py b/spaces/Pie31415/control-animation/annotator/uniformer/configs/_base_/models/emanet_r50-d8.py deleted file mode 100644 index 26adcd430926de0862204a71d345f2543167f27b..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/configs/_base_/models/emanet_r50-d8.py +++ /dev/null @@ -1,47 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='EncoderDecoder', - pretrained='open-mmlab://resnet50_v1c', - backbone=dict( - type='ResNetV1c', - depth=50, - num_stages=4, - out_indices=(0, 1, 2, 3), - dilations=(1, 1, 2, 4), - strides=(1, 2, 1, 1), - norm_cfg=norm_cfg, - norm_eval=False, - style='pytorch', - contract_dilation=True), - decode_head=dict( - type='EMAHead', - in_channels=2048, - in_index=3, - channels=256, - ema_channels=512, - num_bases=64, - num_stages=3, - momentum=0.1, - dropout_ratio=0.1, - num_classes=19, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - auxiliary_head=dict( - type='FCNHead', - in_channels=1024, - in_index=2, - channels=256, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=19, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), - # model training and testing settings - train_cfg=dict(), - test_cfg=dict(mode='whole')) diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/cnn/bricks/conv_ws.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/cnn/bricks/conv_ws.py deleted file mode 100644 index a3941e27874993418b3b5708d5a7485f175ff9c8..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/cnn/bricks/conv_ws.py +++ /dev/null @@ -1,148 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -import torch.nn as nn -import torch.nn.functional as F - -from .registry import CONV_LAYERS - - -def conv_ws_2d(input, - weight, - bias=None, - stride=1, - padding=0, - dilation=1, - groups=1, - eps=1e-5): - c_in = weight.size(0) - weight_flat = weight.view(c_in, -1) - mean = weight_flat.mean(dim=1, keepdim=True).view(c_in, 1, 1, 1) - std = weight_flat.std(dim=1, keepdim=True).view(c_in, 1, 1, 1) - weight = (weight - mean) / (std + eps) - return F.conv2d(input, weight, bias, stride, padding, dilation, groups) - - -@CONV_LAYERS.register_module('ConvWS') -class ConvWS2d(nn.Conv2d): - - def __init__(self, - in_channels, - out_channels, - kernel_size, - stride=1, - padding=0, - dilation=1, - groups=1, - bias=True, - eps=1e-5): - super(ConvWS2d, self).__init__( - in_channels, - out_channels, - kernel_size, - stride=stride, - padding=padding, - dilation=dilation, - groups=groups, - bias=bias) - self.eps = eps - - def forward(self, x): - return conv_ws_2d(x, self.weight, self.bias, self.stride, self.padding, - self.dilation, self.groups, self.eps) - - -@CONV_LAYERS.register_module(name='ConvAWS') -class ConvAWS2d(nn.Conv2d): - """AWS (Adaptive Weight Standardization) - - This is a variant of Weight Standardization - (https://arxiv.org/pdf/1903.10520.pdf) - It is used in DetectoRS to avoid NaN - (https://arxiv.org/pdf/2006.02334.pdf) - - Args: - in_channels (int): Number of channels in the input image - out_channels (int): Number of channels produced by the convolution - kernel_size (int or tuple): Size of the conv kernel - stride (int or tuple, optional): Stride of the convolution. Default: 1 - padding (int or tuple, optional): Zero-padding added to both sides of - the input. Default: 0 - dilation (int or tuple, optional): Spacing between kernel elements. - Default: 1 - groups (int, optional): Number of blocked connections from input - channels to output channels. Default: 1 - bias (bool, optional): If set True, adds a learnable bias to the - output. Default: True - """ - - def __init__(self, - in_channels, - out_channels, - kernel_size, - stride=1, - padding=0, - dilation=1, - groups=1, - bias=True): - super().__init__( - in_channels, - out_channels, - kernel_size, - stride=stride, - padding=padding, - dilation=dilation, - groups=groups, - bias=bias) - self.register_buffer('weight_gamma', - torch.ones(self.out_channels, 1, 1, 1)) - self.register_buffer('weight_beta', - torch.zeros(self.out_channels, 1, 1, 1)) - - def _get_weight(self, weight): - weight_flat = weight.view(weight.size(0), -1) - mean = weight_flat.mean(dim=1).view(-1, 1, 1, 1) - std = torch.sqrt(weight_flat.var(dim=1) + 1e-5).view(-1, 1, 1, 1) - weight = (weight - mean) / std - weight = self.weight_gamma * weight + self.weight_beta - return weight - - def forward(self, x): - weight = self._get_weight(self.weight) - return F.conv2d(x, weight, self.bias, self.stride, self.padding, - self.dilation, self.groups) - - def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, - missing_keys, unexpected_keys, error_msgs): - """Override default load function. - - AWS overrides the function _load_from_state_dict to recover - weight_gamma and weight_beta if they are missing. If weight_gamma and - weight_beta are found in the checkpoint, this function will return - after super()._load_from_state_dict. Otherwise, it will compute the - mean and std of the pretrained weights and store them in weight_beta - and weight_gamma. - """ - - self.weight_gamma.data.fill_(-1) - local_missing_keys = [] - super()._load_from_state_dict(state_dict, prefix, local_metadata, - strict, local_missing_keys, - unexpected_keys, error_msgs) - if self.weight_gamma.data.mean() > 0: - for k in local_missing_keys: - missing_keys.append(k) - return - weight = self.weight.data - weight_flat = weight.view(weight.size(0), -1) - mean = weight_flat.mean(dim=1).view(-1, 1, 1, 1) - std = torch.sqrt(weight_flat.var(dim=1) + 1e-5).view(-1, 1, 1, 1) - self.weight_beta.data.copy_(mean) - self.weight_gamma.data.copy_(std) - missing_gamma_beta = [ - k for k in local_missing_keys - if k.endswith('weight_gamma') or k.endswith('weight_beta') - ] - for k in missing_gamma_beta: - local_missing_keys.remove(k) - for k in local_missing_keys: - missing_keys.append(k) diff --git a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/structures/bounding_box.py b/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/structures/bounding_box.py deleted file mode 100644 index dc788f310d9539bc5d1720c2ab2808c3adf9397f..0000000000000000000000000000000000000000 --- a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/structures/bounding_box.py +++ /dev/null @@ -1,321 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -import torch - -# transpose -FLIP_LEFT_RIGHT = 0 -FLIP_TOP_BOTTOM = 1 - - -class BoxList(object): - """ - This class represents a set of bounding boxes. - The bounding boxes are represented as a Nx4 Tensor. - In order to uniquely determine the bounding boxes with respect - to an image, we also store the corresponding image dimensions. - They can contain extra information that is specific to each bounding box, such as - labels. - """ - - def __init__(self, bbox, image_size, mode="xyxy"): - device = bbox.device if isinstance(bbox, torch.Tensor) else torch.device("cpu") - # only do as_tensor if isn't a "no-op", because it hurts JIT tracing - if (not isinstance(bbox, torch.Tensor) - or bbox.dtype != torch.float32 or bbox.device != device): - bbox = torch.as_tensor(bbox, dtype=torch.float32, device=device) - if bbox.ndimension() != 2: - raise ValueError( - "bbox should have 2 dimensions, got {}".format(bbox.ndimension()) - ) - if bbox.size(-1) != 4: - raise ValueError( - "last dimenion of bbox should have a " - "size of 4, got {}".format(bbox.size(-1)) - ) - if mode not in ("xyxy", "xywh"): - raise ValueError("mode should be 'xyxy' or 'xywh'") - - self.bbox = bbox - self.size = image_size # (image_width, image_height) - self.mode = mode - self.extra_fields = {} - - # note: _jit_wrap/_jit_unwrap only work if the keys and the sizes don't change in between - def _jit_unwrap(self): - return (self.bbox,) + tuple(f for f in (self.get_field(field) - for field in sorted(self.fields())) - if isinstance(f, torch.Tensor)) - - def _jit_wrap(self, input_stream): - self.bbox = input_stream[0] - num_consumed = 1 - for f in sorted(self.fields()): - if isinstance(self.extra_fields[f], torch.Tensor): - self.extra_fields[f] = input_stream[num_consumed] - num_consumed += 1 - return self, input_stream[num_consumed:] - - def add_field(self, field, field_data): - self.extra_fields[field] = field_data - - def get_field(self, field): - return self.extra_fields[field] - - def has_field(self, field): - return field in self.extra_fields - - def fields(self): - return list(self.extra_fields.keys()) - - def _copy_extra_fields(self, bbox): - for k, v in bbox.extra_fields.items(): - self.extra_fields[k] = v - - def convert(self, mode): - if mode not in ("xyxy", "xywh"): - raise ValueError("mode should be 'xyxy' or 'xywh'") - if mode == self.mode: - return self - # we only have two modes, so don't need to check - # self.mode - xmin, ymin, xmax, ymax = self._split_into_xyxy() - if mode == "xyxy": - bbox = torch.cat((xmin, ymin, xmax, ymax), dim=-1) - bbox = BoxList(bbox, self.size, mode=mode) - else: - TO_REMOVE = 1 - # NOTE: explicitly specify dim to avoid tracing error in GPU - bbox = torch.cat( - (xmin, ymin, xmax - xmin + TO_REMOVE, ymax - ymin + TO_REMOVE), dim=1 - ) - bbox = BoxList(bbox, self.size, mode=mode) - bbox._copy_extra_fields(self) - return bbox - - def _split_into_xyxy(self): - if self.mode == "xyxy": - xmin, ymin, xmax, ymax = self.bbox.split(1, dim=-1) - return xmin, ymin, xmax, ymax - elif self.mode == "xywh": - TO_REMOVE = 1 - xmin, ymin, w, h = self.bbox.split(1, dim=-1) - return ( - xmin, - ymin, - xmin + (w - TO_REMOVE).clamp(min=0), - ymin + (h - TO_REMOVE).clamp(min=0), - ) - else: - raise RuntimeError("Should not be here") - - def resize(self, size, *args, **kwargs): - """ - Returns a resized copy of this bounding box - - :param size: The requested size in pixels, as a 2-tuple: - (width, height). - """ - - ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size)) - if ratios[0] == ratios[1]: - ratio = ratios[0] - scaled_box = self.bbox * ratio - bbox = BoxList(scaled_box, size, mode=self.mode) - # bbox._copy_extra_fields(self) - for k, v in self.extra_fields.items(): - if not isinstance(v, torch.Tensor): - v = v.resize(size, *args, **kwargs) - bbox.add_field(k, v) - return bbox - - ratio_width, ratio_height = ratios - xmin, ymin, xmax, ymax = self._split_into_xyxy() - scaled_xmin = xmin * ratio_width - scaled_xmax = xmax * ratio_width - scaled_ymin = ymin * ratio_height - scaled_ymax = ymax * ratio_height - scaled_box = torch.cat( - (scaled_xmin, scaled_ymin, scaled_xmax, scaled_ymax), dim=-1 - ) - bbox = BoxList(scaled_box, size, mode="xyxy") - # bbox._copy_extra_fields(self) - for k, v in self.extra_fields.items(): - if not isinstance(v, torch.Tensor): - v = v.resize(size, *args, **kwargs) - bbox.add_field(k, v) - - return bbox.convert(self.mode) - - def transpose(self, method): - """ - Transpose bounding box (flip or rotate in 90 degree steps) - :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, - :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, - :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`, - :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`. - """ - if method not in (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM): - raise NotImplementedError( - "Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented" - ) - - image_width, image_height = self.size - xmin, ymin, xmax, ymax = self._split_into_xyxy() - if method == FLIP_LEFT_RIGHT: - TO_REMOVE = 1 - transposed_xmin = image_width - xmax - TO_REMOVE - transposed_xmax = image_width - xmin - TO_REMOVE - transposed_ymin = ymin - transposed_ymax = ymax - elif method == FLIP_TOP_BOTTOM: - transposed_xmin = xmin - transposed_xmax = xmax - transposed_ymin = image_height - ymax - transposed_ymax = image_height - ymin - - transposed_boxes = torch.cat( - (transposed_xmin, transposed_ymin, transposed_xmax, transposed_ymax), dim=-1 - ) - bbox = BoxList(transposed_boxes, self.size, mode="xyxy") - # bbox._copy_extra_fields(self) - for k, v in self.extra_fields.items(): - if not isinstance(v, torch.Tensor): - v = v.transpose(method) - bbox.add_field(k, v) - return bbox.convert(self.mode) - - def crop(self, box): - """ - Cropss a rectangular region from this bounding box. The box is a - 4-tuple defining the left, upper, right, and lower pixel - coordinate. - """ - xmin, ymin, xmax, ymax = self._split_into_xyxy() - w, h = box[2] - box[0], box[3] - box[1] - cropped_xmin = (xmin - box[0]).clamp(min=0, max=w) - cropped_ymin = (ymin - box[1]).clamp(min=0, max=h) - cropped_xmax = (xmax - box[0]).clamp(min=0, max=w) - cropped_ymax = (ymax - box[1]).clamp(min=0, max=h) - - # TODO should I filter empty boxes here? - cropped_box = torch.cat( - (cropped_xmin, cropped_ymin, cropped_xmax, cropped_ymax), dim=-1 - ) - bbox = BoxList(cropped_box, (w, h), mode="xyxy") - # bbox._copy_extra_fields(self) - for k, v in self.extra_fields.items(): - if not isinstance(v, torch.Tensor): - v = v.crop(box) - bbox.add_field(k, v) - return bbox.convert(self.mode) - - # Tensor-like methods - - def to(self, device): - bbox = BoxList(self.bbox.to(device), self.size, self.mode) - for k, v in self.extra_fields.items(): - if hasattr(v, "to"): - v = v.to(device) - bbox.add_field(k, v) - return bbox - - def __getitem__(self, item): - bbox = BoxList(self.bbox[item], self.size, self.mode) - for k, v in self.extra_fields.items(): - bbox.add_field(k, v[item]) - return bbox - - def __len__(self): - return self.bbox.shape[0] - - def clip_to_image(self, remove_empty=True): - TO_REMOVE = 1 - x1s = self.bbox[:, 0].clamp(min=0, max=self.size[0] - TO_REMOVE) - y1s = self.bbox[:, 1].clamp(min=0, max=self.size[1] - TO_REMOVE) - x2s = self.bbox[:, 2].clamp(min=0, max=self.size[0] - TO_REMOVE) - y2s = self.bbox[:, 3].clamp(min=0, max=self.size[1] - TO_REMOVE) - self.bbox = torch.stack((x1s, y1s, x2s, y2s), dim=-1) - if remove_empty: - box = self.bbox - keep = (box[:, 3] > box[:, 1]) & (box[:, 2] > box[:, 0]) - return self[keep] - return self - - def area(self): - if self.mode == 'xyxy': - TO_REMOVE = 1 - box = self.bbox - area = (box[:, 2] - box[:, 0] + TO_REMOVE) * (box[:, 3] - box[:, 1] + TO_REMOVE) - elif self.mode == 'xywh': - box = self.bbox - area = box[:, 2] * box[:, 3] - else: - raise RuntimeError("Should not be here") - - return area - - def copy_with_fields(self, fields): - bbox = BoxList(self.bbox, self.size, self.mode) - if not isinstance(fields, (list, tuple)): - fields = [fields] - for field in fields: - bbox.add_field(field, self.get_field(field)) - return bbox - - def __repr__(self): - s = self.__class__.__name__ + "(" - s += "num_boxes={}, ".format(len(self)) - s += "image_width={}, ".format(self.size[0]) - s += "image_height={}, ".format(self.size[1]) - s += "mode={})".format(self.mode) - return s - - @staticmethod - def concate_box_list(list_of_boxes): - boxes = torch.cat([i.bbox for i in list_of_boxes], dim = 0) - extra_fields_keys = list(list_of_boxes[0].extra_fields.keys()) - extra_fields = {} - for key in extra_fields_keys: - extra_fields[key] = torch.cat([i.extra_fields[key] for i in list_of_boxes], dim = 0) - - final = list_of_boxes[0].copy_with_fields(extra_fields_keys) - - final.bbox = boxes - final.extra_fields = extra_fields - return final - -@torch.jit.unused -def _onnx_clip_boxes_to_image(boxes, size): - # type: (Tensor, Tuple[int, int]) - """ - Clip boxes so that they lie inside an image of size `size`. - Clip's min max are traced as constants. Use torch.min/max to WAR this issue - Arguments: - boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) format - size (Tuple[height, width]): size of the image - Returns: - clipped_boxes (Tensor[N, 4]) - """ - TO_REMOVE = 1 - device = boxes.device - dim = boxes.dim() - boxes_x = boxes[..., 0::2] - boxes_y = boxes[..., 1::2] - - boxes_x = torch.max(boxes_x, torch.tensor(0., dtype=torch.float).to(device)) - boxes_x = torch.min(boxes_x, torch.tensor(size[1] - TO_REMOVE, dtype=torch.float).to(device)) - boxes_y = torch.max(boxes_y, torch.tensor(0., dtype=torch.float).to(device)) - boxes_y = torch.min(boxes_y, torch.tensor(size[0] - TO_REMOVE, dtype=torch.float).to(device)) - - clipped_boxes = torch.stack((boxes_x, boxes_y), dim=dim) - return clipped_boxes.reshape(boxes.shape) - - -if __name__ == "__main__": - bbox = BoxList([[0, 0, 10, 10], [0, 0, 5, 5]], (10, 10)) - s_bbox = bbox.resize((5, 5)) - print(s_bbox) - print(s_bbox.bbox) - - t_bbox = bbox.transpose(0) - print(t_bbox) - print(t_bbox.bbox) diff --git a/spaces/ProteinDesignLab/protpardelle/draw_samples.py b/spaces/ProteinDesignLab/protpardelle/draw_samples.py deleted file mode 100644 index d179620b698bc9d2dfc1bf73fbcadbc06dbe5bc0..0000000000000000000000000000000000000000 --- a/spaces/ProteinDesignLab/protpardelle/draw_samples.py +++ /dev/null @@ -1,356 +0,0 @@ -""" -https://github.com/ProteinDesignLab/protpardelle -License: MIT -Author: Alex Chu - -Entry point for unconditional or simple conditional sampling. -""" -import argparse -from datetime import datetime -import json -import os -import shlex -import subprocess -import sys -import time - -from einops import repeat -import torch - -from core import data -from core import residue_constants -from core import utils -import diffusion -import models -import sampling - - -def draw_and_save_samples( - model, - samples_per_len=8, - lengths=range(50, 512), - save_dir="./", - mode="backbone", - **sampling_kwargs, -): - device = model.device - if mode == "backbone": - total_sampling_time = 0 - for l in lengths: - prot_lens = torch.ones(samples_per_len).long() * l - seq_mask = model.make_seq_mask_for_sampling(prot_lens=prot_lens) - aux = sampling.draw_backbone_samples( - model, - seq_mask=seq_mask, - pdb_save_path=f"{save_dir}/len{format(l, '03d')}_samp", - return_aux=True, - return_sampling_runtime=True, - **sampling_kwargs, - ) - total_sampling_time += aux["runtime"] - print("Samples drawn for length", l) - return total_sampling_time - elif mode == "allatom": - total_sampling_time = 0 - for l in lengths: - prot_lens = torch.ones(samples_per_len).long() * l - seq_mask = model.make_seq_mask_for_sampling(prot_lens=prot_lens) - aux = sampling.draw_allatom_samples( - model, - seq_mask=seq_mask, - pdb_save_path=f"{save_dir}/len{format(l, '03d')}", - return_aux=True, - **sampling_kwargs, - ) - total_sampling_time += aux["runtime"] - print("Samples drawn for length", l) - return total_sampling_time - - -def parse_idx_string(idx_str): - spans = idx_str.split(",") - idxs = [] - for s in spans: - if "-" in s: - start, stop = s.split("-") - idxs.extend(list(range(int(start), int(stop)))) - else: - idxs.append(int(s)) - return idxs - - -class Manager(object): - def __init__(self): - self.parser = argparse.ArgumentParser( - formatter_class=argparse.RawTextHelpFormatter - ) - - self.parser.add_argument( - "--model_checkpoint", - type=str, - default="checkpoints", - help="Path to denoiser model weights and config", - ) - self.parser.add_argument( - "--mpnnpath", - type=str, - default="checkpoints/minimpnn_state_dict.pth", - help="Path to minimpnn model weights", - ) - self.parser.add_argument( - "--modeldir", - type=str, - help="Model base directory, ex 'training_logs/other/lemon-shape-51'", - ) - self.parser.add_argument("--modelepoch", type=int, help="Model epoch, ex 1000") - self.parser.add_argument( - "--type", type=str, default="allatom", help="Type of model" - ) - self.parser.add_argument( - "--param", type=str, default=None, help="Which sampling param to vary" - ) - self.parser.add_argument( - "--paramval", type=str, default=None, help="Which param val to use" - ) - self.parser.add_argument( - "--parampath", - type=str, - default=None, - help="Path to json file with params, either use param/paramval or parampath, not both", - ) - self.parser.add_argument( - "--perlen", type=int, default=2, help="How many samples per sequence length" - ) - self.parser.add_argument( - "--minlen", type=int, default=50, help="Minimum sequence length" - ) - self.parser.add_argument( - "--maxlen", - type=int, - default=60, - help="Maximum sequence length, not inclusive", - ) - self.parser.add_argument( - "--steplen", - type=int, - default=5, - help="How frequently to select sequence length, for steplen 2, would be 50, 52, 54, etc", - ) - self.parser.add_argument( - "--num_lens", - type=int, - required=False, - help="If steplen not provided, how many random lengths to sample at", - ) - self.parser.add_argument( - "--targetdir", type=str, default=".", help="Directory to save results" - ) - self.parser.add_argument( - "--input_pdb", type=str, required=False, help="PDB file to condition on" - ) - self.parser.add_argument( - "--resample_idxs", - type=str, - required=False, - help="Indices from PDB file to resample. Zero-indexed, comma-delimited, can use dashes, eg 0,2-5,7", - ) - - def add_argument(self, *args, **kwargs): - self.parser.add_argument(*args, **kwargs) - - def parse_args(self): - self.args = self.parser.parse_args() - - return self.args - - -def main(): - # Set up params, arguments, sampling config - #################### - manager = Manager() - manager.parse_args() - args = manager.args - print(args) - is_test_run = False - seed = 0 - samples_per_len = args.perlen - min_len = args.minlen - max_len = args.maxlen - len_step_size = args.steplen - device = "cuda:0" - - # setting default sampling config - if args.type == "backbone": - sampling_config = sampling.default_backbone_sampling_config() - elif args.type == "allatom": - sampling_config = sampling.default_allatom_sampling_config() - - sampling_kwargs = vars(sampling_config) - - # Parse conditioning inputs - input_pdb_len = None - if args.input_pdb: - input_feats = utils.load_feats_from_pdb(args.input_pdb, protein_only=True) - input_pdb_len = input_feats["aatype"].shape[0] - if args.resample_idxs: - print( - f"Warning: when sampling conditionally, the input pdb length ({input_pdb_len} residues) is used automatically for the sampling lengths." - ) - resample_idxs = parse_idx_string(args.resample_idxs) - else: - resample_idxs = list(range(input_pdb_len)) - cond_idxs = [i for i in range(input_pdb_len) if i not in resample_idxs] - to_batch_size = lambda x: repeat(x, "... -> b ...", b=samples_per_len).to( - device - ) - - # For unconditional model, center coords on whole structure - centered_coords = data.apply_random_se3( - input_feats["atom_positions"], - atom_mask=input_feats["atom_mask"], - translation_scale=0.0, - ) - cond_kwargs = {} - cond_kwargs["gt_coords"] = to_batch_size(centered_coords) - cond_kwargs["gt_cond_atom_mask"] = to_batch_size(input_feats["atom_mask"]) - cond_kwargs["gt_cond_atom_mask"][:, resample_idxs] = 0 - cond_kwargs["gt_aatype"] = to_batch_size(input_feats["aatype"]) - cond_kwargs["gt_cond_seq_mask"] = torch.zeros_like(cond_kwargs["gt_aatype"]) - cond_kwargs["gt_cond_seq_mask"][:, cond_idxs] = 1 - sampling_kwargs.update(cond_kwargs) - - # Determine lengths to sample at - if min_len is not None and max_len is not None: - if len_step_size is not None: - sampling_lengths = range(min_len, max_len, len_step_size) - else: - sampling_lengths = list( - torch.randint(min_len, max_len, size=(args.num_lens,)) - ) - elif input_pdb_len is not None: - sampling_lengths = [input_pdb_len] - else: - raise Exception("Need to provide a set of protein lengths or an input pdb.") - - total_num_samples = len(list(sampling_lengths)) * samples_per_len - - model_directory = args.modeldir - epoch = args.modelepoch - base_dir = args.targetdir - - date_string = datetime.now().strftime("%y-%m-%d-%H-%M-%S") - if is_test_run: - date_string = f"test-{date_string}" - - # Update sampling config with arguments - if args.param: - var_param = args.param - var_value = args.paramval - sampling_kwargs[var_param] = ( - None - if var_value == "None" - else int(var_value) - if var_param == "n_steps" - else float(var_value) - ) - elif args.parampath: - with open(args.parampath) as f: - var_params = json.loads(f.read()) - sampling_kwargs.update(var_params) - - # this is only used for the readme, keep s_min and s_max as params instead of struct_noise_schedule - sampling_kwargs_readme = list(sampling_kwargs.items()) - - print("Base directory:", base_dir) - save_dir = f"{base_dir}/samples" - save_init_dir = f"{base_dir}/samples_inits" - - print("Samples saved to:", save_dir) - #################### - - torch.manual_seed(seed) - if not os.path.exists(save_dir): - subprocess.run(shlex.split(f"mkdir -p {save_dir}")) - - if not os.path.exists(save_init_dir): - subprocess.run(shlex.split(f"mkdir -p {save_init_dir}")) - - # Load model - if args.type == "backbone": - if args.model_checkpoint: - checkpoint = f"{args.model_checkpoint}/backbone_state_dict.pth" - cfg_path = f"{args.model_checkpoint}/backbone_pretrained.yml" - else: - checkpoint = ( - f"{model_directory}/checkpoints/epoch{epoch}_training_state.pth" - ) - cfg_path = f"{model_directory}/configs/backbone.yml" - config = utils.load_config(cfg_path) - weights = torch.load(checkpoint, map_location=device)["model_state_dict"] - model = models.Protpardelle(config, device=device) - model.load_state_dict(weights) - model.to(device) - model.eval() - model.device = device - elif args.type == "allatom": - if args.model_checkpoint: - checkpoint = f"{args.model_checkpoint}/allatom_state_dict.pth" - cfg_path = f"{args.model_checkpoint}/allatom_pretrained.yml" - else: - checkpoint = ( - f"{model_directory}/checkpoints/epoch{epoch}_training_state.pth" - ) - cfg_path = f"{model_directory}/configs/allatom.yml" - config = utils.load_config(cfg_path) - weights = torch.load(checkpoint, map_location=device)["model_state_dict"] - model = models.Protpardelle(config, device=device) - model.load_state_dict(weights) - model.load_minimpnn(args.mpnnpath) - model.to(device) - model.eval() - model.device = device - - if config.train.home_dir == '': - config.train.home_dir = os.getcwd() - - # Sampling - with open(save_dir + "/readme.txt", "w") as f: - f.write(f"Sampling run for {date_string}\n") - f.write(f"Random seed {seed}\n") - f.write(f"Model checkpoint: {checkpoint}\n") - f.write( - f"{samples_per_len} samples per length from {min_len}:{max_len}:{len_step_size}\n" - ) - f.write("Sampling params:\n") - for k, v in sampling_kwargs_readme: - f.write(f"{k}\t{v}\n") - - print(f"Model loaded from {checkpoint}") - print(f"Beginning sampling for {date_string}...") - - # Draw samples - start_time = time.time() - sampling_time = draw_and_save_samples( - model, - samples_per_len=samples_per_len, - lengths=sampling_lengths, - save_dir=save_dir, - mode=args.type, - **sampling_kwargs, - ) - time_elapsed = time.time() - start_time - - print(f"Sampling concluded after {time_elapsed} seconds.") - print(f"Of this, {sampling_time} seconds were for actual sampling.") - print(f"{total_num_samples} total samples were drawn.") - - with open(save_dir + "/readme.txt", "a") as f: - f.write(f"Total job time: {time_elapsed} seconds\n") - f.write(f"Model run time: {sampling_time} seconds\n") - f.write(f"Total samples drawn: {total_num_samples}\n") - - return - - -if __name__ == "__main__": - main() diff --git a/spaces/QINGFNEG/White-box-Cartoonization/wbc/guided_filter.py b/spaces/QINGFNEG/White-box-Cartoonization/wbc/guided_filter.py deleted file mode 100644 index fd019d145efc7f308cd96de90f4e7b648f6820b4..0000000000000000000000000000000000000000 --- a/spaces/QINGFNEG/White-box-Cartoonization/wbc/guided_filter.py +++ /dev/null @@ -1,87 +0,0 @@ -import tensorflow as tf -import numpy as np - - - - -def tf_box_filter(x, r): - k_size = int(2*r+1) - ch = x.get_shape().as_list()[-1] - weight = 1/(k_size**2) - box_kernel = weight*np.ones((k_size, k_size, ch, 1)) - box_kernel = np.array(box_kernel).astype(np.float32) - output = tf.nn.depthwise_conv2d(x, box_kernel, [1, 1, 1, 1], 'SAME') - return output - - - -def guided_filter(x, y, r, eps=1e-2): - - x_shape = tf.shape(x) - #y_shape = tf.shape(y) - - N = tf_box_filter(tf.ones((1, x_shape[1], x_shape[2], 1), dtype=x.dtype), r) - - mean_x = tf_box_filter(x, r) / N - mean_y = tf_box_filter(y, r) / N - cov_xy = tf_box_filter(x * y, r) / N - mean_x * mean_y - var_x = tf_box_filter(x * x, r) / N - mean_x * mean_x - - A = cov_xy / (var_x + eps) - b = mean_y - A * mean_x - - mean_A = tf_box_filter(A, r) / N - mean_b = tf_box_filter(b, r) / N - - output = mean_A * x + mean_b - - return output - - - -def fast_guided_filter(lr_x, lr_y, hr_x, r=1, eps=1e-8): - - #assert lr_x.shape.ndims == 4 and lr_y.shape.ndims == 4 and hr_x.shape.ndims == 4 - - lr_x_shape = tf.shape(lr_x) - #lr_y_shape = tf.shape(lr_y) - hr_x_shape = tf.shape(hr_x) - - N = tf_box_filter(tf.ones((1, lr_x_shape[1], lr_x_shape[2], 1), dtype=lr_x.dtype), r) - - mean_x = tf_box_filter(lr_x, r) / N - mean_y = tf_box_filter(lr_y, r) / N - cov_xy = tf_box_filter(lr_x * lr_y, r) / N - mean_x * mean_y - var_x = tf_box_filter(lr_x * lr_x, r) / N - mean_x * mean_x - - A = cov_xy / (var_x + eps) - b = mean_y - A * mean_x - - mean_A = tf.image.resize_images(A, hr_x_shape[1: 3]) - mean_b = tf.image.resize_images(b, hr_x_shape[1: 3]) - - output = mean_A * hr_x + mean_b - - return output - - -if __name__ == '__main__': - import cv2 - from tqdm import tqdm - - input_photo = tf.placeholder(tf.float32, [1, None, None, 3]) - #input_superpixel = tf.placeholder(tf.float32, [16, 256, 256, 3]) - output = guided_filter(input_photo, input_photo, 5, eps=1) - image = cv2.imread('output_figure1/cartoon2.jpg') - image = image/127.5 - 1 - image = np.expand_dims(image, axis=0) - - config = tf.ConfigProto() - config.gpu_options.allow_growth = True - sess = tf.Session(config=config) - sess.run(tf.global_variables_initializer()) - - out = sess.run(output, feed_dict={input_photo: image}) - out = (np.squeeze(out)+1)*127.5 - out = np.clip(out, 0, 255).astype(np.uint8) - cv2.imwrite('output_figure1/cartoon2_filter.jpg', out) diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/formatters/terminal.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/formatters/terminal.py deleted file mode 100644 index e0bda16a236bfcf2c17068f2ff0cb8551830244a..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/formatters/terminal.py +++ /dev/null @@ -1,127 +0,0 @@ -""" - pygments.formatters.terminal - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Formatter for terminal output with ANSI sequences. - - :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from pip._vendor.pygments.formatter import Formatter -from pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \ - Number, Operator, Generic, Token, Whitespace -from pip._vendor.pygments.console import ansiformat -from pip._vendor.pygments.util import get_choice_opt - - -__all__ = ['TerminalFormatter'] - - -#: Map token types to a tuple of color values for light and dark -#: backgrounds. -TERMINAL_COLORS = { - Token: ('', ''), - - Whitespace: ('gray', 'brightblack'), - Comment: ('gray', 'brightblack'), - Comment.Preproc: ('cyan', 'brightcyan'), - Keyword: ('blue', 'brightblue'), - Keyword.Type: ('cyan', 'brightcyan'), - Operator.Word: ('magenta', 'brightmagenta'), - Name.Builtin: ('cyan', 'brightcyan'), - Name.Function: ('green', 'brightgreen'), - Name.Namespace: ('_cyan_', '_brightcyan_'), - Name.Class: ('_green_', '_brightgreen_'), - Name.Exception: ('cyan', 'brightcyan'), - Name.Decorator: ('brightblack', 'gray'), - Name.Variable: ('red', 'brightred'), - Name.Constant: ('red', 'brightred'), - Name.Attribute: ('cyan', 'brightcyan'), - Name.Tag: ('brightblue', 'brightblue'), - String: ('yellow', 'yellow'), - Number: ('blue', 'brightblue'), - - Generic.Deleted: ('brightred', 'brightred'), - Generic.Inserted: ('green', 'brightgreen'), - Generic.Heading: ('**', '**'), - Generic.Subheading: ('*magenta*', '*brightmagenta*'), - Generic.Prompt: ('**', '**'), - Generic.Error: ('brightred', 'brightred'), - - Error: ('_brightred_', '_brightred_'), -} - - -class TerminalFormatter(Formatter): - r""" - Format tokens with ANSI color sequences, for output in a text console. - Color sequences are terminated at newlines, so that paging the output - works correctly. - - The `get_style_defs()` method doesn't do anything special since there is - no support for common styles. - - Options accepted: - - `bg` - Set to ``"light"`` or ``"dark"`` depending on the terminal's background - (default: ``"light"``). - - `colorscheme` - A dictionary mapping token types to (lightbg, darkbg) color names or - ``None`` (default: ``None`` = use builtin colorscheme). - - `linenos` - Set to ``True`` to have line numbers on the terminal output as well - (default: ``False`` = no line numbers). - """ - name = 'Terminal' - aliases = ['terminal', 'console'] - filenames = [] - - def __init__(self, **options): - Formatter.__init__(self, **options) - self.darkbg = get_choice_opt(options, 'bg', - ['light', 'dark'], 'light') == 'dark' - self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS - self.linenos = options.get('linenos', False) - self._lineno = 0 - - def format(self, tokensource, outfile): - return Formatter.format(self, tokensource, outfile) - - def _write_lineno(self, outfile): - self._lineno += 1 - outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno)) - - def _get_color(self, ttype): - # self.colorscheme is a dict containing usually generic types, so we - # have to walk the tree of dots. The base Token type must be a key, - # even if it's empty string, as in the default above. - colors = self.colorscheme.get(ttype) - while colors is None: - ttype = ttype.parent - colors = self.colorscheme.get(ttype) - return colors[self.darkbg] - - def format_unencoded(self, tokensource, outfile): - if self.linenos: - self._write_lineno(outfile) - - for ttype, value in tokensource: - color = self._get_color(ttype) - - for line in value.splitlines(True): - if color: - outfile.write(ansiformat(color, line.rstrip('\n'))) - else: - outfile.write(line.rstrip('\n')) - if line.endswith('\n'): - if self.linenos: - self._write_lineno(outfile) - else: - outfile.write('\n') - - if self.linenos: - outfile.write("\n") diff --git a/spaces/Reself/StableVideo/ldm/modules/midas/midas/transforms.py b/spaces/Reself/StableVideo/ldm/modules/midas/midas/transforms.py deleted file mode 100644 index 350cbc11662633ad7f8968eb10be2e7de6e384e9..0000000000000000000000000000000000000000 --- a/spaces/Reself/StableVideo/ldm/modules/midas/midas/transforms.py +++ /dev/null @@ -1,234 +0,0 @@ -import numpy as np -import cv2 -import math - - -def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): - """Rezise the sample to ensure the given size. Keeps aspect ratio. - - Args: - sample (dict): sample - size (tuple): image size - - Returns: - tuple: new size - """ - shape = list(sample["disparity"].shape) - - if shape[0] >= size[0] and shape[1] >= size[1]: - return sample - - scale = [0, 0] - scale[0] = size[0] / shape[0] - scale[1] = size[1] / shape[1] - - scale = max(scale) - - shape[0] = math.ceil(scale * shape[0]) - shape[1] = math.ceil(scale * shape[1]) - - # resize - sample["image"] = cv2.resize( - sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method - ) - - sample["disparity"] = cv2.resize( - sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST - ) - sample["mask"] = cv2.resize( - sample["mask"].astype(np.float32), - tuple(shape[::-1]), - interpolation=cv2.INTER_NEAREST, - ) - sample["mask"] = sample["mask"].astype(bool) - - return tuple(shape) - - -class Resize(object): - """Resize sample to given size (width, height). - """ - - def __init__( - self, - width, - height, - resize_target=True, - keep_aspect_ratio=False, - ensure_multiple_of=1, - resize_method="lower_bound", - image_interpolation_method=cv2.INTER_AREA, - ): - """Init. - - Args: - width (int): desired output width - height (int): desired output height - resize_target (bool, optional): - True: Resize the full sample (image, mask, target). - False: Resize image only. - Defaults to True. - keep_aspect_ratio (bool, optional): - True: Keep the aspect ratio of the input sample. - Output sample might not have the given width and height, and - resize behaviour depends on the parameter 'resize_method'. - Defaults to False. - ensure_multiple_of (int, optional): - Output width and height is constrained to be multiple of this parameter. - Defaults to 1. - resize_method (str, optional): - "lower_bound": Output will be at least as large as the given size. - "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) - "minimal": Scale as least as possible. (Output size might be smaller than given size.) - Defaults to "lower_bound". - """ - self.__width = width - self.__height = height - - self.__resize_target = resize_target - self.__keep_aspect_ratio = keep_aspect_ratio - self.__multiple_of = ensure_multiple_of - self.__resize_method = resize_method - self.__image_interpolation_method = image_interpolation_method - - def constrain_to_multiple_of(self, x, min_val=0, max_val=None): - y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int) - - if max_val is not None and y > max_val: - y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int) - - if y < min_val: - y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int) - - return y - - def get_size(self, width, height): - # determine new height and width - scale_height = self.__height / height - scale_width = self.__width / width - - if self.__keep_aspect_ratio: - if self.__resize_method == "lower_bound": - # scale such that output size is lower bound - if scale_width > scale_height: - # fit width - scale_height = scale_width - else: - # fit height - scale_width = scale_height - elif self.__resize_method == "upper_bound": - # scale such that output size is upper bound - if scale_width < scale_height: - # fit width - scale_height = scale_width - else: - # fit height - scale_width = scale_height - elif self.__resize_method == "minimal": - # scale as least as possbile - if abs(1 - scale_width) < abs(1 - scale_height): - # fit width - scale_height = scale_width - else: - # fit height - scale_width = scale_height - else: - raise ValueError( - f"resize_method {self.__resize_method} not implemented" - ) - - if self.__resize_method == "lower_bound": - new_height = self.constrain_to_multiple_of( - scale_height * height, min_val=self.__height - ) - new_width = self.constrain_to_multiple_of( - scale_width * width, min_val=self.__width - ) - elif self.__resize_method == "upper_bound": - new_height = self.constrain_to_multiple_of( - scale_height * height, max_val=self.__height - ) - new_width = self.constrain_to_multiple_of( - scale_width * width, max_val=self.__width - ) - elif self.__resize_method == "minimal": - new_height = self.constrain_to_multiple_of(scale_height * height) - new_width = self.constrain_to_multiple_of(scale_width * width) - else: - raise ValueError(f"resize_method {self.__resize_method} not implemented") - - return (new_width, new_height) - - def __call__(self, sample): - width, height = self.get_size( - sample["image"].shape[1], sample["image"].shape[0] - ) - - # resize sample - sample["image"] = cv2.resize( - sample["image"], - (width, height), - interpolation=self.__image_interpolation_method, - ) - - if self.__resize_target: - if "disparity" in sample: - sample["disparity"] = cv2.resize( - sample["disparity"], - (width, height), - interpolation=cv2.INTER_NEAREST, - ) - - if "depth" in sample: - sample["depth"] = cv2.resize( - sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST - ) - - sample["mask"] = cv2.resize( - sample["mask"].astype(np.float32), - (width, height), - interpolation=cv2.INTER_NEAREST, - ) - sample["mask"] = sample["mask"].astype(bool) - - return sample - - -class NormalizeImage(object): - """Normlize image by given mean and std. - """ - - def __init__(self, mean, std): - self.__mean = mean - self.__std = std - - def __call__(self, sample): - sample["image"] = (sample["image"] - self.__mean) / self.__std - - return sample - - -class PrepareForNet(object): - """Prepare sample for usage as network input. - """ - - def __init__(self): - pass - - def __call__(self, sample): - image = np.transpose(sample["image"], (2, 0, 1)) - sample["image"] = np.ascontiguousarray(image).astype(np.float32) - - if "mask" in sample: - sample["mask"] = sample["mask"].astype(np.float32) - sample["mask"] = np.ascontiguousarray(sample["mask"]) - - if "disparity" in sample: - disparity = sample["disparity"].astype(np.float32) - sample["disparity"] = np.ascontiguousarray(disparity) - - if "depth" in sample: - depth = sample["depth"].astype(np.float32) - sample["depth"] = np.ascontiguousarray(depth) - - return sample diff --git a/spaces/Rongjiehuang/GenerSpeech/modules/hifigan/hifigan.py b/spaces/Rongjiehuang/GenerSpeech/modules/hifigan/hifigan.py deleted file mode 100644 index ae7e61f56b00d60bcc49a18ece3edbe54746f7ea..0000000000000000000000000000000000000000 --- a/spaces/Rongjiehuang/GenerSpeech/modules/hifigan/hifigan.py +++ /dev/null @@ -1,365 +0,0 @@ -import torch -import torch.nn.functional as F -import torch.nn as nn -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm - -from modules.parallel_wavegan.layers import UpsampleNetwork, ConvInUpsampleNetwork -from modules.parallel_wavegan.models.source import SourceModuleHnNSF -import numpy as np - -LRELU_SLOPE = 0.1 - - -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 apply_weight_norm(m): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - weight_norm(m) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size * dilation - dilation) / 2) - - -class ResBlock1(torch.nn.Module): - def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)): - super(ResBlock1, self).__init__() - self.h = h - self.convs1 = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2], - padding=get_padding(kernel_size, dilation[2]))) - ]) - self.convs1.apply(init_weights) - - self.convs2 = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))) - ]) - self.convs2.apply(init_weights) - - def forward(self, x): - for c1, c2 in zip(self.convs1, self.convs2): - xt = F.leaky_relu(x, LRELU_SLOPE) - xt = c1(xt) - xt = F.leaky_relu(xt, LRELU_SLOPE) - xt = c2(xt) - x = xt + x - return x - - def remove_weight_norm(self): - for l in self.convs1: - remove_weight_norm(l) - for l in self.convs2: - remove_weight_norm(l) - - -class ResBlock2(torch.nn.Module): - def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)): - super(ResBlock2, self).__init__() - self.h = h - self.convs = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))) - ]) - self.convs.apply(init_weights) - - def forward(self, x): - for c in self.convs: - xt = F.leaky_relu(x, LRELU_SLOPE) - xt = c(xt) - x = xt + x - return x - - def remove_weight_norm(self): - for l in self.convs: - remove_weight_norm(l) - - -class Conv1d1x1(Conv1d): - """1x1 Conv1d with customized initialization.""" - - def __init__(self, in_channels, out_channels, bias): - """Initialize 1x1 Conv1d module.""" - super(Conv1d1x1, self).__init__(in_channels, out_channels, - kernel_size=1, padding=0, - dilation=1, bias=bias) - - -class HifiGanGenerator(torch.nn.Module): - def __init__(self, h, c_out=1): - super(HifiGanGenerator, self).__init__() - self.h = h - self.num_kernels = len(h['resblock_kernel_sizes']) - self.num_upsamples = len(h['upsample_rates']) - - if h['use_pitch_embed']: - self.harmonic_num = 8 - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(h['upsample_rates'])) - self.m_source = SourceModuleHnNSF( - sampling_rate=h['audio_sample_rate'], - harmonic_num=self.harmonic_num) - self.noise_convs = nn.ModuleList() - self.conv_pre = weight_norm(Conv1d(80, h['upsample_initial_channel'], 7, 1, padding=3)) - resblock = ResBlock1 if h['resblock'] == '1' else ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(h['upsample_rates'], h['upsample_kernel_sizes'])): - c_cur = h['upsample_initial_channel'] // (2 ** (i + 1)) - self.ups.append(weight_norm( - ConvTranspose1d(c_cur * 2, c_cur, k, u, padding=(k - u) // 2))) - if h['use_pitch_embed']: - if i + 1 < len(h['upsample_rates']): - stride_f0 = np.prod(h['upsample_rates'][i + 1:]) - self.noise_convs.append(Conv1d( - 1, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=stride_f0 // 2)) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = h['upsample_initial_channel'] // (2 ** (i + 1)) - for j, (k, d) in enumerate(zip(h['resblock_kernel_sizes'], h['resblock_dilation_sizes'])): - self.resblocks.append(resblock(h, ch, k, d)) - - self.conv_post = weight_norm(Conv1d(ch, c_out, 7, 1, padding=3)) - self.ups.apply(init_weights) - self.conv_post.apply(init_weights) - - def forward(self, x, f0=None): - if f0 is not None: - # harmonic-source signal, noise-source signal, uv flag - f0 = self.f0_upsamp(f0[:, None]).transpose(1, 2) - har_source, noi_source, uv = self.m_source(f0) - har_source = har_source.transpose(1, 2) - - x = self.conv_pre(x) - for i in range(self.num_upsamples): - x = F.leaky_relu(x, LRELU_SLOPE) - x = self.ups[i](x) - if f0 is not None: - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - print('Removing weight norm...') - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - remove_weight_norm(self.conv_pre) - remove_weight_norm(self.conv_post) - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False, use_cond=False, c_in=1): - super(DiscriminatorP, self).__init__() - self.use_cond = use_cond - if use_cond: - from utils.hparams import hparams - t = hparams['hop_size'] - self.cond_net = torch.nn.ConvTranspose1d(80, 1, t * 2, stride=t, padding=t // 2) - c_in = 2 - - self.period = period - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv2d(c_in, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))), - norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))), - norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))), - norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))), - norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))), - ]) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x, mel): - fmap = [] - if self.use_cond: - x_mel = self.cond_net(mel) - x = torch.cat([x_mel, x], 1) - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_cond=False, c_in=1): - super(MultiPeriodDiscriminator, self).__init__() - self.discriminators = nn.ModuleList([ - DiscriminatorP(2, use_cond=use_cond, c_in=c_in), - DiscriminatorP(3, use_cond=use_cond, c_in=c_in), - DiscriminatorP(5, use_cond=use_cond, c_in=c_in), - DiscriminatorP(7, use_cond=use_cond, c_in=c_in), - DiscriminatorP(11, use_cond=use_cond, c_in=c_in), - ]) - - def forward(self, y, y_hat, mel=None): - y_d_rs = [] - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y, mel) - y_d_g, fmap_g = d(y_hat, mel) - y_d_rs.append(y_d_r) - fmap_rs.append(fmap_r) - y_d_gs.append(y_d_g) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False, use_cond=False, upsample_rates=None, c_in=1): - super(DiscriminatorS, self).__init__() - self.use_cond = use_cond - if use_cond: - t = np.prod(upsample_rates) - self.cond_net = torch.nn.ConvTranspose1d(80, 1, t * 2, stride=t, padding=t // 2) - c_in = 2 - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv1d(c_in, 128, 15, 1, padding=7)), - norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)), - norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)), - norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ]) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x, mel): - if self.use_cond: - x_mel = self.cond_net(mel) - x = torch.cat([x_mel, x], 1) - fmap = [] - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class MultiScaleDiscriminator(torch.nn.Module): - def __init__(self, use_cond=False, c_in=1): - super(MultiScaleDiscriminator, self).__init__() - from utils.hparams import hparams - self.discriminators = nn.ModuleList([ - DiscriminatorS(use_spectral_norm=True, use_cond=use_cond, - upsample_rates=[4, 4, hparams['hop_size'] // 16], - c_in=c_in), - DiscriminatorS(use_cond=use_cond, - upsample_rates=[4, 4, hparams['hop_size'] // 32], - c_in=c_in), - DiscriminatorS(use_cond=use_cond, - upsample_rates=[4, 4, hparams['hop_size'] // 64], - c_in=c_in), - ]) - self.meanpools = nn.ModuleList([ - AvgPool1d(4, 2, padding=1), - AvgPool1d(4, 2, padding=1) - ]) - - def forward(self, y, y_hat, mel=None): - y_d_rs = [] - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - if i != 0: - y = self.meanpools[i - 1](y) - y_hat = self.meanpools[i - 1](y_hat) - y_d_r, fmap_r = d(y, mel) - y_d_g, fmap_g = d(y_hat, mel) - y_d_rs.append(y_d_r) - fmap_rs.append(fmap_r) - y_d_gs.append(y_d_g) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - loss += torch.mean(torch.abs(rl - gl)) - - return loss * 2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - r_losses = 0 - g_losses = 0 - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - r_loss = torch.mean((1 - dr) ** 2) - g_loss = torch.mean(dg ** 2) - r_losses += r_loss - g_losses += g_loss - r_losses = r_losses / len(disc_real_outputs) - g_losses = g_losses / len(disc_real_outputs) - return r_losses, g_losses - - -def cond_discriminator_loss(outputs): - loss = 0 - for dg in outputs: - g_loss = torch.mean(dg ** 2) - loss += g_loss - loss = loss / len(outputs) - return loss - - -def generator_loss(disc_outputs): - loss = 0 - for dg in disc_outputs: - l = torch.mean((1 - dg) ** 2) - loss += l - loss = loss / len(disc_outputs) - return loss diff --git a/spaces/Sa-m/YOLO-V7-Custom-Model-Pot-Hole-Detection/models/yolo.py b/spaces/Sa-m/YOLO-V7-Custom-Model-Pot-Hole-Detection/models/yolo.py deleted file mode 100644 index 95a019c6aeec8c3f1d582907d5fe7ff3ed6b9369..0000000000000000000000000000000000000000 --- a/spaces/Sa-m/YOLO-V7-Custom-Model-Pot-Hole-Detection/models/yolo.py +++ /dev/null @@ -1,843 +0,0 @@ -import argparse -import logging -import sys -from copy import deepcopy - -sys.path.append('./') # to run '$ python *.py' files in subdirectories -logger = logging.getLogger(__name__) -import torch -from models.common import * -from models.experimental import * -from utils.autoanchor import check_anchor_order -from utils.general import make_divisible, check_file, set_logging -from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \ - select_device, copy_attr -from utils.loss import SigmoidBin - -try: - import thop # for FLOPS computation -except ImportError: - thop = None - - -class Detect(nn.Module): - stride = None # strides computed during build - export = False # onnx export - end2end = False - include_nms = False - concat = False - - def __init__(self, nc=80, anchors=(), ch=()): # detection layer - super(Detect, self).__init__() - self.nc = nc # number of classes - self.no = nc + 5 # number of outputs per anchor - self.nl = len(anchors) # number of detection layers - self.na = len(anchors[0]) // 2 # number of anchors - self.grid = [torch.zeros(1)] * self.nl # init grid - a = torch.tensor(anchors).float().view(self.nl, -1, 2) - self.register_buffer('anchors', a) # shape(nl,na,2) - self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) - self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv - - def forward(self, x): - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - x[i] = self.m[i](x[i]) # conv - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - y = x[i].sigmoid() - if not torch.onnx.is_in_onnx_export(): - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - else: - xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 - xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy - wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh - y = torch.cat((xy, wh, conf), 4) - z.append(y.view(bs, -1, self.no)) - - if self.training: - out = x - elif self.end2end: - out = torch.cat(z, 1) - elif self.include_nms: - z = self.convert(z) - out = (z, ) - elif self.concat: - out = torch.cat(z, 1) - else: - out = (torch.cat(z, 1), x) - - return out - - @staticmethod - def _make_grid(nx=20, ny=20): - yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) - return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() - - def convert(self, z): - z = torch.cat(z, 1) - box = z[:, :, :4] - conf = z[:, :, 4:5] - score = z[:, :, 5:] - score *= conf - convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]], - dtype=torch.float32, - device=z.device) - box @= convert_matrix - return (box, score) - - -class IDetect(nn.Module): - stride = None # strides computed during build - export = False # onnx export - end2end = False - include_nms = False - concat = False - - def __init__(self, nc=80, anchors=(), ch=()): # detection layer - super(IDetect, self).__init__() - self.nc = nc # number of classes - self.no = nc + 5 # number of outputs per anchor - self.nl = len(anchors) # number of detection layers - self.na = len(anchors[0]) // 2 # number of anchors - self.grid = [torch.zeros(1)] * self.nl # init grid - a = torch.tensor(anchors).float().view(self.nl, -1, 2) - self.register_buffer('anchors', a) # shape(nl,na,2) - self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) - self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv - - self.ia = nn.ModuleList(ImplicitA(x) for x in ch) - self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch) - - def forward(self, x): - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - x[i] = self.m[i](self.ia[i](x[i])) # conv - x[i] = self.im[i](x[i]) - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - - y = x[i].sigmoid() - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - z.append(y.view(bs, -1, self.no)) - - return x if self.training else (torch.cat(z, 1), x) - - def fuseforward(self, x): - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - x[i] = self.m[i](x[i]) # conv - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - - y = x[i].sigmoid() - if not torch.onnx.is_in_onnx_export(): - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - else: - xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 - xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy - wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh - y = torch.cat((xy, wh, conf), 4) - z.append(y.view(bs, -1, self.no)) - - if self.training: - out = x - elif self.end2end: - out = torch.cat(z, 1) - elif self.include_nms: - z = self.convert(z) - out = (z, ) - elif self.concat: - out = torch.cat(z, 1) - else: - out = (torch.cat(z, 1), x) - - return out - - def fuse(self): - print("IDetect.fuse") - # fuse ImplicitA and Convolution - for i in range(len(self.m)): - c1,c2,_,_ = self.m[i].weight.shape - c1_,c2_, _,_ = self.ia[i].implicit.shape - self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1) - - # fuse ImplicitM and Convolution - for i in range(len(self.m)): - c1,c2, _,_ = self.im[i].implicit.shape - self.m[i].bias *= self.im[i].implicit.reshape(c2) - self.m[i].weight *= self.im[i].implicit.transpose(0,1) - - @staticmethod - def _make_grid(nx=20, ny=20): - yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) - return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() - - def convert(self, z): - z = torch.cat(z, 1) - box = z[:, :, :4] - conf = z[:, :, 4:5] - score = z[:, :, 5:] - score *= conf - convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]], - dtype=torch.float32, - device=z.device) - box @= convert_matrix - return (box, score) - - -class IKeypoint(nn.Module): - stride = None # strides computed during build - export = False # onnx export - - def __init__(self, nc=80, anchors=(), nkpt=17, ch=(), inplace=True, dw_conv_kpt=False): # detection layer - super(IKeypoint, self).__init__() - self.nc = nc # number of classes - self.nkpt = nkpt - self.dw_conv_kpt = dw_conv_kpt - self.no_det=(nc + 5) # number of outputs per anchor for box and class - self.no_kpt = 3*self.nkpt ## number of outputs per anchor for keypoints - self.no = self.no_det+self.no_kpt - self.nl = len(anchors) # number of detection layers - self.na = len(anchors[0]) // 2 # number of anchors - self.grid = [torch.zeros(1)] * self.nl # init grid - self.flip_test = False - a = torch.tensor(anchors).float().view(self.nl, -1, 2) - self.register_buffer('anchors', a) # shape(nl,na,2) - self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) - self.m = nn.ModuleList(nn.Conv2d(x, self.no_det * self.na, 1) for x in ch) # output conv - - self.ia = nn.ModuleList(ImplicitA(x) for x in ch) - self.im = nn.ModuleList(ImplicitM(self.no_det * self.na) for _ in ch) - - if self.nkpt is not None: - if self.dw_conv_kpt: #keypoint head is slightly more complex - self.m_kpt = nn.ModuleList( - nn.Sequential(DWConv(x, x, k=3), Conv(x,x), - DWConv(x, x, k=3), Conv(x, x), - DWConv(x, x, k=3), Conv(x,x), - DWConv(x, x, k=3), Conv(x, x), - DWConv(x, x, k=3), Conv(x, x), - DWConv(x, x, k=3), nn.Conv2d(x, self.no_kpt * self.na, 1)) for x in ch) - else: #keypoint head is a single convolution - self.m_kpt = nn.ModuleList(nn.Conv2d(x, self.no_kpt * self.na, 1) for x in ch) - - self.inplace = inplace # use in-place ops (e.g. slice assignment) - - def forward(self, x): - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - if self.nkpt is None or self.nkpt==0: - x[i] = self.im[i](self.m[i](self.ia[i](x[i]))) # conv - else : - x[i] = torch.cat((self.im[i](self.m[i](self.ia[i](x[i]))), self.m_kpt[i](x[i])), axis=1) - - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - x_det = x[i][..., :6] - x_kpt = x[i][..., 6:] - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - kpt_grid_x = self.grid[i][..., 0:1] - kpt_grid_y = self.grid[i][..., 1:2] - - if self.nkpt == 0: - y = x[i].sigmoid() - else: - y = x_det.sigmoid() - - if self.inplace: - xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh - if self.nkpt != 0: - x_kpt[..., 0::3] = (x_kpt[..., ::3] * 2. - 0.5 + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy - x_kpt[..., 1::3] = (x_kpt[..., 1::3] * 2. - 0.5 + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy - #x_kpt[..., 0::3] = (x_kpt[..., ::3] + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy - #x_kpt[..., 1::3] = (x_kpt[..., 1::3] + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy - #print('=============') - #print(self.anchor_grid[i].shape) - #print(self.anchor_grid[i][...,0].unsqueeze(4).shape) - #print(x_kpt[..., 0::3].shape) - #x_kpt[..., 0::3] = ((x_kpt[..., 0::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy - #x_kpt[..., 1::3] = ((x_kpt[..., 1::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy - #x_kpt[..., 0::3] = (((x_kpt[..., 0::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy - #x_kpt[..., 1::3] = (((x_kpt[..., 1::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy - x_kpt[..., 2::3] = x_kpt[..., 2::3].sigmoid() - - y = torch.cat((xy, wh, y[..., 4:], x_kpt), dim = -1) - - else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 - xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - if self.nkpt != 0: - y[..., 6:] = (y[..., 6:] * 2. - 0.5 + self.grid[i].repeat((1,1,1,1,self.nkpt))) * self.stride[i] # xy - y = torch.cat((xy, wh, y[..., 4:]), -1) - - z.append(y.view(bs, -1, self.no)) - - return x if self.training else (torch.cat(z, 1), x) - - @staticmethod - def _make_grid(nx=20, ny=20): - yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) - return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() - - -class IAuxDetect(nn.Module): - stride = None # strides computed during build - export = False # onnx export - end2end = False - include_nms = False - concat = False - - def __init__(self, nc=80, anchors=(), ch=()): # detection layer - super(IAuxDetect, self).__init__() - self.nc = nc # number of classes - self.no = nc + 5 # number of outputs per anchor - self.nl = len(anchors) # number of detection layers - self.na = len(anchors[0]) // 2 # number of anchors - self.grid = [torch.zeros(1)] * self.nl # init grid - a = torch.tensor(anchors).float().view(self.nl, -1, 2) - self.register_buffer('anchors', a) # shape(nl,na,2) - self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) - self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[:self.nl]) # output conv - self.m2 = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[self.nl:]) # output conv - - self.ia = nn.ModuleList(ImplicitA(x) for x in ch[:self.nl]) - self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch[:self.nl]) - - def forward(self, x): - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - x[i] = self.m[i](self.ia[i](x[i])) # conv - x[i] = self.im[i](x[i]) - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - x[i+self.nl] = self.m2[i](x[i+self.nl]) - x[i+self.nl] = x[i+self.nl].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - - y = x[i].sigmoid() - if not torch.onnx.is_in_onnx_export(): - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - else: - xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 - xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy - wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh - y = torch.cat((xy, wh, conf), 4) - z.append(y.view(bs, -1, self.no)) - - return x if self.training else (torch.cat(z, 1), x[:self.nl]) - - def fuseforward(self, x): - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - x[i] = self.m[i](x[i]) # conv - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - - y = x[i].sigmoid() - if not torch.onnx.is_in_onnx_export(): - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - else: - xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].data # wh - y = torch.cat((xy, wh, y[..., 4:]), -1) - z.append(y.view(bs, -1, self.no)) - - if self.training: - out = x - elif self.end2end: - out = torch.cat(z, 1) - elif self.include_nms: - z = self.convert(z) - out = (z, ) - elif self.concat: - out = torch.cat(z, 1) - else: - out = (torch.cat(z, 1), x) - - return out - - def fuse(self): - print("IAuxDetect.fuse") - # fuse ImplicitA and Convolution - for i in range(len(self.m)): - c1,c2,_,_ = self.m[i].weight.shape - c1_,c2_, _,_ = self.ia[i].implicit.shape - self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1) - - # fuse ImplicitM and Convolution - for i in range(len(self.m)): - c1,c2, _,_ = self.im[i].implicit.shape - self.m[i].bias *= self.im[i].implicit.reshape(c2) - self.m[i].weight *= self.im[i].implicit.transpose(0,1) - - @staticmethod - def _make_grid(nx=20, ny=20): - yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) - return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() - - def convert(self, z): - z = torch.cat(z, 1) - box = z[:, :, :4] - conf = z[:, :, 4:5] - score = z[:, :, 5:] - score *= conf - convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]], - dtype=torch.float32, - device=z.device) - box @= convert_matrix - return (box, score) - - -class IBin(nn.Module): - stride = None # strides computed during build - export = False # onnx export - - def __init__(self, nc=80, anchors=(), ch=(), bin_count=21): # detection layer - super(IBin, self).__init__() - self.nc = nc # number of classes - self.bin_count = bin_count - - self.w_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0) - self.h_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0) - # classes, x,y,obj - self.no = nc + 3 + \ - self.w_bin_sigmoid.get_length() + self.h_bin_sigmoid.get_length() # w-bce, h-bce - # + self.x_bin_sigmoid.get_length() + self.y_bin_sigmoid.get_length() - - self.nl = len(anchors) # number of detection layers - self.na = len(anchors[0]) // 2 # number of anchors - self.grid = [torch.zeros(1)] * self.nl # init grid - a = torch.tensor(anchors).float().view(self.nl, -1, 2) - self.register_buffer('anchors', a) # shape(nl,na,2) - self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) - self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv - - self.ia = nn.ModuleList(ImplicitA(x) for x in ch) - self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch) - - def forward(self, x): - - #self.x_bin_sigmoid.use_fw_regression = True - #self.y_bin_sigmoid.use_fw_regression = True - self.w_bin_sigmoid.use_fw_regression = True - self.h_bin_sigmoid.use_fw_regression = True - - # x = x.copy() # for profiling - z = [] # inference output - self.training |= self.export - for i in range(self.nl): - x[i] = self.m[i](self.ia[i](x[i])) # conv - x[i] = self.im[i](x[i]) - bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) - x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() - - if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) - - y = x[i].sigmoid() - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - #y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh - - - #px = (self.x_bin_sigmoid.forward(y[..., 0:12]) + self.grid[i][..., 0]) * self.stride[i] - #py = (self.y_bin_sigmoid.forward(y[..., 12:24]) + self.grid[i][..., 1]) * self.stride[i] - - pw = self.w_bin_sigmoid.forward(y[..., 2:24]) * self.anchor_grid[i][..., 0] - ph = self.h_bin_sigmoid.forward(y[..., 24:46]) * self.anchor_grid[i][..., 1] - - #y[..., 0] = px - #y[..., 1] = py - y[..., 2] = pw - y[..., 3] = ph - - y = torch.cat((y[..., 0:4], y[..., 46:]), dim=-1) - - z.append(y.view(bs, -1, y.shape[-1])) - - return x if self.training else (torch.cat(z, 1), x) - - @staticmethod - def _make_grid(nx=20, ny=20): - yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) - return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() - - -class Model(nn.Module): - def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes - super(Model, self).__init__() - self.traced = False - if isinstance(cfg, dict): - self.yaml = cfg # model dict - else: # is *.yaml - import yaml # for torch hub - self.yaml_file = Path(cfg).name - with open(cfg) as f: - self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict - - # Define model - ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels - if nc and nc != self.yaml['nc']: - logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") - self.yaml['nc'] = nc # override yaml value - if anchors: - logger.info(f'Overriding model.yaml anchors with anchors={anchors}') - self.yaml['anchors'] = round(anchors) # override yaml value - self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist - self.names = [str(i) for i in range(self.yaml['nc'])] # default names - # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) - - # Build strides, anchors - m = self.model[-1] # Detect() - if isinstance(m, Detect): - s = 256 # 2x min stride - m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward - check_anchor_order(m) - m.anchors /= m.stride.view(-1, 1, 1) - self.stride = m.stride - self._initialize_biases() # only run once - # print('Strides: %s' % m.stride.tolist()) - if isinstance(m, IDetect): - s = 256 # 2x min stride - m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward - check_anchor_order(m) - m.anchors /= m.stride.view(-1, 1, 1) - self.stride = m.stride - self._initialize_biases() # only run once - # print('Strides: %s' % m.stride.tolist()) - if isinstance(m, IAuxDetect): - s = 256 # 2x min stride - m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]) # forward - #print(m.stride) - check_anchor_order(m) - m.anchors /= m.stride.view(-1, 1, 1) - self.stride = m.stride - self._initialize_aux_biases() # only run once - # print('Strides: %s' % m.stride.tolist()) - if isinstance(m, IBin): - s = 256 # 2x min stride - m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward - check_anchor_order(m) - m.anchors /= m.stride.view(-1, 1, 1) - self.stride = m.stride - self._initialize_biases_bin() # only run once - # print('Strides: %s' % m.stride.tolist()) - if isinstance(m, IKeypoint): - s = 256 # 2x min stride - m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward - check_anchor_order(m) - m.anchors /= m.stride.view(-1, 1, 1) - self.stride = m.stride - self._initialize_biases_kpt() # only run once - # print('Strides: %s' % m.stride.tolist()) - - # Init weights, biases - initialize_weights(self) - self.info() - logger.info('') - - def forward(self, x, augment=False, profile=False): - if augment: - img_size = x.shape[-2:] # height, width - s = [1, 0.83, 0.67] # scales - f = [None, 3, None] # flips (2-ud, 3-lr) - y = [] # outputs - for si, fi in zip(s, f): - xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) - yi = self.forward_once(xi)[0] # forward - # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save - yi[..., :4] /= si # de-scale - if fi == 2: - yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud - elif fi == 3: - yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr - y.append(yi) - return torch.cat(y, 1), None # augmented inference, train - else: - return self.forward_once(x, profile) # single-scale inference, train - - def forward_once(self, x, profile=False): - y, dt = [], [] # outputs - for m in self.model: - if m.f != -1: # if not from previous layer - x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers - - if not hasattr(self, 'traced'): - self.traced=False - - if self.traced: - if isinstance(m, Detect) or isinstance(m, IDetect) or isinstance(m, IAuxDetect) or isinstance(m, IKeypoint): - break - - if profile: - c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin)) - o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS - for _ in range(10): - m(x.copy() if c else x) - t = time_synchronized() - for _ in range(10): - m(x.copy() if c else x) - dt.append((time_synchronized() - t) * 100) - print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type)) - - x = m(x) # run - - y.append(x if m.i in self.save else None) # save output - - if profile: - print('%.1fms total' % sum(dt)) - return x - - def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency - # https://arxiv.org/abs/1708.02002 section 3.3 - # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. - m = self.model[-1] # Detect() module - for mi, s in zip(m.m, m.stride): # from - b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) - b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) - b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls - mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) - - def _initialize_aux_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency - # https://arxiv.org/abs/1708.02002 section 3.3 - # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. - m = self.model[-1] # Detect() module - for mi, mi2, s in zip(m.m, m.m2, m.stride): # from - b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) - b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) - b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls - mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) - b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85) - b2.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) - b2.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls - mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True) - - def _initialize_biases_bin(self, cf=None): # initialize biases into Detect(), cf is class frequency - # https://arxiv.org/abs/1708.02002 section 3.3 - # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. - m = self.model[-1] # Bin() module - bc = m.bin_count - for mi, s in zip(m.m, m.stride): # from - b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) - old = b[:, (0,1,2,bc+3)].data - obj_idx = 2*bc+4 - b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99)) - b[:, obj_idx].data += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) - b[:, (obj_idx+1):].data += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls - b[:, (0,1,2,bc+3)].data = old - mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) - - def _initialize_biases_kpt(self, cf=None): # initialize biases into Detect(), cf is class frequency - # https://arxiv.org/abs/1708.02002 section 3.3 - # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. - m = self.model[-1] # Detect() module - for mi, s in zip(m.m, m.stride): # from - b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) - b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) - b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls - mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) - - def _print_biases(self): - m = self.model[-1] # Detect() module - for mi in m.m: # from - b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) - print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) - - # def _print_weights(self): - # for m in self.model.modules(): - # if type(m) is Bottleneck: - # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights - - def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers - print('Fusing layers... ') - for m in self.model.modules(): - if isinstance(m, RepConv): - #print(f" fuse_repvgg_block") - m.fuse_repvgg_block() - elif isinstance(m, RepConv_OREPA): - #print(f" switch_to_deploy") - m.switch_to_deploy() - elif type(m) is Conv and hasattr(m, 'bn'): - m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv - delattr(m, 'bn') # remove batchnorm - m.forward = m.fuseforward # update forward - elif isinstance(m, (IDetect, IAuxDetect)): - m.fuse() - m.forward = m.fuseforward - self.info() - return self - - def nms(self, mode=True): # add or remove NMS module - present = type(self.model[-1]) is NMS # last layer is NMS - if mode and not present: - print('Adding NMS... ') - m = NMS() # module - m.f = -1 # from - m.i = self.model[-1].i + 1 # index - self.model.add_module(name='%s' % m.i, module=m) # add - self.eval() - elif not mode and present: - print('Removing NMS... ') - self.model = self.model[:-1] # remove - return self - - def autoshape(self): # add autoShape module - print('Adding autoShape... ') - m = autoShape(self) # wrap model - copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes - return m - - def info(self, verbose=False, img_size=640): # print model information - model_info(self, verbose, img_size) - - -def parse_model(d, ch): # model_dict, input_channels(3) - logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) - anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] - na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors - no = na * (nc + 5) # number of outputs = anchors * (classes + 5) - - layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out - for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args - m = eval(m) if isinstance(m, str) else m # eval strings - for j, a in enumerate(args): - try: - args[j] = eval(a) if isinstance(a, str) else a # eval strings - except: - pass - - n = max(round(n * gd), 1) if n > 1 else n # depth gain - if m in [nn.Conv2d, Conv, RobustConv, RobustConv2, DWConv, GhostConv, RepConv, RepConv_OREPA, DownC, - SPP, SPPF, SPPCSPC, GhostSPPCSPC, MixConv2d, Focus, Stem, GhostStem, CrossConv, - Bottleneck, BottleneckCSPA, BottleneckCSPB, BottleneckCSPC, - RepBottleneck, RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC, - Res, ResCSPA, ResCSPB, ResCSPC, - RepRes, RepResCSPA, RepResCSPB, RepResCSPC, - ResX, ResXCSPA, ResXCSPB, ResXCSPC, - RepResX, RepResXCSPA, RepResXCSPB, RepResXCSPC, - Ghost, GhostCSPA, GhostCSPB, GhostCSPC, - SwinTransformerBlock, STCSPA, STCSPB, STCSPC, - SwinTransformer2Block, ST2CSPA, ST2CSPB, ST2CSPC]: - c1, c2 = ch[f], args[0] - if c2 != no: # if not output - c2 = make_divisible(c2 * gw, 8) - - args = [c1, c2, *args[1:]] - if m in [DownC, SPPCSPC, GhostSPPCSPC, - BottleneckCSPA, BottleneckCSPB, BottleneckCSPC, - RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC, - ResCSPA, ResCSPB, ResCSPC, - RepResCSPA, RepResCSPB, RepResCSPC, - ResXCSPA, ResXCSPB, ResXCSPC, - RepResXCSPA, RepResXCSPB, RepResXCSPC, - GhostCSPA, GhostCSPB, GhostCSPC, - STCSPA, STCSPB, STCSPC, - ST2CSPA, ST2CSPB, ST2CSPC]: - args.insert(2, n) # number of repeats - n = 1 - elif m is nn.BatchNorm2d: - args = [ch[f]] - elif m is Concat: - c2 = sum([ch[x] for x in f]) - elif m is Chuncat: - c2 = sum([ch[x] for x in f]) - elif m is Shortcut: - c2 = ch[f[0]] - elif m is Foldcut: - c2 = ch[f] // 2 - elif m in [Detect, IDetect, IAuxDetect, IBin, IKeypoint]: - args.append([ch[x] for x in f]) - if isinstance(args[1], int): # number of anchors - args[1] = [list(range(args[1] * 2))] * len(f) - elif m is ReOrg: - c2 = ch[f] * 4 - elif m is Contract: - c2 = ch[f] * args[0] ** 2 - elif m is Expand: - c2 = ch[f] // args[0] ** 2 - else: - c2 = ch[f] - - m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module - t = str(m)[8:-2].replace('__main__.', '') # module type - np = sum([x.numel() for x in m_.parameters()]) # number params - m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params - logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print - save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist - layers.append(m_) - if i == 0: - ch = [] - ch.append(c2) - return nn.Sequential(*layers), sorted(save) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--cfg', type=str, default='yolor-csp-c.yaml', help='model.yaml') - parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') - parser.add_argument('--profile', action='store_true', help='profile model speed') - opt = parser.parse_args() - opt.cfg = check_file(opt.cfg) # check file - set_logging() - device = select_device(opt.device) - - # Create model - model = Model(opt.cfg).to(device) - model.train() - - if opt.profile: - img = torch.rand(1, 3, 640, 640).to(device) - y = model(img, profile=True) - - # Profile - # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) - # y = model(img, profile=True) - - # Tensorboard - # from torch.utils.tensorboard import SummaryWriter - # tb_writer = SummaryWriter() - # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/") - # tb_writer.add_graph(model.model, img) # add model to tensorboard - # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard diff --git a/spaces/SarthakSidhant/Go-Cattle/diseases/pink tooth (actinomycosis).md b/spaces/SarthakSidhant/Go-Cattle/diseases/pink tooth (actinomycosis).md deleted file mode 100644 index 38f6552f44e0cd3f233c1f8dfa769f60e18baf91..0000000000000000000000000000000000000000 --- a/spaces/SarthakSidhant/Go-Cattle/diseases/pink tooth (actinomycosis).md +++ /dev/null @@ -1,31 +0,0 @@ -## Pink tooth (actinomycosis) - -**Information:** Pink tooth, also known as **actinomycosis**, is a bacterial infection that affects the teeth of cattle. It is caused by bacteria called **Actinomyces bovis**. - -**Symptoms:** - -* Pink discoloration of the teeth -* Pus or discharge from the teeth -* Pain -* Difficulty chewing -* Loss of teeth - -**Remedies:** - -* There is no specific cure for pink tooth. -* Treatment is usually supportive and may include: - * Removing the affected tooth - * Treating with antibiotics - * Providing pain medication - * Keeping the area clean and dry - -**Causes:** - -* Pink tooth is caused by bacteria called **Actinomyces bovis**. -* These bacteria live in the soil and can enter the teeth of cattle through cuts or cracks in the teeth. -* Pink tooth is more common in cattle that are stressed or malnourished. - -**Prevention:** - -* The best way to prevent pink tooth is to keep cattle's teeth clean and free of cuts or cracks. -* Cattle should be vaccinated against pink tooth. diff --git a/spaces/SeViLA/SeViLA/lavis/models/blip2_models/blip2_qformer.py b/spaces/SeViLA/SeViLA/lavis/models/blip2_models/blip2_qformer.py deleted file mode 100644 index 9a68812088937d6a38e3156339d3cfd5d7f3c075..0000000000000000000000000000000000000000 --- a/spaces/SeViLA/SeViLA/lavis/models/blip2_models/blip2_qformer.py +++ /dev/null @@ -1,506 +0,0 @@ -""" - Copyright (c) 2023, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" -import logging - -import torch -import torch.distributed as dist -import torch.nn as nn -from torch.cuda.amp import autocast as autocast -from torch.nn import functional as F - -from lavis.common.registry import registry -from lavis.models.base_model import all_gather_with_grad, concat_all_gather -from lavis.models.blip2_models.blip2 import ( - Blip2Base, - compute_sim_matrix, - disabled_train, -) -from lavis.models.blip_models.blip_outputs import BlipOutput, BlipOutputFeatures - - -@registry.register_model("blip2") -@registry.register_model("blip2_feature_extractor") -class Blip2Qformer(Blip2Base): - """ - BLIP2 first-stage model with Q-former and ViT. - Supported model types: - - pretrained: pretrained model - - coco: fintuned model on coco - Usage: - >>> from lavis.models import load_model - >>> model = load_model("blip2", "pretrain") - """ - - PRETRAINED_MODEL_CONFIG_DICT = { - "pretrain": "configs/models/blip2/blip2_pretrain.yaml", - "coco": "configs/models/blip2/blip2_coco.yaml", - } - - def __init__( - self, - img_size=224, - drop_path_rate=0, - use_grad_checkpoint=False, - vit_precision="fp16", - freeze_vit=True, - num_query_token=32, - embed_dim=256, - max_txt_len=32, - ): - super().__init__() - - self.tokenizer = self.init_tokenizer() - - self.visual_encoder, self.ln_vision = self.init_vision_encoder( - img_size, drop_path_rate, use_grad_checkpoint, vit_precision - ) - if freeze_vit: - for name, param in self.visual_encoder.named_parameters(): - param.requires_grad = False - self.visual_encoder = self.visual_encoder.eval() - self.visual_encoder.train = disabled_train - logging.info("freeze vision encoder") - self.Qformer, self.query_tokens = self.init_Qformer( - num_query_token, self.visual_encoder.num_features - ) - self.Qformer.resize_token_embeddings(len(self.tokenizer)) - state_dict = self.Qformer.state_dict() - for name, param in self.Qformer.named_parameters(): - if "_query" in name: - key_orig = name.replace("_query", "") - param.data.copy_(state_dict[key_orig]) - - self.vision_proj = nn.Linear(self.Qformer.config.hidden_size, embed_dim) - self.text_proj = nn.Linear(self.Qformer.config.hidden_size, embed_dim) - - self.itm_head = nn.Linear(self.Qformer.config.hidden_size, 2) - - self.temp = nn.Parameter(0.07 * torch.ones([])) - - self.max_txt_len = max_txt_len - - def forward(self, samples): - image = samples["image"] - text = samples["text_input"] - - image_embeds = self.ln_vision(self.visual_encoder(image)) - image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( - image.device - ) - - query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1) - - query_output = self.Qformer.bert( - query_embeds=query_tokens, - encoder_hidden_states=image_embeds, - encoder_attention_mask=image_atts, - use_cache=True, - return_dict=True, - ) - - image_feats = F.normalize( - self.vision_proj(query_output.last_hidden_state), dim=-1 - ) - - text_tokens = self.tokenizer( - text, - padding="max_length", - truncation=True, - max_length=self.max_txt_len, - return_tensors="pt", - ).to(image.device) - text_output = self.Qformer.bert( - text_tokens.input_ids, - attention_mask=text_tokens.attention_mask, - return_dict=True, - ) - text_feat = F.normalize( - self.text_proj(text_output.last_hidden_state[:, 0, :]), dim=-1 - ) - - ###============== Image-text Contrastive ===================### - image_feats_all = concat_all_gather( - image_feats - ) # [batch_size*num_gpu, num_query_tokens, embed_dim] - text_feat_all = concat_all_gather(text_feat) # [batch_size*num_gpu, embed_dim] - - sim_q2t = torch.matmul( - image_feats.unsqueeze(1), text_feat_all.unsqueeze(-1) - ).squeeze() - # [batch_size, batch_size*num_gpu, num_query_tokens] - - # image-text similarity: aggregate across all query tokens - sim_i2t, _ = sim_q2t.max(-1) - sim_i2t = sim_i2t / self.temp - - # text-query similarity: [batch_size, batch_size*num_gpu, num_query_tokens] - sim_t2q = torch.matmul( - text_feat.unsqueeze(1).unsqueeze(1), image_feats_all.permute(0, 2, 1) - ).squeeze() - - # text-image similarity: aggregate across all query tokens - sim_t2i, _ = sim_t2q.max(-1) - sim_t2i = sim_t2i / self.temp # [batch_size, batch_size*num_gpu] - - rank = dist.get_rank() - bs = image.size(0) - targets = torch.linspace(rank * bs, rank * bs + bs - 1, bs, dtype=int).to( - image.device - ) - - loss_itc = ( - F.cross_entropy(sim_i2t, targets, label_smoothing=0.1) - + F.cross_entropy(sim_t2i, targets, label_smoothing=0.1) - ) / 2 - - ###============== Image-text Matching ===================### - text_input_ids_world = concat_all_gather(text_tokens.input_ids) - text_attention_mask_world = concat_all_gather(text_tokens.attention_mask) - image_embeds_world = all_gather_with_grad(image_embeds) - with torch.no_grad(): - weights_t2i = F.softmax(sim_t2i, dim=1) + 1e-4 - weights_t2i[:, rank * bs : rank * bs + bs].fill_diagonal_(0) - weights_i2t = F.softmax(sim_i2t, dim=1) + 1e-4 - weights_i2t[:, rank * bs : rank * bs + bs].fill_diagonal_(0) - - # select a negative image for each text - image_embeds_neg = [] - for b in range(bs): - neg_idx = torch.multinomial(weights_t2i[b], 1).item() - image_embeds_neg.append(image_embeds_world[neg_idx]) - image_embeds_neg = torch.stack(image_embeds_neg, dim=0) - - # select a negative text for each image - text_ids_neg = [] - text_atts_neg = [] - for b in range(bs): - neg_idx = torch.multinomial(weights_i2t[b], 1).item() - text_ids_neg.append(text_input_ids_world[neg_idx]) - text_atts_neg.append(text_attention_mask_world[neg_idx]) - - text_ids_neg = torch.stack(text_ids_neg, dim=0) - text_atts_neg = torch.stack(text_atts_neg, dim=0) - - text_ids_all = torch.cat( - [text_tokens.input_ids, text_tokens.input_ids, text_ids_neg], dim=0 - ) # pos, pos, neg - text_atts_all = torch.cat( - [text_tokens.attention_mask, text_tokens.attention_mask, text_atts_neg], - dim=0, - ) - - query_tokens_itm = self.query_tokens.expand(text_ids_all.shape[0], -1, -1) - query_atts_itm = torch.ones(query_tokens_itm.size()[:-1], dtype=torch.long).to( - image.device - ) - attention_mask_all = torch.cat([query_atts_itm, text_atts_all], dim=1) - - image_embeds_all = torch.cat( - [image_embeds, image_embeds_neg, image_embeds], dim=0 - ) # pos, neg, pos - image_atts_all = torch.ones(image_embeds_all.size()[:-1], dtype=torch.long).to( - image.device - ) - - output_itm = self.Qformer.bert( - text_ids_all, - query_embeds=query_tokens_itm, - attention_mask=attention_mask_all, - encoder_hidden_states=image_embeds_all, - encoder_attention_mask=image_atts_all, - return_dict=True, - ) - - vl_embeddings = output_itm.last_hidden_state[:, : query_tokens_itm.size(1), :] - vl_output = self.itm_head(vl_embeddings) - logits = vl_output.mean(dim=1) - - itm_labels = torch.cat( - [torch.ones(bs, dtype=torch.long), torch.zeros(2 * bs, dtype=torch.long)], - dim=0, - ).to(image.device) - loss_itm = F.cross_entropy(logits, itm_labels) - - ##================= Image Captioning ========================## - decoder_input_ids = text_tokens.input_ids.clone() - decoder_input_ids[:, 0] = self.tokenizer.bos_token_id - labels = decoder_input_ids.masked_fill( - decoder_input_ids == self.tokenizer.pad_token_id, -100 - ) - - query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to( - image.device - ) - attention_mask = torch.cat([query_atts, text_tokens.attention_mask], dim=1) - lm_output = self.Qformer( - decoder_input_ids, - attention_mask=attention_mask, - past_key_values=query_output.past_key_values, - return_dict=True, - labels=labels, - ) - - loss_lm = lm_output.loss - - return BlipOutput( - loss=loss_itc + loss_itm + loss_lm, - loss_itc=loss_itc, - loss_itm=loss_itm, - loss_lm=loss_lm, - ) - - @torch.no_grad() - def generate( - self, - samples, - use_nucleus_sampling=False, - num_beams=3, - max_length=30, - min_length=10, - top_p=0.9, - repetition_penalty=1.0, - ): - """ - Args: - samples (dict): A dictionary containing the following keys: - - image (torch.Tensor): A tensor of shape (batch_size, 3, H, W) - use_nucleus_sampling (bool): Whether to use nucleus sampling. If False, use top-k sampling. - num_beams (int): Number of beams for beam search. 1 means no beam search. - max_length (int): The maximum length of the sequence to be generated. - min_length (int): The minimum length of the sequence to be generated. - top_p (float): The cumulative probability for nucleus sampling. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty. - num_captions (int): Number of captions to be generated for each image. - Returns: - captions (list): A list of strings of length batch_size * num_captions. - """ - image = samples["image"] - image_embeds = self.ln_vision(self.visual_encoder(image)) - - if not use_nucleus_sampling: - image_embeds = image_embeds.repeat_interleave(num_beams, dim=0) - else: - num_beams = 1 - image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( - image.device - ) - - model_kwargs = { - "encoder_hidden_states": image_embeds, - "encoder_attention_mask": image_atts, - } - - input_ids = ( - torch.LongTensor(image.size(0), 1) - .fill_(self.tokenizer.bos_token_id) - .to(image.device) - ) - query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1) - - outputs = self.Qformer.generate( - input_ids=input_ids, - query_embeds=query_tokens, - max_length=max_length, - min_length=min_length, - num_beams=num_beams, - do_sample=use_nucleus_sampling, - top_p=top_p, - eos_token_id=self.tokenizer.sep_token_id, - pad_token_id=self.tokenizer.pad_token_id, - **model_kwargs - ) - captions = self.tokenizer.batch_decode(outputs, skip_special_tokens=True) - return captions - - def forward_image(self, image): - image_embeds = self.ln_vision(self.visual_encoder(image)) - image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( - image.device - ) - - query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1) - - query_output = self.Qformer.bert( - query_embeds=query_tokens, - encoder_hidden_states=image_embeds, - encoder_attention_mask=image_atts, - return_dict=True, - ) - return query_output.last_hidden_state, image_embeds - - def forward_text(self, text_tokens): - text_output = self.Qformer.bert( - text_tokens.input_ids, - attention_mask=text_tokens.attention_mask, - return_dict=True, - ) - return text_output.last_hidden_state[:, 0, :] - - def compute_itm(self, image_inputs, text_ids, text_atts): - image_atts = torch.ones(image_inputs.size()[:-1], dtype=torch.long).to( - image_inputs.device - ) - query_tokens = self.query_tokens.expand(image_inputs.shape[0], -1, -1) - query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to( - image_inputs.device - ) - attention_mask = torch.cat([query_atts, text_atts], dim=1) - output_itm = self.Qformer.bert( - text_ids, - query_embeds=query_tokens, - attention_mask=attention_mask, - encoder_hidden_states=image_inputs, - encoder_attention_mask=image_atts, - return_dict=True, - ) - vl_embeddings = output_itm.last_hidden_state[:, : query_tokens.size(1), :] - itm_logit = self.itm_head(vl_embeddings) - itm_logit = itm_logit[:, :, 1].mean(dim=1) - return itm_logit - - @torch.no_grad() - def extract_features(self, samples, mode="multimodal"): - """ - Extract features for multimodal or unimodal samples. - Args: - samples (dict): A dictionary of samples, containing the following keys: - - image (torch.Tensor): A tensor of shape (B, C, H, W) containing the image. - Raw images should be preprocessed before being passed to feature extractor. - - text_input (list): A list of strings containing the text, length B. - mode (str): The mode of feature extraction. Can be either "multimodal", "text" or "image". - If "multimodal", return image features and multimodal features; - if "text", return text features; - if "image", return image features. - Default: "multimodal". - Returns: - BlipOutputFeatures: A BlipOutputFeatures object containing the features. - See lavis/models/blip_models/blip_outputs.py for more details. - """ - image = samples.get("image") - caption = samples.get("text_input") - - # assert mode is one of "image", "text", "multimodal" - assert mode in [ - "image", - "text", - "multimodal", - ], "mode must be one of 'image', 'text', 'multimodal'" - - # initalize output - image_embeds, text_embeds, multimodal_embeds = None, None, None - image_features, text_features = None, None - - if mode == "image": - assert ( - image is not None - ), "Image is not provided for mode 'image' or 'multimodal'" - # return query features - image_embeds_frozen = self.ln_vision(self.visual_encoder(image)) - image_atts = torch.ones( - image_embeds_frozen.size()[:-1], dtype=torch.long - ).to(self.device) - query_tokens = self.query_tokens.expand( - image_embeds_frozen.shape[0], -1, -1 - ) - - query_output = self.Qformer.bert( - query_embeds=query_tokens, - encoder_hidden_states=image_embeds_frozen, - encoder_attention_mask=image_atts, - return_dict=True, - ) - image_embeds = query_output.last_hidden_state - image_features = F.normalize(self.vision_proj(image_embeds), dim=-1) - - elif mode == "text": - assert ( - caption is not None - ), "text input is None for mode 'text' or 'multimodal'" - - # return text features - text = self.tokenizer(caption, return_tensors="pt", padding=True).to( - self.device - ) - - text_output = self.Qformer.bert( - text.input_ids, - attention_mask=text.attention_mask, - return_dict=True, - ) - text_embeds = text_output.last_hidden_state - text_features = self.text_proj(text_embeds) - text_features = F.normalize(text_features, dim=-1) - - elif mode == "multimodal": - # return multimodel query features - image_embeds_frozen = self.ln_vision(self.visual_encoder(image)) - image_atts = torch.ones( - image_embeds_frozen.size()[:-1], dtype=torch.long - ).to(self.device) - query_tokens = self.query_tokens.expand( - image_embeds_frozen.shape[0], -1, -1 - ) - query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to( - self.device - ) - - text = self.tokenizer(caption, return_tensors="pt", padding=True).to( - self.device - ) - attention_mask = torch.cat([query_atts, text.attention_mask], dim=1) - - output = self.Qformer.bert( - text.input_ids, - query_embeds=query_tokens, - attention_mask=attention_mask, - encoder_hidden_states=image_embeds_frozen, - encoder_attention_mask=image_atts, - return_dict=True, - ) - - multimodal_embeds = output.last_hidden_state[:, : query_tokens.size(1), :] - - return BlipOutputFeatures( - image_embeds=image_embeds, - image_embeds_proj=image_features, - text_embeds=text_embeds, - text_embeds_proj=text_features, - multimodal_embeds=multimodal_embeds, - ) - - @classmethod - def from_config(cls, cfg): - img_size = cfg.get("image_size") - num_query_token = cfg.get("num_query_token") - - drop_path_rate = cfg.get("drop_path_rate", 0) - use_grad_checkpoint = cfg.get("use_grad_checkpoint", False) - vit_precision = cfg.get("vit_precision", "fp16") - freeze_vit = cfg.get("freeze_vit", True) - - max_txt_len = cfg.get("max_txt_len", 32) - - model = cls( - img_size=img_size, - drop_path_rate=drop_path_rate, - use_grad_checkpoint=use_grad_checkpoint, - vit_precision=vit_precision, - freeze_vit=freeze_vit, - num_query_token=num_query_token, - max_txt_len=max_txt_len, - ) - model.load_checkpoint_from_config(cfg) - - return model - - def compute_sim_matrix(self, data_loader, task_cfg): - """ - Compute similarity i2t, t2i matrix for the given data loader. - """ - k_test = task_cfg.k_test - - return compute_sim_matrix(model=self, data_loader=data_loader, k_test=k_test) diff --git a/spaces/SmilingWolf/danbooru2022_image_similarity/app.py b/spaces/SmilingWolf/danbooru2022_image_similarity/app.py deleted file mode 100644 index 202ac6e3f11ffb39a5fed71546d26d581b13e8ce..0000000000000000000000000000000000000000 --- a/spaces/SmilingWolf/danbooru2022_image_similarity/app.py +++ /dev/null @@ -1,210 +0,0 @@ -import argparse -import functools -import json -import os -from pathlib import Path - -import faiss -import gradio as gr -import numpy as np -import PIL.Image -import requests -import tensorflow as tf -from huggingface_hub import hf_hub_download - -from Utils import dbimutils - -TITLE = "## Danbooru Explorer" -DESCRIPTION = """ -Image similarity-based retrieval tool using: -- [SmilingWolf/wd-v1-4-convnext-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2) as feature extractor -- [Faiss](https://github.com/facebookresearch/faiss) and [autofaiss](https://github.com/criteo/autofaiss) for indexing -""" - -HF_TOKEN = os.environ["HF_TOKEN"] -CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger-v2" -CONV_MODEL_REVISION = "v2.0" -CONV_FEXT_LAYER = "predictions_norm" - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser() - parser.add_argument("--share", action="store_true") - return parser.parse_args() - - -def download_model(model_repo, model_revision): - model_files = [ - {"filename": "saved_model.pb", "subfolder": ""}, - {"filename": "keras_metadata.pb", "subfolder": ""}, - {"filename": "variables.index", "subfolder": "variables"}, - {"filename": "variables.data-00000-of-00001", "subfolder": "variables"}, - ] - - model_file_paths = [] - for elem in model_files: - model_file_paths.append( - Path( - hf_hub_download( - model_repo, revision=model_revision, use_auth_token=HF_TOKEN, **elem - ) - ) - ) - - model_path = model_file_paths[0].parents[0] - return model_path - - -def load_model(model_repo, model_revision, feature_extraction_layer): - model_path = download_model(model_repo, model_revision) - full_model = tf.keras.models.load_model(model_path) - model = tf.keras.models.Model( - full_model.inputs, full_model.get_layer(feature_extraction_layer).output - ) - return model - - -def danbooru_id_to_url(image_id, selected_ratings, api_username="", api_key=""): - headers = {"User-Agent": "image_similarity_tool"} - ratings_to_letters = { - "General": "g", - "Sensitive": "s", - "Questionable": "q", - "Explicit": "e", - } - - acceptable_ratings = [ratings_to_letters[x] for x in selected_ratings] - - image_url = f"https://danbooru.donmai.us/posts/{image_id}.json" - if api_username != "" and api_key != "": - image_url = f"{image_url}?api_key={api_key}&login={api_username}" - - r = requests.get(image_url, headers=headers) - if r.status_code != 200: - return None - - content = json.loads(r.text) - image_url = content["large_file_url"] if "large_file_url" in content else None - image_url = image_url if content["rating"] in acceptable_ratings else None - return image_url - - -class SimilaritySearcher: - def __init__(self, model, images_ids): - self.knn_index = None - self.knn_metric = None - - self.model = model - self.images_ids = images_ids - - def change_index(self, knn_metric): - if knn_metric == self.knn_metric: - return - - if knn_metric == "ip": - self.knn_index = faiss.read_index("index/ip_knn.index") - config = json.loads(open("index/ip_infos.json").read())["index_param"] - elif knn_metric == "cosine": - self.knn_index = faiss.read_index("index/cosine_knn.index") - config = json.loads(open("index/cosine_infos.json").read())["index_param"] - - faiss.ParameterSpace().set_index_parameters(self.knn_index, config) - self.knn_metric = knn_metric - - def predict( - self, image, selected_ratings, knn_metric, api_username, api_key, n_neighbours - ): - _, height, width, _ = self.model.inputs[0].shape - - self.change_index(knn_metric) - - # Alpha to white - image = image.convert("RGBA") - new_image = PIL.Image.new("RGBA", image.size, "WHITE") - new_image.paste(image, mask=image) - image = new_image.convert("RGB") - image = np.asarray(image) - - # PIL RGB to OpenCV BGR - image = image[:, :, ::-1] - - image = dbimutils.make_square(image, height) - image = dbimutils.smart_resize(image, height) - image = image.astype(np.float32) - image = np.expand_dims(image, 0) - target = self.model(image).numpy() - - if self.knn_metric == "cosine": - faiss.normalize_L2(target) - - dists, indexes = self.knn_index.search(target, k=n_neighbours) - neighbours_ids = self.images_ids[indexes][0] - neighbours_ids = [int(x) for x in neighbours_ids] - - captions = [] - image_urls = [] - for image_id, dist in zip(neighbours_ids, dists[0]): - current_url = danbooru_id_to_url( - image_id, selected_ratings, api_username, api_key - ) - if current_url is not None: - image_urls.append(current_url) - captions.append(f"{image_id}/{dist:.2f}") - return list(zip(image_urls, captions)) - - -def main(): - args = parse_args() - model = load_model(CONV_MODEL_REPO, CONV_MODEL_REVISION, CONV_FEXT_LAYER) - images_ids = np.load("index/cosine_ids.npy") - - searcher = SimilaritySearcher(model=model, images_ids=images_ids) - - with gr.Blocks() as demo: - gr.Markdown(TITLE) - gr.Markdown(DESCRIPTION) - - with gr.Row(): - input = gr.Image(type="pil", label="Input") - with gr.Column(): - with gr.Row(): - api_username = gr.Textbox(label="Danbooru API Username") - api_key = gr.Textbox(label="Danbooru API Key") - selected_ratings = gr.CheckboxGroup( - choices=["General", "Sensitive", "Questionable", "Explicit"], - value=["General", "Sensitive"], - label="Ratings", - ) - with gr.Row(): - selected_metric = gr.Radio( - choices=["cosine"], - value="cosine", - label="Metric selection", - visible=False, - ) - n_neighbours = gr.Slider( - minimum=1, maximum=20, value=5, step=1, label="# of images" - ) - find_btn = gr.Button("Find similar images") - similar_images = gr.Gallery(label="Similar images") - - similar_images.style(grid=5) - find_btn.click( - fn=searcher.predict, - inputs=[ - input, - selected_ratings, - selected_metric, - api_username, - api_key, - n_neighbours, - ], - outputs=[similar_images], - ) - - demo.queue() - demo.launch(share=args.share) - - -if __name__ == "__main__": - main() diff --git a/spaces/Smols/AWS/README.md b/spaces/Smols/AWS/README.md deleted file mode 100644 index 4d56093735c1ce46f1ffb025b196ef5eae036366..0000000000000000000000000000000000000000 --- a/spaces/Smols/AWS/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: AWS Clauders -emoji: 🦀 -colorFrom: yellow -colorTo: blue -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/SpacesExamples/single_file_phx_bumblebee_ml/Dockerfile b/spaces/SpacesExamples/single_file_phx_bumblebee_ml/Dockerfile deleted file mode 100644 index 8cdcdf6f8d24f5b18fd5348163a156b441383324..0000000000000000000000000000000000000000 --- a/spaces/SpacesExamples/single_file_phx_bumblebee_ml/Dockerfile +++ /dev/null @@ -1,71 +0,0 @@ -# Find eligible builder and runner images on Docker Hub. We use Ubuntu/Debian instead of -# Alpine to avoid DNS resolution issues in production. -# -# https://hub.docker.com/r/hexpm/elixir/tags?page=1&name=ubuntu -# https://hub.docker.com/_/ubuntu?tab=tags -# -# -# This file is based on these images: -# -# - https://hub.docker.com/r/hexpm/elixir/tags - for the build image -# - https://hub.docker.com/_/debian?tab=tags&page=1&name=bullseye-20210902-slim - for the release image -# - https://pkgs.org/ - resource for finding needed packages -# - Ex: hexpm/elixir:1.13.4-erlang-24.0.1-debian-bullseye-20210902-slim -# -ARG ELIXIR_VERSION=1.14.2 -ARG OTP_VERSION=25.1 -ARG DEBIAN_VERSION=bullseye-20220801-slim - -ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}" -ARG RUNNER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}" - -FROM ${BUILDER_IMAGE} as builder - -# install build dependencies -RUN apt-get update -y && apt-get install -y build-essential git curl \ - && apt-get clean && rm -f /var/lib/apt/lists/*_* - -# prepare build dir -WORKDIR /app - -# set build ENV -ENV MIX_ENV="prod" -ENV MIX_HOME="/app/.mix" -ENV EXS_DRY_RUN="true" -ENV MIX_INSTALL_DIR="/app/.mix" -ENV BUMBLEBEE_CACHE_DIR="/app/.bumblebee" - -# install hex + rebar -RUN mix local.hex --force && \ - mix local.rebar --force - -# install mix dependencies -COPY run.exs ./ -RUN elixir ./run.exs - -# start a new build stage so that the final image will only contain -# the compiled release and other runtime necessities -FROM ${RUNNER_IMAGE} - -# install build dependencies -RUN apt-get update -y && apt-get install -y build-essential git curl \ - && apt-get clean && rm -f /var/lib/apt/lists/*_* - -WORKDIR "/app" - -# set runner ENV -ENV MIX_ENV="prod" -ENV MIX_HOME="/app/.mix" -ENV MIX_INSTALL_DIR="/app/.mix" -ENV BUMBLEBEE_CACHE_DIR="/app/.bumblebee" -ENV SHELL=/bin/bash -ENV PORT=7860 - -EXPOSE 7860 - -# Only copy the final release from the build stage -COPY --from=builder --chown=nobody:root /app/.mix/ ./.mix -COPY --from=builder --chown=nobody:root /app/.bumblebee/ ./.bumblebee -COPY --from=builder --chown=nobody:root /app/run.exs ./ - -CMD ["elixir", "/app/run.exs"] diff --git a/spaces/SuYuanS/AudioCraft_Plus/tests/common_utils/wav_utils.py b/spaces/SuYuanS/AudioCraft_Plus/tests/common_utils/wav_utils.py deleted file mode 100644 index d3a563ee1749a58217ece55c9a08b8d93c0fc386..0000000000000000000000000000000000000000 --- a/spaces/SuYuanS/AudioCraft_Plus/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/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/MpegImagePlugin.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/MpegImagePlugin.py deleted file mode 100644 index d96d3a11c4966e94a53c67f13c3bf8f7987c0c83..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/PIL/MpegImagePlugin.py +++ /dev/null @@ -1,82 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# MPEG file handling -# -# History: -# 95-09-09 fl Created -# -# Copyright (c) Secret Labs AB 1997. -# Copyright (c) Fredrik Lundh 1995. -# -# See the README file for information on usage and redistribution. -# - - -from . import Image, ImageFile -from ._binary import i8 - -# -# Bitstream parser - - -class BitStream: - def __init__(self, fp): - self.fp = fp - self.bits = 0 - self.bitbuffer = 0 - - def next(self): - return i8(self.fp.read(1)) - - def peek(self, bits): - while self.bits < bits: - c = self.next() - if c < 0: - self.bits = 0 - continue - self.bitbuffer = (self.bitbuffer << 8) + c - self.bits += 8 - return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1 - - def skip(self, bits): - while self.bits < bits: - self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1)) - self.bits += 8 - self.bits = self.bits - bits - - def read(self, bits): - v = self.peek(bits) - self.bits = self.bits - bits - return v - - -## -# Image plugin for MPEG streams. This plugin can identify a stream, -# but it cannot read it. - - -class MpegImageFile(ImageFile.ImageFile): - format = "MPEG" - format_description = "MPEG" - - def _open(self): - s = BitStream(self.fp) - - if s.read(32) != 0x1B3: - msg = "not an MPEG file" - raise SyntaxError(msg) - - self.mode = "RGB" - self._size = s.read(12), s.read(12) - - -# -------------------------------------------------------------------- -# Registry stuff - -Image.register_open(MpegImageFile.format, MpegImageFile) - -Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"]) - -Image.register_mime(MpegImageFile.format, "video/mpeg") diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/aiohttp/web_runner.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/aiohttp/web_runner.py deleted file mode 100644 index 9282bb93d37a4a3a0ada346ec7534de0ea0e893d..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/aiohttp/web_runner.py +++ /dev/null @@ -1,381 +0,0 @@ -import asyncio -import signal -import socket -from abc import ABC, abstractmethod -from typing import Any, List, Optional, Set - -from yarl import URL - -from .web_app import Application -from .web_server import Server - -try: - from ssl import SSLContext -except ImportError: - SSLContext = object # type: ignore[misc,assignment] - - -__all__ = ( - "BaseSite", - "TCPSite", - "UnixSite", - "NamedPipeSite", - "SockSite", - "BaseRunner", - "AppRunner", - "ServerRunner", - "GracefulExit", -) - - -class GracefulExit(SystemExit): - code = 1 - - -def _raise_graceful_exit() -> None: - raise GracefulExit() - - -class BaseSite(ABC): - __slots__ = ("_runner", "_shutdown_timeout", "_ssl_context", "_backlog", "_server") - - def __init__( - self, - runner: "BaseRunner", - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - ) -> None: - if runner.server is None: - raise RuntimeError("Call runner.setup() before making a site") - self._runner = runner - self._shutdown_timeout = shutdown_timeout - self._ssl_context = ssl_context - self._backlog = backlog - self._server: Optional[asyncio.AbstractServer] = None - - @property - @abstractmethod - def name(self) -> str: - pass # pragma: no cover - - @abstractmethod - async def start(self) -> None: - self._runner._reg_site(self) - - async def stop(self) -> None: - self._runner._check_site(self) - if self._server is None: - self._runner._unreg_site(self) - return # not started yet - self._server.close() - # named pipes do not have wait_closed property - if hasattr(self._server, "wait_closed"): - await self._server.wait_closed() - await self._runner.shutdown() - assert self._runner.server - await self._runner.server.shutdown(self._shutdown_timeout) - self._runner._unreg_site(self) - - -class TCPSite(BaseSite): - __slots__ = ("_host", "_port", "_reuse_address", "_reuse_port") - - def __init__( - self, - runner: "BaseRunner", - host: Optional[str] = None, - port: Optional[int] = None, - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None, - ) -> None: - super().__init__( - runner, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - self._host = host - if port is None: - port = 8443 if self._ssl_context else 8080 - self._port = port - self._reuse_address = reuse_address - self._reuse_port = reuse_port - - @property - def name(self) -> str: - scheme = "https" if self._ssl_context else "http" - host = "0.0.0.0" if self._host is None else self._host - return str(URL.build(scheme=scheme, host=host, port=self._port)) - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - self._server = await loop.create_server( - server, - self._host, - self._port, - ssl=self._ssl_context, - backlog=self._backlog, - reuse_address=self._reuse_address, - reuse_port=self._reuse_port, - ) - - -class UnixSite(BaseSite): - __slots__ = ("_path",) - - def __init__( - self, - runner: "BaseRunner", - path: str, - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - ) -> None: - super().__init__( - runner, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - self._path = path - - @property - def name(self) -> str: - scheme = "https" if self._ssl_context else "http" - return f"{scheme}://unix:{self._path}:" - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - self._server = await loop.create_unix_server( - server, self._path, ssl=self._ssl_context, backlog=self._backlog - ) - - -class NamedPipeSite(BaseSite): - __slots__ = ("_path",) - - def __init__( - self, runner: "BaseRunner", path: str, *, shutdown_timeout: float = 60.0 - ) -> None: - loop = asyncio.get_event_loop() - if not isinstance( - loop, asyncio.ProactorEventLoop # type: ignore[attr-defined] - ): - raise RuntimeError( - "Named Pipes only available in proactor" "loop under windows" - ) - super().__init__(runner, shutdown_timeout=shutdown_timeout) - self._path = path - - @property - def name(self) -> str: - return self._path - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - _server = await loop.start_serving_pipe( # type: ignore[attr-defined] - server, self._path - ) - self._server = _server[0] - - -class SockSite(BaseSite): - __slots__ = ("_sock", "_name") - - def __init__( - self, - runner: "BaseRunner", - sock: socket.socket, - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - ) -> None: - super().__init__( - runner, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - self._sock = sock - scheme = "https" if self._ssl_context else "http" - if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: - name = f"{scheme}://unix:{sock.getsockname()}:" - else: - host, port = sock.getsockname()[:2] - name = str(URL.build(scheme=scheme, host=host, port=port)) - self._name = name - - @property - def name(self) -> str: - return self._name - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - self._server = await loop.create_server( - server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog - ) - - -class BaseRunner(ABC): - __slots__ = ("_handle_signals", "_kwargs", "_server", "_sites") - - def __init__(self, *, handle_signals: bool = False, **kwargs: Any) -> None: - self._handle_signals = handle_signals - self._kwargs = kwargs - self._server: Optional[Server] = None - self._sites: List[BaseSite] = [] - - @property - def server(self) -> Optional[Server]: - return self._server - - @property - def addresses(self) -> List[Any]: - ret: List[Any] = [] - for site in self._sites: - server = site._server - if server is not None: - sockets = server.sockets - if sockets is not None: - for sock in sockets: - ret.append(sock.getsockname()) - return ret - - @property - def sites(self) -> Set[BaseSite]: - return set(self._sites) - - async def setup(self) -> None: - loop = asyncio.get_event_loop() - - if self._handle_signals: - try: - loop.add_signal_handler(signal.SIGINT, _raise_graceful_exit) - loop.add_signal_handler(signal.SIGTERM, _raise_graceful_exit) - except NotImplementedError: # pragma: no cover - # add_signal_handler is not implemented on Windows - pass - - self._server = await self._make_server() - - @abstractmethod - async def shutdown(self) -> None: - pass # pragma: no cover - - async def cleanup(self) -> None: - loop = asyncio.get_event_loop() - - # The loop over sites is intentional, an exception on gather() - # leaves self._sites in unpredictable state. - # The loop guaranties that a site is either deleted on success or - # still present on failure - for site in list(self._sites): - await site.stop() - await self._cleanup_server() - self._server = None - if self._handle_signals: - try: - loop.remove_signal_handler(signal.SIGINT) - loop.remove_signal_handler(signal.SIGTERM) - except NotImplementedError: # pragma: no cover - # remove_signal_handler is not implemented on Windows - pass - - @abstractmethod - async def _make_server(self) -> Server: - pass # pragma: no cover - - @abstractmethod - async def _cleanup_server(self) -> None: - pass # pragma: no cover - - def _reg_site(self, site: BaseSite) -> None: - if site in self._sites: - raise RuntimeError(f"Site {site} is already registered in runner {self}") - self._sites.append(site) - - def _check_site(self, site: BaseSite) -> None: - if site not in self._sites: - raise RuntimeError(f"Site {site} is not registered in runner {self}") - - def _unreg_site(self, site: BaseSite) -> None: - if site not in self._sites: - raise RuntimeError(f"Site {site} is not registered in runner {self}") - self._sites.remove(site) - - -class ServerRunner(BaseRunner): - """Low-level web server runner""" - - __slots__ = ("_web_server",) - - def __init__( - self, web_server: Server, *, handle_signals: bool = False, **kwargs: Any - ) -> None: - super().__init__(handle_signals=handle_signals, **kwargs) - self._web_server = web_server - - async def shutdown(self) -> None: - pass - - async def _make_server(self) -> Server: - return self._web_server - - async def _cleanup_server(self) -> None: - pass - - -class AppRunner(BaseRunner): - """Web Application runner""" - - __slots__ = ("_app",) - - def __init__( - self, app: Application, *, handle_signals: bool = False, **kwargs: Any - ) -> None: - super().__init__(handle_signals=handle_signals, **kwargs) - if not isinstance(app, Application): - raise TypeError( - "The first argument should be web.Application " - "instance, got {!r}".format(app) - ) - self._app = app - - @property - def app(self) -> Application: - return self._app - - async def shutdown(self) -> None: - await self._app.shutdown() - - async def _make_server(self) -> Server: - loop = asyncio.get_event_loop() - self._app._set_loop(loop) - self._app.on_startup.freeze() - await self._app.startup() - self._app.freeze() - - return self._app._make_handler(loop=loop, **self._kwargs) - - async def _cleanup_server(self) -> None: - await self._app.cleanup() diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/attrs/converters.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/attrs/converters.py deleted file mode 100644 index edfa8d3c16ac8642773651778012a3cd57005d9b..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/attrs/converters.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.converters import * # noqa diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/dateutil/_common.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/dateutil/_common.py deleted file mode 100644 index 4eb2659bd2986125fcfb4afea5bae9efc2dcd1a0..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/dateutil/_common.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Common code used in multiple modules. -""" - - -class weekday(object): - __slots__ = ["weekday", "n"] - - def __init__(self, weekday, n=None): - self.weekday = weekday - self.n = n - - def __call__(self, n): - if n == self.n: - return self - else: - return self.__class__(self.weekday, n) - - def __eq__(self, other): - try: - if self.weekday != other.weekday or self.n != other.n: - return False - except AttributeError: - return False - return True - - def __hash__(self): - return hash(( - self.weekday, - self.n, - )) - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] - if not self.n: - return s - else: - return "%s(%+d)" % (s, self.n) - -# vim:ts=4:sw=4:et diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/typing/tensor/video/video_tensor.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/typing/tensor/video/video_tensor.py deleted file mode 100644 index fa4fbb47d6b045b7618f04a1ff35a257aff9a1da..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/typing/tensor/video/video_tensor.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Union - -from docarray.typing.tensor.video.video_ndarray import VideoNdArray -from docarray.utils._internal.misc import is_tf_available, is_torch_available - -torch_available = is_torch_available() -if torch_available: - from docarray.typing.tensor.video.video_torch_tensor import VideoTorchTensor - - -tf_available = is_tf_available() -if tf_available: - from docarray.typing.tensor.video.video_tensorflow_tensor import ( - VideoTensorFlowTensor as VideoTFTensor, - ) - -if tf_available and torch_available: - VideoTensor = Union[VideoNdArray, VideoTorchTensor, VideoTFTensor] # type: ignore -elif tf_available: - VideoTensor = Union[VideoNdArray, VideoTFTensor] # type: ignore -elif torch_available: - VideoTensor = Union[VideoNdArray, VideoTorchTensor] # type: ignore -else: - VideoTensor = Union[VideoNdArray] # type: ignore diff --git a/spaces/Superlang/ImageProcessor/annotator/oneformer/oneformer/modeling/pixel_decoder/ops/make.sh b/spaces/Superlang/ImageProcessor/annotator/oneformer/oneformer/modeling/pixel_decoder/ops/make.sh deleted file mode 100644 index ca5c0b469da786c847ba04d437bb31ee0fc938da..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/oneformer/oneformer/modeling/pixel_decoder/ops/make.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash -# ------------------------------------------------------------------------------------------------ -# Deformable DETR -# Copyright (c) 2020 SenseTime. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 [see LICENSE for details] -# ------------------------------------------------------------------------------------------------ -# Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0 -# ------------------------------------------------------------------------------------------------ - -# Copyright (c) Facebook, Inc. and its affiliates. -# Modified by Bowen Cheng from https://github.com/fundamentalvision/Deformable-DETR - -FORCE_CUDA=1 python setup.py build install diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/configs/_base_/default_runtime.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/configs/_base_/default_runtime.py deleted file mode 100644 index b564cc4e7e7d9a67dacaaddecb100e4d8f5c005b..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/configs/_base_/default_runtime.py +++ /dev/null @@ -1,14 +0,0 @@ -# yapf:disable -log_config = dict( - interval=50, - hooks=[ - dict(type='TextLoggerHook', by_epoch=False), - # dict(type='TensorboardLoggerHook') - ]) -# yapf:enable -dist_params = dict(backend='nccl') -log_level = 'INFO' -load_from = None -resume_from = None -workflow = [('train', 1)] -cudnn_benchmark = True diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/ops/contour_expand.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/ops/contour_expand.py deleted file mode 100644 index ea1111e1768b5f27e118bf7dbc0d9c70a7afd6d7..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/ops/contour_expand.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import numpy as np -import torch - -from ..utils import ext_loader - -ext_module = ext_loader.load_ext('_ext', ['contour_expand']) - - -def contour_expand(kernel_mask, internal_kernel_label, min_kernel_area, - kernel_num): - """Expand kernel contours so that foreground pixels are assigned into - instances. - - Arguments: - kernel_mask (np.array or Tensor): The instance kernel mask with - size hxw. - internal_kernel_label (np.array or Tensor): The instance internal - kernel label with size hxw. - min_kernel_area (int): The minimum kernel area. - kernel_num (int): The instance kernel number. - - Returns: - label (list): The instance index map with size hxw. - """ - assert isinstance(kernel_mask, (torch.Tensor, np.ndarray)) - assert isinstance(internal_kernel_label, (torch.Tensor, np.ndarray)) - assert isinstance(min_kernel_area, int) - assert isinstance(kernel_num, int) - - if isinstance(kernel_mask, np.ndarray): - kernel_mask = torch.from_numpy(kernel_mask) - if isinstance(internal_kernel_label, np.ndarray): - internal_kernel_label = torch.from_numpy(internal_kernel_label) - - if torch.__version__ == 'parrots': - if kernel_mask.shape[0] == 0 or internal_kernel_label.shape[0] == 0: - label = [] - else: - label = ext_module.contour_expand( - kernel_mask, - internal_kernel_label, - min_kernel_area=min_kernel_area, - kernel_num=kernel_num) - label = label.tolist() - else: - label = ext_module.contour_expand(kernel_mask, internal_kernel_label, - min_kernel_area, kernel_num) - return label diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmseg/ops/encoding.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/mmseg/ops/encoding.py deleted file mode 100644 index 7eb3629a6426550b8e4c537ee1ff4341893e489e..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmseg/ops/encoding.py +++ /dev/null @@ -1,74 +0,0 @@ -import torch -from torch import nn -from torch.nn import functional as F - - -class Encoding(nn.Module): - """Encoding Layer: a learnable residual encoder. - - Input is of shape (batch_size, channels, height, width). - Output is of shape (batch_size, num_codes, channels). - - Args: - channels: dimension of the features or feature channels - num_codes: number of code words - """ - - def __init__(self, channels, num_codes): - super(Encoding, self).__init__() - # init codewords and smoothing factor - self.channels, self.num_codes = channels, num_codes - std = 1. / ((num_codes * channels)**0.5) - # [num_codes, channels] - self.codewords = nn.Parameter( - torch.empty(num_codes, channels, - dtype=torch.float).uniform_(-std, std), - requires_grad=True) - # [num_codes] - self.scale = nn.Parameter( - torch.empty(num_codes, dtype=torch.float).uniform_(-1, 0), - requires_grad=True) - - @staticmethod - def scaled_l2(x, codewords, scale): - num_codes, channels = codewords.size() - batch_size = x.size(0) - reshaped_scale = scale.view((1, 1, num_codes)) - expanded_x = x.unsqueeze(2).expand( - (batch_size, x.size(1), num_codes, channels)) - reshaped_codewords = codewords.view((1, 1, num_codes, channels)) - - scaled_l2_norm = reshaped_scale * ( - expanded_x - reshaped_codewords).pow(2).sum(dim=3) - return scaled_l2_norm - - @staticmethod - def aggregate(assignment_weights, x, codewords): - num_codes, channels = codewords.size() - reshaped_codewords = codewords.view((1, 1, num_codes, channels)) - batch_size = x.size(0) - - expanded_x = x.unsqueeze(2).expand( - (batch_size, x.size(1), num_codes, channels)) - encoded_feat = (assignment_weights.unsqueeze(3) * - (expanded_x - reshaped_codewords)).sum(dim=1) - return encoded_feat - - def forward(self, x): - assert x.dim() == 4 and x.size(1) == self.channels - # [batch_size, channels, height, width] - batch_size = x.size(0) - # [batch_size, height x width, channels] - x = x.view(batch_size, self.channels, -1).transpose(1, 2).contiguous() - # assignment_weights: [batch_size, channels, num_codes] - assignment_weights = F.softmax( - self.scaled_l2(x, self.codewords, self.scale), dim=2) - # aggregate - encoded_feat = self.aggregate(assignment_weights, x, self.codewords) - return encoded_feat - - def __repr__(self): - repr_str = self.__class__.__name__ - repr_str += f'(Nx{self.channels}xHxW =>Nx{self.num_codes}' \ - f'x{self.channels})' - return repr_str diff --git a/spaces/Superlang/ImageProcessor/annotator/zoe/zoedepth/models/base_models/midas_repo/ros/midas_cpp/scripts/listener.py b/spaces/Superlang/ImageProcessor/annotator/zoe/zoedepth/models/base_models/midas_repo/ros/midas_cpp/scripts/listener.py deleted file mode 100644 index 6927ea7a83ac9309e5f883ee974a5dcfa8a2aa3b..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/zoe/zoedepth/models/base_models/midas_repo/ros/midas_cpp/scripts/listener.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import print_function - -import roslib -#roslib.load_manifest('my_package') -import sys -import rospy -import cv2 -import numpy as np -from std_msgs.msg import String -from sensor_msgs.msg import Image -from cv_bridge import CvBridge, CvBridgeError - -class video_show: - - def __init__(self): - self.show_output = rospy.get_param('~show_output', True) - self.save_output = rospy.get_param('~save_output', False) - self.output_video_file = rospy.get_param('~output_video_file','result.mp4') - # rospy.loginfo(f"Listener - params: show_output={self.show_output}, save_output={self.save_output}, output_video_file={self.output_video_file}") - - self.bridge = CvBridge() - self.image_sub = rospy.Subscriber("midas_topic", Image, self.callback) - - def callback(self, data): - try: - cv_image = self.bridge.imgmsg_to_cv2(data) - except CvBridgeError as e: - print(e) - return - - if cv_image.size == 0: - return - - rospy.loginfo("Listener: Received new frame") - cv_image = cv_image.astype("uint8") - - if self.show_output==True: - cv2.imshow("video_show", cv_image) - cv2.waitKey(10) - - if self.save_output==True: - if self.video_writer_init==False: - fourcc = cv2.VideoWriter_fourcc(*'XVID') - self.out = cv2.VideoWriter(self.output_video_file, fourcc, 25, (cv_image.shape[1], cv_image.shape[0])) - - self.out.write(cv_image) - - - -def main(args): - rospy.init_node('listener', anonymous=True) - ic = video_show() - try: - rospy.spin() - except KeyboardInterrupt: - print("Shutting down") - cv2.destroyAllWindows() - -if __name__ == '__main__': - main(sys.argv) \ No newline at end of file diff --git a/spaces/TRI-ML/risk_biased_prediction/README.md b/spaces/TRI-ML/risk_biased_prediction/README.md deleted file mode 100644 index f8981c7c45d4667dd834366ace62354a072d364d..0000000000000000000000000000000000000000 --- a/spaces/TRI-ML/risk_biased_prediction/README.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: "RAP: Risk-Aware Prediction" -emoji: 🚙 -colorFrom: red -colorTo: gray -sdk: gradio -sdk_version: 3.8 -app_file: app.py -pinned: false -language: - - Python -thumbnail: "url to a thumbnail used in social sharing" -tags: -- Risk Measures -- Forecasting -- Safety -- Human-Robot Interaction -license: cc-by-nc-4.0 -arxiv: 2210.01368 - ---- - -# License statement - -The code is provided under a Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. Under the license, the code is provided royalty free for non-commercial purposes only. The code may be covered by patents and if you want to use the code for commercial purposes, please contact us for a different license. - -# RAP: Risk-Aware Prediction - -This is the official code for [RAP: Risk-Aware Prediction for Robust Planning](https://arxiv.org/abs/2210.01368). You can test the results in [our huggingface demo](https://huggingface.co/spaces/TRI-ML/risk_biased_prediction) and see some additional experiments on the [paper website](https://sites.google.com/view/corl-risk/). - -![A planner reacts to low-probability events if they are dangerous, biasing the predictions to better represent these events helps the planner to be cautious.](image/illustration.png) - -We define and train a trajectory forecasting model and bias its prediction towards risk such that it helps a planner to estimate risk by producing the relevant pessimistic trajectory forecasts to consider. - -## Datasets -This repository uses two datasets: - - A didactic simulated environement with a single vehicle at constant velocity and a single pedestrian. - Two pedestrian behavior are implemented: fast and slow. At each step, pedestrians might walk at their favored speed or at the other speed. - This produces a distribution of pedestrian trajectories with two modes. The dataset is automatically generated and used. You can change the parameters of the data generation in "config/learning_config.py" - - The Waymo Open Motion Dataset (WOMD) with complex real scenes. - - -## Forecasting model -A conditional variational auto-encoder (CVAE) model is used as the base pedestrian trajectory predictor. Its latent space is quantized or gaussian depending on the parameter that you set in the config. It uses either multi-head attention or a modified version of context gating to account for interactions. Depending on the parameters, the trajectory encoder and decoder can be set to MLP, LSTM, or maskedLSTM. - -# Usage - -## Installation - -- (Set up a virtual environment with python>3.7) -- Install the packge with `pip -e install .` - -## Setting up the data - -### Didactic simulation - - The dataset is automatically generated and used. You can change the parameters of the data generation in "config/learning_config.py" - -### WOMD - - [Download the Waymo Open Motion Dataset (WOMD)](https://waymo.com/open/) - - Pre-process it as follows: - - Sample set: `python scripts/scripts_utils/generate_dataset_waymo.py /scenario/validation /interactive_veh_type/sample --num_parallel=<16> --debug_size=<1000>` - - Training set: `python scripts/interaction_utils/generate_dataset_waymo.py /scenario/training /interactive_veh_type/training --num_parallel=<16>` - - Validation set: `python scripts/interaction_utils/generate_dataset_waymo.py /scenario/validation_interactive /interactive_veh_type/validation --num_parallel=<16>` - - Replace the arguments: - - `` with the path where you downloaded WOMD - - `<16>` with the number of cores you want to use - - `<1000>` with the number of scene to process for the sample set (some scenes are filtered out so the resulting number of pre-processed scenes might be about the third of the input number) - - Set up the path to the dataset in "risk_biased/config/paths.py" - -## Configuration and training - -- Set up the output log path in "risk_biased/config/paths.py" -- You might need to login to wandb with `wandb login